1

I have multiple dataframes that contain stock market data in the form:

Open High Low Close Volume

I am trying to get an average (over a given period) of the last row of each stock and combine them into a single data frame like so:

Name SMA
StockA 15.1
StockB 34.44

I have a simple function that calculates the mean value and formats it correctly. It works on when I run it on a single stock (dataframe). However when I try and use lapply to apply the function to a list of all the dataframes, I get the error:

Error in x[,Close]: incorrect number of dimensions.

symbols is the list of all stock dataframes.

Any help would be greatly appreciated.

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU", "XLE", "XLP", "XLF", "XLB", "XLV", "XLY")
getSymbols(symbols, src='yahoo', from = '2016-01-01')

fun1<-function(x,Close) {
  mean1<-SMA(x[,Close],5)
  mean2<-tail(mean1,1)
  df_name<-deparse(substitute(x))
  print(mean2,paste(df_name))
}

df<-lapply(symbols,fun1)
final_df <- do.call(rbind, df)
trentcroad
  • 79
  • 1
  • 7
  • Please show a reproducible example. Regarding the average of last row of each stock, did you meant to extract the last row of each stock from each of the datasets and then do the average by stock? – akrun May 18 '16 at 05:09
  • Yes @akrun, it is just the average by stock, then it is extracted second. I'll update the example so it can be reproduced. – trentcroad May 18 '16 at 05:12
  • Thanks, Also, please do mention the packages used. – akrun May 18 '16 at 05:14
  • Hopefully the new example is clear. Thanks @akrun – trentcroad May 18 '16 at 05:23
  • You can check [here](http://stackoverflow.com/questions/24377590/getsymbols-downloading-data-for-multiple-symbols-and-calculate-returns) – akrun May 18 '16 at 05:56
  • 1
    Thank you @akrun this helped me find out what was wrong. Many thanks. – trentcroad May 18 '16 at 08:37

1 Answers1

0

The issue appeared to be that I was taking the last value (tail) of the running moving average (SMA) and also adding names within the function - prior to combining/merging the data frames. If this is all done after the dataframes have been merged, then it seems to work.

require(TTR)
require(quantmod)

symbols <- c("XLF", "XLK", "XLU", "XLE", "XLP", "XLF", "XLB", "XLV", "XLY")

StartDate = '2016-01-01'

Stocks = lapply(symbols, function(sym, column) {
  SMA(na.omit(getSymbols(sym, from=StartDate, auto.assign=FALSE))[,4],5)
})

test<-do.call(merge, Stocks)
test2<-tail(test,1)
test3<-t(test2)
rownames(test3)<-symbols
colnames(test3)<-"SMA"
View(test3)
trentcroad
  • 79
  • 1
  • 7