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.