Search code examples
rquantmodstockstechnical-indicator

How do you use stock tickers and for-loops together in R for technical analysis?


I am having trouble finding stock technical indicators using a for-loop to loop through stocks.

Below I am using 10 stocks and am trying to see (through the output) if the current 10 day moving average (MA) for each stock is above, below, or at the current stock price.

library(quantmod) # also loads xts and TTR
ticker = c("GD","BA","ALV","AGU","MOS","POT","MON","CF","BG","SQM") 
#10 ticker symbols that I want to find the 10 day MA of

z<-1 # z starts with a value of 1
for ( z in 1:10) { 
  myStock<-getSymbols(ticker[z])  
#gets the z'th stock ticker are puts in into variable myStock
  stock_ts = ts(myStock$myStock.Adjusted)

##Moving Average Calculations back 10 steps using TTR:  
  #SMA(stock_ts, n=10)
  x<- length(stock_ts)
  y <- 0
  averagediv <- 10
  for ( i in (x-9):x) {
    y <- y + stock_ts[i]
  }

  ma10 <- y/averagediv

  print(ticker[z])
  if(ma10 <  stock_ts[x]) {
      print(mySP)
      print ("green")
      finalMA<-"green"
  } else if (ma10 > stock_ts[x]) {
      print(mySP)
      print ("red")
      finalMA<-"red"
  } else {
      print(mySP)
      print("even")
      finalMA<-"even"
  }
}

The code does not successfully run because myStock$myStock.Adjusted does not run correctly. I am pretty sure that the variable myStock only holds the stock ticker (AAPL, for example), not the actual stock information with the highs, lows, open, close prices and such.

My 10-Day MA Code works perfectly to my knowledge for individual stocks, just not with the for loop. For instance the code:

...
getSymbols("AAPL")  
stock_ts = ts(AAPL$AAPL.Adjusted)
##Moving Average Calculations back 10 steps using TTR:
...

I plan to add more tickers and more complex analysis to this code. Hence, listing out all the code for each stock is not a very viable or efficient solution.

Thanks for your help.


Solution

  • No need to manually calculate Moving Averages. quant mod/TTR has a whole array of different MAs. (SMA,EMA,WMA …) ? is your friend :-). With just a few lines you can attach MAs to your symbols and chart, compare to the current price or do whatever you like. i.e. a simple 10day MA using the adjusted closings:

    tickers <- c('GE','IBM')
    getSymbols(tickers, from = '2016-01-01')
    smas <- lapply(1:length(tickers),function(x) SMA(get(tickers[x])[,6],10))
    stocks <- lapply(1:length(tickers), function(x) cbind(get(tickers[x]),smas[[x]][,1]))
    names(stocks) <- tickers
    

    All stocks are in a list now and you can access them like so: i.e. to get GE

    > tail(stocks$GE)
               GE.Open GE.High GE.Low GE.Close GE.Volume GE.Adjusted    SMA
    2016-08-08   31.30   31.40  31.21    31.27  20434100       31.27 31.219
    2016-08-09   31.23   31.35  31.15    31.30  20108800       31.30 31.202
    2016-08-10   31.25   31.34  31.20    31.27  18538100       31.27 31.201
    2016-08-11   31.31   31.37  31.20    31.29  37986200       31.29 31.205
    2016-08-12   31.20   31.28  31.18    31.24  21327000       31.24 31.215
    2016-08-15   31.30   31.35  31.22    31.24  19546600       31.24 31.224
    

    If you want to convert the list back to individual named xts-objects you can use the list2env function.