求书: How To Bacmydisktestt a Trading Strategy Using Excel By Mark Ursell PDF

How&to&backtest&a&strategy&in&R
March 26, 2011
This is the third post in the&&series and it will show how to backtest a
simple strategy in R.& It will follow the 4 steps
Damian outlined in his post on&.
Step 1: Get the data
The&getSymbols&function
in&&makes this step easy if you
can use daily data from&.& There are also "methods" (not in the
strict sense) to pull data from other sources (FRED, Google, Oanda,
R save files, databases, etc.).& You could also
use them as a template to write a custom function for a particular
vendor you use.
# run the command below if
quantmod isn't already installed
install.packages("quantmod")
# use the quantmod package (loads
TTR, xts, and zoo)
require(quantmod)
# pull SPX data from Yahoo
(getSymbols returns an xts object)
getSymbols("^GSPC")
Step 2: Create your indicator
The&&contains a multitude of
indicators.& The indicators are written to make it
easy to&.& Starting with revision 106 on R-forge,
TTR has a&.
# calculate DVI
DVI(Cl(GSPC))& # Cl() extracts the close price
Step 3: Construct your trading rule
Since this trading rule is simple--we're long 100% if the DVI is
below 0.5 and short 100% otherwise--it can be written in a single
line.& More elaborate rules and/or position
sizings can be done as well, but require more code (&is
an example of more complex position sizing
rules).& Also notice that the signal vector is
lagged, which avoids look-ahead bias.
# create signal: (long (short) if
DVI is below (above) 0.5)
# lag so yesterday's signal is
applied to today's returns
Lag(ifelse(dvi$dvi & 0.5, 1, -1))
Step 4: The trading rules/equity curve
As in Damian's example, the code below is a simplified approach
that is frictionless and does not account for
slippage.& The code below takes today's percentage
return and multiplies it by yesterday's signal / position size
(always +/- 100% in this example).& I also subset
the system returns to match the results in
# calculate signal-based
ROC(Cl(GSPC))*sig
# subset returns to match data in
Excel file
Step 5: Evaluate strategy performance
Damian mentioned the importance of evaluating your
strategy.& Fortunately for R users,
the&&makes this easy.&
With a few lines of code we can view the drawdowns, downside risks,
and a performance summary.
# use the PerformanceAnalytics
install.packages("PerformanceAnalytics")
require(PerformanceAnalytics)
# create table showing drawdown
statistics
table.Drawdowns(ret,
# create table of downside risk
table.DownsideRisk(ret)
# chart equity curve, daily
performance, and drawdowns
charts.PerformanceSummary(ret)
That's all there is to backtesting a simple strategy in
R.& It wasn't that intimidating, was
it?& Please leave feedback if you're moving your
backtesting from Excel to R and there's something you're hung up on
or you have an awesome tip you'd like to share.
Here's a succinct version of the code in the above post if you want
to be able to copy / paste it all in one block:
require(quantmod)
require(PerformanceAnalytics)
# Step 1: Get the
getSymbols("^GSPC")
# Step 2: Create your
DVI(Cl(GSPC))
# Step 3: Construct your trading
Lag(ifelse(dvi$dvi & 0.5, 1, -1))
# Step 4: The trading
rules/equity curve
ROC(Cl(GSPC))*sig
exp(cumsum(ret))
# Step 5: Evaluate strategy
performance
table.Drawdowns(ret,
table.DownsideRisk(ret)
charts.PerformanceSummary(ret)
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。How to Backtest a Strategy in R
| LinkedIn
We're going to explore the backtesting capabilities of R.
we developed some simple entry opportunities for the USD/CAD using a machine-learning algorithm and techniques from a subset of data mining called association rule learning. In this post, we are going to explore how to do a full backtest in R; using our rules from the previous post and implementing take profits and stop losses.
Let's dive right in:
library(RCurl)library(quantmod)#Install the libraries we need
sit = getURLContent('/systematicinvestor/SIT/raw/master/sit.gz', binary=TRUE, followlocation = TRUE, ssl.verifypeer = FALSE)con = gzcon(rawConnection(sit, 'rb'))#Download Michael Kapler's “”, a powerful set of tools used to backtest and evaluate quantitative trading strategies
source(con)close(con)#Install the toolbox
data &- new.env()#Create a new environment
tickers&-spl('USDCAD')file.path&- my.file.path#Specify the name of the asset and where the csv file is located on your computer. (You can find more ways to load data .)
for(n in tickers) {
data[[n]] = read.xts(paste(file.path, n, '.csv', sep=''), format='%m/%d/%y %H:%M')
}bt.prep(data, align='remove.na')#Load and clean the data
prices = data$pricesmodels = list()#Specify the prices and store our models
data$weight[] = NA;data$weight[] = 1models$buy.hold = bt.run.share(data, clean.signal=T)#Create our baseline “Buy and Hold” strategy
CCI20&-CCI(prices,20)RSI3&-RSI(prices,3)#Calculate our CCI and RSI indicators
DEMA10&-DEMA(prices,n = 10, v = 1, wilder = FALSE)DEMA10c&-prices - DEMA10; DEMA10c&-DEMA10c/.0001#Calculate the DEMA, find the distance from the price and convert to pips
buy.signal&-ifelse(RSI3 & 30 & CCI20 & -290 & CCI20 & -100 & DEMA10c & -40 & DEMA10c & -20,1,NA)#Set our long entry conditions found by our algorithms and optimized by us in the last post
data$weight[] = NA; data$weight[] = buy.signalmodels$long = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Create our long model
sell.signal&-ifelse(DEMA10c & 10 & DEMA10c & 40 & CCI20 & 185 & CCI20 & 325 & RSI3 & 50, -1 ,NA)#Set our short conditions
data$weight[] = NA; data$weight[] = sell.signalmodels$short = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Create our short model
long.short.strategy&-iif(RSI3 & 30 & CCI20 & -290 & CCI20 & -100 & DEMA10c & -40 & DEMA10c & -20,1,iif(DEMA10c & 10 & DEMA10c & 40 & CCI20 & 185 & CCI20 & 325 & RSI3 & 50, -1 ,NA))#Set the long and short conditions for our strategy
data$weight[] = NA; data$weight[] = long.short.strategymodels$longshort = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Create our long short strategy
dates = '::'#Isolate the dates from our validation set (The data not used to train the model or create the rules, our out-of-sample test)
bt.stop.strategy.plot(data, models$longshort, dates = dates, layout=T, main = 'Long Short Strategy', plotX = F)#View the plot of our trades
strategy.performance.snapshoot(models, T)#View the equity curve and performance statistics.
Let’s see if we can improve the performance by adding a stop loss and take profit.
stop.loss &- function(weight, price, tstart, tend, pstop) {
index = tstart : tend
if(weight & 0)
price[ index ] & (1 - pstop) * price[ tstart ]
price[ index ] & (1 + pstop) * price[ tstart ]
}#The stop loss function
Stoploss = .25/100#Set our maximum loss at a .25% move in price against our trade
data$weight[] = NA; data$weight[] = custom.stop.fn(coredata(long.short.strategy), coredata(prices), stop.loss,pstop = Stoploss)models$stoploss = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Our long short model with a .25% stop loss
bt.stop.strategy.plot(data, models$stoploss, dates = dates, layout=T, main = 'Stop Loss', plotX = F)#View the plot of our trades
strategy.performance.snapshoot(models[c(1,4:5)], T)#And how it compares to the original model
With just a stop loss, performance went down. It looks like we are getting taken out of our trades before they are able to recover. In order to lock in our profits, let’s go ahead and implement a take profit.
take.profit&- function(weight, price, tstart, tend, pprofit) {
index = tstart : tend
if(weight & 0)
price[ index ] & (1 + pprofit) * price[ tstart ]
price[ index ] & (1 - pprofit) * price[ tstart ]
}#The take profit function
Takeprofit = .25/100#Maintain at 1:1 risk/reward ratio and set our take profit at a .25% change in price
data$weight[] = NA; data$weight[] = custom.stop.fn(coredata(long.short.strategy), coredata(prices), take.profit, pprofit = Takeprofit)models$takeprofit = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Our long short model with a .25% take profit
bt.stop.strategy.plot(data, models$takeprofit, dates = dates, layout=T, main = 'Take Profit', plotX = F)#The plot of our trades
strategy.performance.snapshoot(models[c(1,4:6)], T)#Compare it to our other models
Locking in our gains with a take profit slightly improved the performance, but not drastically. Let’s incorporate both a stop loss and a take profit.
stop.loss.take.profit&-function(weight, price, tstart, tend, pstop, pprofit) {
index = tstart : tend
if(weight & 0) {
temp = price[ index ] & (1 - pstop) * price[ tstart ]
# profit target
temp = temp | price[ index ] & (1 + pprofit) * price[ tstart ]
temp = price[ index ] & (1 + pstop) * price[ tstart ]
# profit target
temp = temp | price[ index ] & (1 - pprofit) * price[ tstart ]
return( temp )
}#The stop loss and take profit function
data$weight[] = NA; data$weight[] = custom.stop.fn(coredata(long.short.strategy), coredata(prices), stop.loss.take.profit,pstop = Stoploss, pprofit = Takeprofit)models$stop.loss.take.profit = bt.run.share(data, clean.signal=T, trade.summary = TRUE)#Our long short model with a .25% stop loss and .25% take profit
Now let’s compare the baseline Long Short strategy, with just a stop loss, just a take profit, and both a take stop loss and take profit.
layout(1:4)#The layout of the plots
bt.stop.strategy.plot(data, models$longshort, dates = dates, layout=T, main = 'Long Short', plotX = F)bt.stop.strategy.plot(data, models$stoploss, dates = dates, layout=T, main = 'Long Short .25% SL', plotX = F)#The long short strategy and with just a stop loss
bt.stop.strategy.plot(data, models$takeprofit, dates = dates, layout=T, main = 'Long Short .25% TP', plotX = F)bt.stop.strategy.plot(data, models$stop.loss.take.profit, dates = dates, layout=T, main = 'Long Short .25% SL, .25% TP', plotX = F)#The take profit and stop loss/take profit strategy
strategy.performance.snapshoot(models[c(1,4:7)], T)#Finally comparing all the models we created
Now you know how to add a take profit and stop loss, I recommend you play around with the data and test different values based on your own personal risk parameters and using your own rules.
Even with powerful algorithms and sophisticated tools, it is difficult to build a successful strategy. For every good idea, we tend to have many more bad ones. Armed with the right tools and knowledge, you can efficiently test your ideas until you get to the good ones. We have streamlined this process in . We’ve developed a testing infrastructure that allows you to see where the patterns are in your data are and in real-time see how they would have performed over your historical data.
We’ll be releasing
for FX with technical indicators shortly. If you are interested in testing the software and providing feedback, please send an email to ! We have 50 spots available.
Looking for more of the latest headlines on LinkedIn?

我要回帖

更多关于 test server 的文章

 

随机推荐