【问题标题】:Customizing new trading strategy in R using quantmod使用 quantmod 在 R 中自定义新的交易策略
【发布时间】:2014-02-04 20:44:50
【问题描述】:

我想为 R 中的股票代码创建一个新的自定义 TA 指标。但我不知道如何将我的 SQL 条件策略转换为 R 自定义函数并将其添加到 R 中的 ChartSeries。

问题列在下面的代码中作为解释。

library("quantmod")
library("FinancialInstrument")
library("PerformanceAnalytics")
library("TTR")


stock <- getSymbols("002457.SZ",auto.assign=FALSE,from="2012-11-26",to="2014-01-30")   
head(stock)

chartSeries(stock, theme = "white", subset = "2013-07-01/2014-01-30",TA = "addSMA(n=5,col=\"gray\");addSMA(n=10,col=\"yellow\");
            addSMA(n=20,col=\"pink\");addSMA(n=30,col=\"green\");addSMA(n=60,col=\"blue\");addVo()")

问题:如何重写下面的代码以使其在 R 中作为函数可用?

#Signal Design
#Today's volume is the lowset during the last 20 trading days
lowvolume <- VOL<=LLV(VOL,20);

#seveal moving average lines stick together
X1:=ABS(MA(C,10)/MA(C,20)-1)<0.01;
X2:=ABS(MA(C,5)/MA(C,10)-1)<0.01;
X3:=ABS(MA(C,5)/MA(C,20)-1)<0.01;

#If the follwing condition is satisfied, then the signal appears
MA(C,5)>REF(MA(C,5),1) AND X1 AND X2 AND X3 AND lowvolume;

#Convert the above SQL code into the following R custom function
VOLINE <- function(x) {

    }

#Create a new TA function for the chartseries and then add it up.
addVoline <- newTA(FUN=VOLINE,
                  + preFUN=Cl,
                  + col=c(rep(3,6),
                          + rep(”#333333”,6)),
                                + legend=”VOLINE”)

【问题讨论】:

    标签: sql r quantmod quantstrat


    【解决方案1】:

    我认为在这种情况下你不需要 sql

    试试这个

    require(quantmod)
    
    # fetch the data 
    s <- get(getSymbols('yhoo'))
    
    # add the indicators
    s$ma5 <- SMA(Cl(s) ,5)
    s$ma10 <- SMA(Cl(s) ,10)
    s$ma20 <- SMA(Cl(s) ,20)
    s$llv <- rollapply(Vo(s), 20, min)
    
    # generate the signal 
    s$signal <- (s$ma10 / s$ma20 - 1 < 0.01 & s$ma5 / s$ma10 - 1 < 0.01 & s$ma5 / s$ma20 - 1 < 0.01 & Vo(s) == s$llv)
    
    # draw 
    chart_Series(s)
    add_TA(s$signal == 1, on = 1, col='red')
    

    我不确定 REF 是什么意思,但我相信您可以自己完成。

    这是输出(我似乎无法上传照片,但您会看到一个带有水平线的图表,其中信号 eq 1)

    【讨论】:

    • 如果我改变最后一个代码,像这样:x
    • 你想做什么?如果不久前被问到关于在 quantmod 图表中绘制水平线并从包的创建者那里得到答案 - 可能 this 会帮助你。
    【解决方案2】:

    sqldf 包中将该函数用作sqldf() 的包装器。 sqldf() 的参数将是包含数据的数据框上的 select 语句。

    可以在Burns Statistics找到一个很好的教程。

    【讨论】:

    • 谢谢,但我真的很想在满足所有条件时添加多个信号。就像在 quantmod 中一样,“signal1 = slowMA”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多