我需要一些帮助,让我的代码正常工作。我试图创造一个简单的位置信号,基于收盘价高于MACD,Bollinger波段,和缓慢的预测。我在第17行上有错误。我不确定这是否因为"Stock“是xts对象。最后,我也想绘制输出图。谢谢!
#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))发布于 2015-05-03 02:40:30
正如Pascal在上面的评论中提到的,MACD使用了一个单变量对象。这个对象应该是收盘价(除非您想要其他东西),这是HLC(Stock)中名为CAT.Close的第三列。Stock$stochOSC没有工作,因为列名指定错误(CAT )。应在“高”、“低”和“关”之前添加)。最后,&应该分离ifelse的多个条件(注意问题(ck而不是ch)中Stock$stochOSC中的错误)。
以下是代码:
#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))您应该得到以下情节:

https://stackoverflow.com/questions/29981193
复制相似问题