Thursday, 28 September 2017

Set Operations in R

After a fairly long break, we are back to writing interesting insights on data and related areas. The focus of this short post is on the set operations in R. Set operations are useful when we have to find out, say, common elements between two sets of data or need the elements of one set of data not present in another set of data. We will consider a few functions in R that can be of immense help in data analysis.

To illustrate the functions, we use two sets of vectors called p and q defined as follows:









Unique() function gives the unique elements in a vector. Let us use this function on p and q to fetch the unique elements as shown below:







As can be seen, unique function on p and q results in distinct elements and duplicates are discarded. To get the union of elements in p and q, we use the union function as below:






Note that the union of p and q results in distinct elements from p and q. Next, we look at intersect function that returns in common elements between the two sets under consideration.







setdiff function returns the elements of the first set not present in the second set. setdiff is like minus operation in a relational database. Unlike union or intersect where the order of the dataset does not matter, in the case of setdiff, it matters.







Note again that the setdiff returns only distinct elements.

We can create a custom setdiff function that returns duplicates as shown below:






To see if two vectors are identical we can use setequal as shown below:







setequal returns false in the first case as p and q are not equal and true in the second case as p is same as p.

is.element returns TRUE or FALSE based on whether the element in the first dataset is present in the second dataset or not. It is same as %in%  operator. The is.element is shown below:






The last function we discuss is choose. choose(n,r) is the same as nCr defined in Combinatorics. choose returns the binomial coefficient. In other words, choose(n,r) returns the number of possible subsets of size r chosen from n elements. Examples are shown below:











Friday, 23 June 2017

Statistical Functions in Excel I


In the first post of Statistical Functions in Excel, we will cover a part of the functions that can be used for statistical analysis available in Excel. While there are several functions with a variety of functionality, we will focus on Statistical functions only in this post. It is assumed that the reader will know basics of Statistics and Like before, we will explore these functions in Excel 2016.


Let's take a quick look at some of these functions that are available OOTB on the Status Bar.












If we enter 1 to 4 in cells as shown above and select them, then, we see the Average, Count and Sum shown on the Status Bar on the right bottom of the window. We can customize the measures shown in the Status Bar by right clicking anywhere on the Status Bar and, then, clicking Numerical Count, Minimum and Maximum from the Menu Items shown. This is shown below:




















If we wish to add any more functions, then, we can add the functions in the Status Bar using VBA. But, that is a story for another day. Continuing with the above Menu Items figure, we see above that Average, Count, and Sum are checked. So, we see them in the Status Bar once we select cells containing numbers. Once we click Numerical Count, Minimum and Maximum, we see a tick against these measures as shown below:




















To confirm that these measures appear on the Status Bar, we can select cells as shown below and see that the corresponding measures are shown:












Count gives the count of all cells selected while Numerical Count gives the count of all cells containing numbers only. Min and Max give the minimum and maximum of the selected numbers. Now, that we have seen the OOTB functionality, let us quickly see the Statistical functions in alphabetical order:

AVEDEV: Calculates the average of the absolute deviations of data points from their mean. Mathematically, it can be written as shown below where x is a It can take numbers in the form of arguments, but not exceeding 255 in count, like, AVEDEV(1,2,3,4) that will return 1. If more than 255 arguments are passed, then, we get below error:









A work around is to use enter these values in cells and use cell range like, AVEDEV(A1:A2000). This is applicable to many of the statistical functions that we shall see shortly.

AVERAGE: Calculates the average. We can select cells and, then, insert numbers as shown below:



The result of the function is 2.5 and that compares well with the value in the Status bar as shown below:














AVERAGEA: Calculates the average like the AVERAGE function, but with a twist. While AVERAGE ignores any text, AVERAGEA counts any text as a member contributing zero to the sum. This is clearly seen below where for the selection below, AVERAGE returns 2.5 and AVERAGEA returns 2.222222222.









