Search code examples
rfinancequantmodtradingalgorithmic-trading

R Quant Trading


I could use some help getting my code to work properly. I am trying to create a simple position signal based on the closing price being higher than the MACD, Bollinger Bands, and the Slow Stochastics. I am getting errors on line 17 onwards. I am not sure if this is because "Stock" is an xts object or not. I would like to graph the output in the end as well. Thanks!

#install.packages("quantmod")
library("quantmod")
#install.packages("FinancialInstrument")
library("FinancialInstrument")
#install.packages("PerformanceAnalytics")
library("PerformanceAnalytics")
#install.packages("TTR")
library("TTR")

#######################################

Stock <- get(getSymbols('CAT'))["2014::"]

# add the indicators
Stock$BBands <- BBands(HLC(Stock))
Stock$MACD <- MACD(HLC(Stock))
Stock$stochOSC <- stoch(Stock[,c("High","Low","Close")])
Stock$position <- ifelse(Cl(Stock) > Stock$BBands > Stock$MACD > Stock   $stockOSC , 1 , -1)

Gains <- lag(Stock$position) * dailyReturn(Stock)
charts.PerformanceSummary(cbind(dailyReturn(Stock),Gains))

Solution

  • As Pascal mentioned in his above comment, MACD uses a univariate object. This object should be the closing price (unless you want something else) which is the third column in the HLC(Stock) named CAT.Close. The Stock$stochOSC didn't work because column names specified wrongly (CAT. should be added before High, Low and Close). Finally, & should separate multiple conditions of ifelse (note the typo in Stock$stochOSC in the question (ck instead of ch)).

    Here is the code:

    #install.packages("quantmod")
    library("quantmod")
    #install.packages("FinancialInstrument")
    library("FinancialInstrument")
    #install.packages("PerformanceAnalytics")
    library("PerformanceAnalytics")
    #install.packages("TTR")
    library("TTR")
    
    #######################################
    
    Stock <- get(getSymbols('CAT'))["2014::"]
    
    # add the indicators
    Stock$BBands <- BBands(HLC(Stock))
    Stock$MACD <- MACD(HLC(Stock)[,3])
    Stock$stochOSC <- stoch(Stock[,c("CAT.High","CAT.Low","CAT.Close")])
    Stock$position <- ifelse(Cl(Stock)>Stock$BBands & Stock$BBands >Stock$MACD & Stock$MACD > Stock$stochOSC , 1 , -1)
    
    Gains <- lag(Stock$position) * dailyReturn(Stock)
    charts.PerformanceSummary(cbind(dailyReturn(Stock),Gains))
    

    You should get the following plot:

    enter image description here