9.3 Simple Filter Rule
We first use the quanstrat package on simple filter rule.
9.3.1 Step 1: Initialization
After loading all the required packages, we initialize are variables and then download data.
Then we need to get the data and define initial variables. Download stock prices using getSybmols().
options("getSymbols.warning4.0"=FALSE)
from ="2009-01-01"
to ="2012-12-31"
symbols = c("MSFT", "IBM")
getSymbols(symbols, from=from, to=to,
adjust=TRUE)
Currency is USD for US stocks and the multiplier is always 1 for stocks.
We first define our strategy, portfolio and account name.
Remove any old variables
After naming strategy, portfolio and account, we initialize them:
initEq=100000
initDate="1990-01-01"
initPortf(name=portfolio.st,
symbols=symbols,
initDate=initDate,
currency='USD')
initAcct(name=account.st,
portfolios=portfolio.st,
initDate=initDate,
currency='USD',
initEq=initEq)
initOrders(portfolio=portfolio.st,
symbols=symbols,
initDate=initDate)
strategy(strategy.st, store=TRUE)
9.3.2 Step 2: Define indicator
Indicator is just a function based on price. Since simple filter is not a standard technical indicator, we need to define it first.
filter <- function(price) {
lagprice <- lag(price,1)
temp<-price/lagprice - 1
colnames(temp) <- "filter"
return(temp)
}
We add the simple filter as an indicator. Here the name is the indicator function we have defined. We need to specify what data to be used by the indicator. Since we have defined that the simple filter rule takes price as input, we need to tell the problem we are using the closing price. Note that the label filter is the variable assigned to this indicator, which implies it must be unique.
add.indicator(
strategy=strategy.st,
name = "filter",
arguments = list(price = quote(Cl(mktdata))),
label= "filter")
To check if the indicator is defined correctly, use applyindicators to see if it works. The function try() is to allow the program continue to run even if there is an error.
9.3.3 Step 3: Trading Signals
Trading signals is generated from the trading indicators. For example, simple trading rule dictates that there is a buy signal when the filter exceeds certain threshold.
In quantstrat, there are three ways one can use a signal. It is refer to as name:
- sigThreshold: more or less than a fixed value
- sigCrossover: when two signals cross over
- sigComparsion: compare two signals
The column refers to the data for calculation of signal. There are five possible relationship:
- gt = greater than
- gte = greater than or equal to
- lt = less than
- lte = less than or equal to
- eq = equal to
Buy Signal under simple trading rule with threshold \(\delta=0.05\)
# enter when filter > 1+\delta
add.signal(strategy.st,
name="sigThreshold",
arguments = list(threshold=0.05,
column="filter",
relationship="gt",
cross=TRUE),
label="filter.buy")
Sell Signal under simple trading rule with threshold \(\delta=-0.05\)
9.3.4 Step 4. Trading Rules
While trading signals tell us buy or sell, but it does not specify the execution details.
Trading rules will specify the following seven elements:
- SigCol: Name of Signal
- SigVal: implement when there is signal (or reverse)
- Ordertype: market, stoplimit
- Orderside: long, short
- Pricemethod: market
- Replace: whether to replace other others
- Type: enter or exit the order
Buy rule specifies that when a buy signal appears, place a buy market order with quantity size.
add.rule(strategy.st,
name='ruleSignal',
arguments = list(sigcol="filter.buy",
sigval=TRUE,
orderqty=1000,
ordertype='market',
orderside='long',
pricemethod='market',
replace=FALSE),
type='enter',
path.dep=TRUE)
Sell rule specifies that when a sell signal appears, place a sell market order with quantity size.
9.3.5 Step 5. Evaluation Results
We will apply the our trading strategy, and the we update the portfolio, account and equity.
## [1] "2009-01-22 08:00:00 IBM 1000 @ 83.7975453378965"
## [1] "2009-03-24 08:00:00 IBM 1000 @ 91.9519343052697"
## [1] "2011-07-20 08:00:00 IBM 1000 @ 179.10642184081"
## [1] "2009-01-08 08:00:00 MSFT -1000 @ 18.2435376760854"
## [1] "2009-01-21 08:00:00 MSFT -1000 @ 17.5725509118512"
## [1] "2009-01-23 08:00:00 MSFT -1000 @ 15.595867329838"
## [1] "2009-03-06 08:00:00 MSFT -1000 @ 13.9499293968326"
## [1] "2009-03-11 08:00:00 MSFT 1000 @ 15.6206352048257"
## [1] "2009-03-24 08:00:00 MSFT 1000 @ 16.369256157409"
## [1] "2009-03-27 08:00:00 MSFT 1000 @ 16.5518459433669"
## [1] "2009-04-01 08:00:00 MSFT 1000 @ 17.6291310669443"
## [1] "2009-04-27 08:00:00 MSFT 1000 @ 18.624251288965"
## [1] "2009-07-27 08:00:00 MSFT -1000 @ 21.2323467096564"
## [1] "2009-10-26 08:00:00 MSFT 1000 @ 26.4979519060214"
## [1] "2010-09-14 08:00:00 MSFT 1000 @ 23.5668456416348"
## [1] "2011-08-11 08:00:00 MSFT -1000 @ 24.161608834081"
## [1] "2012-01-23 08:00:00 MSFT 1000 @ 28.912330972876"
Now we can update the portfolio, account and equity.
We can visualize the trading position, profit and loss, and drawdown in graph.
We can also look at the details of the trading statistics of trading strategies such as the number for trades, and profitability of trades.
## MSFT
## Portfolio "filter"
## Symbol "MSFT"
## Num.Txns "14"
## Num.Trades "6"
## Net.Trading.PL "83.59068"
## Avg.Trade.PL "154.7204"
## Med.Trade.PL "-120.0797"
## Largest.Winner "2608.095"
## Largest.Loser "-1288.66"
## Gross.Profits "3327.932"
## Gross.Losses "-2399.609"
## Std.Dev.Trade.PL "1388.605"
## Std.Err.Trade.PL "566.8957"
## Percent.Positive "33.33333"
## Percent.Negative "66.66667"
## Profit.Factor "1.386864"
## Avg.Win.Trade "1663.966"
## Med.Win.Trade "1663.966"
## Avg.Losing.Trade "-599.9023"
## Med.Losing.Trade "-541.0823"
## Avg.Daily.PL "154.7204"
## Med.Daily.PL "-120.0797"
## Std.Dev.Daily.PL "1388.605"
## Std.Err.Daily.PL "566.8957"
## Ann.Sharpe "1.768761"
## Max.Drawdown "-13277.96"
## Profit.To.Max.Draw "0.006295447"
## Avg.WinLoss.Ratio "2.773728"
## Med.WinLoss.Ratio "3.075255"
## Max.Equity "11297.26"
## Min.Equity "-3241.054"
## End.Equity "83.59068"
Then we can evaluate the performance using PerfomanceAnalytics package to see how is the return of the trading strategy.
rets <- PortfReturns(Account = account.st)
rownames(rets) <- NULL
tab <- table.Arbitrary(rets,
metrics=c(
"Return.cumulative",
"Return.annualized",
"SharpeRatio.annualized",
"CalmarRatio"),
metricsNames=c(
"Cumulative Return",
"Annualized Return",
"Annualized Sharpe Ratio",
"Calmar Ratio"))
tab
## IBM.DailyEqPL MSFT.DailyEqPL
## Cumulative Return 1.6193661 -0.019208488
## Annualized Return 0.2730959 -0.004851509
## Annualized Sharpe Ratio 0.3585370 -0.048171847
## Calmar Ratio 0.4339721 -0.037716053
We can visualize the performance of the trading rule