2

我想为 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”)
4

2 回答 2

2

在这种情况下,我认为您不需要 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)

于 2014-02-05T06:58:56.533 回答
0

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

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

于 2014-02-04T20:58:30.153 回答