I would like to use indicators of timeframes different to the data I am using. I have seen this asked a few time but no solutions as of yet (at least for me anyway).
The below example uses daily stock data however the actual project uses intraday currency data. I have an easy work around for importing the intraday csv data now so the example and real-world should be interchangeable enough.
library(quantstrat)
initDate="2000-01-01"
from="2003-01-01"
to="2016-12-31"
#set account currency and system timezone
currency('USD')
Sys.setenv(TZ="UTC")
#get data
symbols <- "SPY"
getSymbols(symbols, from=from, to=to, src="yahoo", adjust=TRUE)
stock(symbols, "USD")
#trade sizing and initial equity settings
tradeSize <- 100000
initEq <- tradeSize*length(symbols)
#set up the portfolio, account and strategy
strategy.st <- portfolio.st <- account.st <- "mtf.strat"
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, currency='USD',initEq=initEq)
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)
#SMA length
nSMA <- 14
Adding the SMA as, in this case a daily indicator works a treat
add.indicator(strategy.st, name="SMA",
arguments=list(x=quote(Cl(mktdata)), n=nSMA, maType = "SMA"),
label="SMA")
test <- applyIndicators(strategy.st, mktdata=OHLC(SPY))
Yet trying to add, in this case a weekly SMA
add.indicator(strategy.st, name="SMA",
arguments=list(x=quote(to.period(Cl(mktdata), period = "weeks", k = 1, indexAt = "startof")), n=nSMA, maType = "SMA"),
label="SMAw1")
## Or this
add.indicator(strategy.st, name="SMA",
arguments=list(x=quote(to.weekly(Cl(mktdata))), n=nSMA, maType = "SMA"),
label="SMAw1")
test <- applyIndicators(strategy.st, mktdata=OHLC(SPY))
# Error in runSum(x, n) : ncol(x) > 1. runSum only supports univariate 'x'
Calling the Close column directly without Cl(x)
results in the same error. I did this as TTR:::runSum
will throw the above error if given more than one column of data.
I'm not entirely sure what the problem is so some assistance would be great.
to.period()
. Is there a way to useendpoints()
either these periods or would it be easier to modify your solution to useto.period()
– Catto