For the selection below, AVERAGE function returns the same value 2.5 whereas AVERAGEA returns a different value because boolean values are treated as numbers by AVERAGEA. TRUE is treated as 1 and FALSE as 0.








AVERAGEIF: Calculates the average of contents in a range of cells based on some criteria. Example is shown below:













Only those value that qualify the condition that value is not equal to 2 or 3.

AVERAGEIFS: Similar to above function. But, we can give multiple criteria. Example is shown below:











CORREL: Calculates the correlation of two arrays containing the same number of elements. Example is show below:













COUNT: Calculates the number of cells having numbers only. See example below:














COUNTA: Calculates the number of cells having any content. See example below:














The reason COUNTA returns 5 is because cell E4 has a blank space.

COUNTBLANK: Calculates the number of blanks in the cells. See example below:















Following from the last example, result is 1 because cell E4 has a blank space.

COUNTIF: Calculates the number of cells having a content based on a condition like we saw in the case of AVERAGEIF. See example below:














The number of cells containing FOO is counted here.

COUNTIFS: Similar to COUNTIF, but based on more than one condition like AVERAGEIFS.

COVARIANCE.P: Calculates the covariance of a population. See example below:











COVARIANCE.P: Calculates the covariance of a sample. See example below:











DEVSQ: Calculates the sum of the squares of the deviations from the average  See example below:













FORECAST, FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.ETS.STAT, and FORECAST.LINEAR are functions that can be used for prediction analysis where future data can be predicted based on historical values.

FREQUENCY: is a wonderful function that can be used to classify raw data into bins. As an example, see below numbers where numbers 1 to 9 and they are classified to 4 bins:

less than 3;
between 3 and 6;
between 6 and 9;
greater than 9;



















Enter the formula as shown below:


















On pressing Enter, the function returns 3 that is in the first bin (less than 3). To get the number of elements in the other bins, after selecting the cell containing the function, drag the selection down such that the selection equals the number of bin. Here, since there are 4 bins, we select 3 cells below the cell containing the function as shown below:


















Once this is done, then, click on F2 and, then, CTRL+Shift+Enter. This will populate the selected cells with the number of elements as shown below:


















GEOMEAN: Calculates the geometric mean of an array of numbers. See example below:











GROWTH: Predicts a value based on the assumption that the growth is exponential.

HARMEAN: Calculates the harmonic mean of an array of numbers. See example below:











INTERCEPT: Calculates the point at which a line will intersect the y-axis when given existing y values and x values. See example below:












KURT: Calculates the kurtosis of an array. See example below:
















LINEST: is a line fitting function and calculates the best straight line.

LOGEST: is a curve fitting function and calculates the best exponential curve.

MAX: Calculates the maximum value from an array of numbers. See example below:














MAXA: Calculates the maximum value from any array of numbers, strings and boolean values.

MAXIFS: Calculates the maximum value in an array of numbers based on a criteria.

MEDIAN: Calculates the median of an array of numbers. See example below:















The rest of the functions will be covered in a following post.

Friday, 12 May 2017

Addition of Graph to Backtesting in R

After the first post on backtesting a trading strategy in Excel, we followed it up by another post that added a graph in Excel to make it more meaningful. Later, we replicated this trading strategy in R. In this post, we will add a graph showing SMA and LMA versus time in R like we had done in the case of Excel.

We will add a line to the earlier function that we wrote in the last post. This line will return the dataframe that is calculated by the function. We need this data frame as this data frame contains the SMA and LMA values that are needed for plotting the graph in R. The line is 
return(data_frame) added just before the close of the function as shown in bold below:

