Quantstrat — First try
Background
I have been interested in stocks. It was like a sports to me. You pick a stock, invest and watch it perform. I always told myself that I was going to learn programming, if you look at my stackoverflow, you will see that I jumped around between many programming languages. Simply because, I didnt find anything interesting for me. For some reasons, I picked up R and now I am totally hooked. I realized that if I marry R to my interest in stocks, I can build some interesting projects. So, my journey has started.
Quantstrat
After a lot of research, I discovered Quantstrat. This was an easy library to play with. Great resources are available at Guy Yolin’s website. I picked Luxor strategy and ran back testing and ended up with the following graph. Its a small victory!
Lets get coding!
Before getting started, get yourself familiar with Luxor strategy. In simple words, we buy when the price is greater than 30 days rolling average and sell when the price is below the 30 days rolling average.
Setup library
#Setup library------------------------------------------------------
library("quantstrat")
For this particular experiment, we only require quantstrat library.
Get data! You cant do anything without the data. By default, the data source is yahoo.
# Get data for SPY for the year 2012
sym <- get(getSymbols("SPY"))["2012"]
mkData <- Cl(sym) #Store only the close price of the data
colnames(mkData) <- "Close" #Naming the column
Set the parameters early in the code (good habit)
#Set the parameters
initDate <- "2012-12-31" #Date of initiation
from <- "2013-01-01" #Start date of the data set
to <- "2013-01-30" #End date of the data set
initEq <- 1000 #Initial equity
Initiate portfolio, account and strategy — later on we will investigate conducting various strategy in various portfolio. For now we will focus on doing it all in one specific name.
#-------------------------Initiate portfolio and account-------------------------------------------
qs.strategy <- "qsFaber" #Name the strategyinitPortf(qs.strategy, "mkData", initDate = initDate) #Initiate portfolio
initAcct(qs.strategy, portfolios = qs.strategy, initDate = initDate, initEq = initEq) #Initiate account
initOrders(portfolio = qs.strategy, initDate = initDate) #Initiate accountstrategy(qs.strategy, store = TRUE) #Store all the events in the strategy
Add indicator — Indicator plays a vital role in the trading. This will add a column to our data table and we can use it later on to trigger buy or sell signal.
#-------------------------Add indicator-------------------
#Calculate the moving average for 30 periods
add.indicator(strategy = qs.strategy,
name = "SMA",
arguments = list (x = mkData$Close,
n = 30),
label = "SMA30"
)
Add signals — Based on indicators, we can add buy or sell signal. Signals will not execute the trade.
#-------------------------Add signals ---------------------
add.signal(qs.strategy,
name = "sigCrossover",
arguments = list(columns = c("Close", "SMA30"),
relationship = "gt"),
label = "Cl.gt.SMA")add.signal(qs.strategy,
name = "sigCrossover",
arguments = list(columns = c("Close", "SMA30"),
relationship = "lt"),
label = "Cl.lt.SMA")
Add.rule — In other words execute the order
#-------------------------Add rules to buy and sell ---------
#Buy 100 when the enter signal is triggered and sell all when the exit signal is triggered
add.rule(qs.strategy, name = "ruleSignal",
arguments = list(sigcol = "Cl.gt.SMA",
sigval = TRUE,
orderqty = 100,
ordertype = "market",
orderside = "long"),
type = "enter")add.rule(qs.strategy, name = "ruleSignal",
arguments = list (sigcol = "Cl.lt.SMA",
sigval = TRUE,
orderqty = "all",
ordertype = "market",
orderside = "long"),
type = "exit")
We are almost there — now we need to run the strategy and update the account, portfolio and equity.
#-------------------------Apply Strategy ------------
applyStrategy(strategy = qs.strategy, portfolios = qs.strategy)
getTxns(Portfolio = qs.strategy, Symbol = "mkData")#-------------------------Update portfolio, account and equity------------
updatePortf(qs.strategy)
updateAcct(qs.strategy)
updateEndEq(qs.strategy)
Plot — This will give us a visual on how our strategy performed over the course of years.
#-------------------------Plot performance-------------------
myTheme <- chart_theme()
myTheme$col$dn.col<-'lightblue'
myTheme$col$dn.border <- 'lightgray'
myTheme$col$up.border <- 'lightgray'chart.Posn(qs.strategy, Symbol = 'mkData', Dates = '2013::',theme=myTheme,
TA='add_SMA(n=10,col=4, on=1, lwd=2)')
That’s all we need at this time. Experiment the n size to see if we can increase the profit over the period of time. This is a simple trading strategy, as we progress forward we will add more complexity!