Question

I want to create a new custom TA-indicator to the stock symbol in R. But I have no idea about how to convert my SQL conditional strategy into R self-defined function and add it up to the ChartSeries in R.

The question are listed in the following code as the explanation.

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()")

Question: How can I rewrite the code below to make it available as a function in 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”)
Was it helpful?

Solution

I dont think you need sql in this case

Try this

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')

I'm not sure what REF means but i'm sure you can do that by your self.

This is the output (i cant seem to upload the photo but you see a chart with horizontal lines where signal eq 1)

OTHER TIPS

Use the function as a wrapper for sqldf() in the sqldf package. The argument to sqldf() will be a select statement on the data frame that has the data.

A good tutorial for this can be found at Burns Statistics.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top