MovingAverageStrategy <- function(file,SMAStart,LMAStart,TradeStart)
{

# read the downloaded .csv file
data_frame <- read.table(file,sep=",", header=TRUE)
ntotal = nrow(data_frame)

# initialize the new columns
data_frame$TradeSignal = ""
data_frame$TradePrice = 0
data_frame$Return = 0

# for loop to calculate SMA, LMA, TradeSignal, TradePrice, Return 
for (i in 1:ntotal){
  if(i>=SMAStart){
    data_frame$SMA[i] = mean(data_frame$Close[(i-(SMAStart-1)):i])
  }
  if(i>=LMAStart){
    data_frame$LMA[i] = mean(data_frame$Close[(i-(LMAStart-1)):i])
  }
  if(i>=TradeStart){
    data_frame$TradeSignal[i] = ifelse((data_frame$SMA[i-1]<data_frame$LMA[i-1])&&(data_frame$SMA[i]>data_frame$LMA[i]),"BUY",ifelse((data_frame$SMA[i-1]>data_frame$LMA[i-1])&&(data_frame$SMA[i]<data_frame$LMA[i]),"SELL",""))

    data_frame$TradePrice[i] = ifelse(data_frame$TradeSignal[i-1] != "",data_frame$Open[i],data_frame$TradePrice[i-1])

    data_frame$Return[i] = 100*ifelse((data_frame$TradeSignal[i-1] != "")&&(data_frame$TradePrice[i-1] != 0),ifelse( data_frame$TradeSignal[i-1] == "BUY",1-(data_frame$TradePrice[i]/data_frame$TradePrice[i-1]),(data_frame$TradePrice[i]/data_frame$TradePrice[i-1])-1),0)
      }
}

# Trade Calculations
TotalReturns=as.numeric(data_frame$Return)
TotalReturns = sum(TotalReturns)
Positive_trades=length(data_frame$Return[data_frame$Return>0])
Negative_trades=length(data_frame$Return[data_frame$Return<0])
no_of_trades=Positive_trades + Negative_trades

Metrics = c("Positive trades","Negative trades","No.of Trades","Total Return")
Values = c(Positive_trades,Negative_trades,no_of_trades,paste(round(TotalReturns,digits=4),"%",sep=""))
tsummary = data.frame(Metrics,Values)
tsummary
return(data_frame)
}

After the above function has been modified and run, the following command is run to fetch the values of the calculation into a data frame.

data_frame <- MovingAverageStrategy("D:\\blog\\apple_data.csv",5,20,2)

Note that the first column containing dates. But, R may not recognize it as being of type Date. So, let us cast it using below command, else, we might end up an absurd graph otherwise. We use below command:

data_frame[,1] = as.Date(data_frame[,1],format='%d-%b-%y')

Once, this is run, we are ready to run the first draft of the graph using below command:

plot(data_frame[,1],data_frame[,7],col="dodgerblue", type="l",main="SMA & LMA versus Date",xlab="Date",ylab="SMA & LMA",lwd=2)

plot is used draw a graph. The argument, data_frame[,1], is Date column and values lie on the x-axis. data_frame[,7] argument contains the calculated SMA values and are the values on the y-axis. col parameter is set to color "dodgerblue". type is set to "l" so that a line is plotted. main parameter used is set to the title of the graph and is assigned a value, "SMA & LMA versus Date". xlab and ylab parameters are used to the titles for the x-axis and y-axis and are set to "Date" and "SMA & LMA", respectively. Lastly, lwd is line width and default value is 1. To make the line appear bold, the value of lwd is set to 2. Once above command is run, the following plot is seen:














To add LMA, we run below command:

lines(data_frame[,1],data_frame[,8],col="darkorange2",lwd=2)

The arguments are self-explanatory. We get the LMA line on the plot as shown below:














Once LMA is added, we just need to add the legend as shown by the command below:

legend("topleft",legend=c("SMA","LMA"),col=c("dodgerblue","darkorange2"),bg="white",lwd=2,cex=0.60)

The argument "topleft" specifies the position of the legend on the plot. The legend argument specifies the text and col specifies the color corresponding to the text. bg specifies the background color of the legend. lwd, like before specifies the line width and cex specifies the level of magnification of the legend of the text and symbols and is set to 0.60. The final plot is shown below:















The plot is identical to the one shown in the case of excel. With this comparison of graphs, we come to the end of this post.