[R-SIG-Finance] quantstrat help
Raghuraman Ramachandran
optionsraghu at gmail.com
Sat Oct 18 14:41:33 CEST 2014
Dear Gents
I went through the documentation as you had kindly suggested and tried
to understand the application of quantstrat. I also tried to run a
code as below (obtained from here:
http://kylebalkissoon.wordpress.com/2013/06/07/trading-on-the-sharpe-ratio-using-quantstrat/).
The only difference is I tried to generate signal based on market
moves as discussed before. When I tried to run this I get the
following error:
A traceback did not help much.
out <- applyStrategy(strategy=stratstocky, port .... [TRUNCATED]
Error in if (inherits(sret$indicators, "xts") & nrow(mktdata) ==
nrow(sret$indicators)) { :
argument is of length zero
What am I missing please? BTW Ilya's pages are excellent and very
descriptive. Great job.
The code below:
#clear workspace (for testing)
rm(list = ls())
#load libraries
require(quantmod)
require(PerformanceAnalytics)
require(blotter)
require(FinancialInstrument)
require(quantstrat)
require(forecast)
require(foreach)
#clear portfolio and acct not needed due to the clearing workspace but
here incase you don't use it.
suppressWarnings(rm("account.stocky","portfolio.stocky",pos=.blotter))
suppressWarnings(rm("order_book.stocky",pos=.strategy))
suppressWarnings(rm(stocky))
#if your stock is different you need to change
(initdate,initportf,addposlimit, chart.posn)
symbol = "SPY"
#Set up currencies
currency("USD")
#define stock change spy to your stock of choice
stock(symbol, currency="USD", multiplier = 1)
####################################################### Get Data
#################################################
getSymbols(symbol,src="yahoo",from = "2000-01-01" )
#Set Initial Date and Equity, note change SPY to your stock of choice.
initDate = start(SPY)
initEq = 10000
########################## Set up portfolio orders and Acct
#######################################
#change SPY to your stock choice
initPortf(name="stocky","SPY",initPosQty=0,initDate=initDate,currency="USD")
initAcct("stocky",portfolios="stocky",initDate=initDate,initEq=initEq)
initOrders("stocky",symbols=symbol,initDate=initDate)
#position limits
#change "SPY" to your stock choice
addPosLimit("stocky","SPY",timestamp=initDate,maxpos=100, minpos=0)
#Set up Strategy
stratstocky<-strategy("stocky")
##############################FUNCTIONS#################################
jumps=function(dat)
{
colnames(dat)=c("Open","High","Low","Close","Volume","AdjPrice")
dat$mclose=round(apply(HLC(dat),1,mean))
dat$sig=ifelse((dat$mclose>1.02*dat$Open), 1,ifelse(dat$mclose<=
0.98*dat$Open, -1, 0))
return(dat$sig)
}
########################indicators#############################
stratstocky<-add.indicator(
strategy = stratstocky,
name = "jumps",
arguments = list(
dat = quote(mktdata)),
label = "sig")
################################################ Signals
#############################
stratstocky<-add.signal(
strategy = stratstocky,
name = "sigThreshold",
arguments = list(
threshold = -1,
column = "sig",
relationship = "eq",
cross = TRUE),
label = "Selltime")
stratstocky<-add.signal(
strategy = stratstocky,
name = "sigThreshold",
arguments = list(
threshold = 1,
column = "sig",
relationship = "eq",
cross = TRUE),
label = "Buytime")
######################################## Rules
#################################################
#Entry Rule Long
stratstocky<- add.rule(stratstocky,
name = "ruleSignal",
arguments = list(
sigcol = "Buytime",
sigval = TRUE,
orderqty = 100,
ordertype = "market",
orderside = "long",
pricemethod = "market",
replace = TRUE,
TxnFees = -1,
osFUN = osMaxPos),
type = "enter",
path.dep = TRUE,
label = "Entry")
#Entry Rule Short
stratstocky<- add.rule(stratstocky,
name = "ruleSignal",
arguments = list(
sigcol = "Selltime",
sigval = TRUE,
orderqty = 100,
ordertype = "market",
orderside = "short",
pricemethod = "market",
replace = TRUE,
TxnFees = -1,
osFUN = osMaxPos),
type = "enter",
path.dep = TRUE,
label = "Entry")
#Exit Rules
#Exit
stratstocky <- add.rule(stratstocky,
name = "ruleSignal",
arguments = list(
sigcol = "Selltime",
sigval = TRUE,
orderqty = "all",
ordertype = "market",
orderside = "long",
pricemethod = "market",
replace = TRUE,
TxnFees = -1),
type = "exit",
path.dep = TRUE,
label = "Exitfromlong")
stratstocky <- add.rule(stratstocky,
name = "ruleSignal",
arguments = list(
sigcol = "Buytime",
sigval = TRUE,
orderqty = "all",
ordertype = "market",
orderside = "short",
pricemethod = "market",
replace = TRUE,
TxnFees = -1),
type = "exit",
path.dep = TRUE,
label = "Exitfromshort")
############################## Apply Strategy
##############################################
out <- applyStrategy(strategy=stratstocky, portfolios="stocky")
updatePortf("stocky")
############################# Portfolio Return Characterics
################################
#get portfolio data
portRet <- PortfReturns("stocky")
portRet$Total <- rowSums(portRet, na.rm=TRUE)
charts.PerformanceSummary(portRet$Total)
#tradeStats("stocky")[,c("Symbol","Num.Trades","Net.Trading.PL","maxDrawdown
#change SPY to your stock choice
chart.Posn("stocky","SPY")
results1<-getTxns("stocky","SPY")
#plot(results1$Net.Txn.Realized.PL)
Many thanks and regards,
Raghu
On Fri, Oct 17, 2014 at 2:13 PM, Raghuraman Ramachandran
<optionsraghu at gmail.com> wrote:
> Thanks Josh, Ilya, Nick. I will start on those lectures of Guy.
> Josh> Thx for correcting the vectorization part of the code. It is a
> steep curve indeed but enjoyable!
>
> Best Rgds
> Raghu
>
> On Fri, Oct 17, 2014 at 2:06 PM, Nick White <n-e-w at qtradr.net> wrote:
>> Raghu,
>>
>> I highly recommend you start with Guy Yollin's excellent lectures @
>> http://www.r-programming.org/papers
>>
>> Begin with understanding the `blotter` package.
>>
>> Guy's notes then proceed onto quantstrat and each successive lecture
>> introduces progressively more advanced features. Lecture 1 will more than
>> sufficiently cover what you're trying to do.
>>
>> There's a learning curve to quantstrat -- but if you follow Guy's lectures
>> it will be about as painless as its possible to be.
>>
>> n.
>>
>>
>>
>> On Fri, Oct 17, 2014 at 11:31 PM, Raghuraman Ramachandran
>> <optionsraghu at gmail.com> wrote:
>>>
>>> Thx Josh.
>>>
>>> Here is the code:
>>>
>>> require(quantmod)
>>> require(TTR)
>>> getSymbols('^GSPC')
>>> colnames(GSPC)=c("Open","High","Low","Close","Volume","AdjPrice")
>>> for (i in 1: nrow(GSPC))
>>> {
>>> GSPC$signal[i]=ifelse((GSPC$Close[i]>1.02*GSPC$Open[i]), 1
>>> ,ifelse(GSPC$Close[i]<= 0.98*GSPC$Open[i], -1, 0))
>>> }
>>>
>>> So there will be consecutive days of longs or shorts but how to ignore
>>> the subsequent signals and take the first occurrences inside
>>> quantstrat pls?
>>>
>>> Rgds
>>> Raghu
>>>
>>> On Fri, Oct 17, 2014 at 12:50 PM, Joshua Ulrich <josh.m.ulrich at gmail.com>
>>> wrote:
>>> > On Fri, Oct 17, 2014 at 4:37 AM, Raghuraman Ramachandran
>>> > <optionsraghu at gmail.com> wrote:
>>> >> Dear guRus
>>> >>
>>> >> I am trying to understand the quantstrat package. My signal is very
>>> >> simple. I want to buy if daily close > 2% of open and vice versa. But
>>> >> my signals produce consecutive 1s (when market is going higher) and
>>> >> -1s (when market is going lower) so I want to avoid buying (or
>>> >> selling) more if already bought or sold.
>>> >>
>>> > Then only take the first signal. If you want more specific
>>> > instructions about how to do that, then provide more specific details
>>> > about your problem (e.g. your actual code).
>>> >
>>> >> My question is:
>>> >> Is it possible to tell quantstrat a) Please do not buy if already
>>> >> bought and if a new buy signal appears and b) Please buy even though
>>> >> if already bought and a new signal appears.
>>> >
>>> > a) Yes.
>>> > b) Yes.
>>> >
>>> >> Also, when a leave a trailing stop which takes precedence? A trailing
>>> >> stop or a new signal on the opposite side and is it possible to change
>>> >> this precedence please?
>>> >>
>>> > Rules are processed in the order described in the Details section of
>>> > ?add.rule. You can change the order, but it is strongly discouraged
>>> > because it's very easy to create unrealistic behavior if you modify
>>> > the order incorrectly.
>>> >
>>> >> Sincere thanks for the guidance,
>>> >> Raghu
>>> >>
>>> >
>>> > --
>>> > Joshua Ulrich | about.me/joshuaulrich
>>> > FOSS Trading | www.fosstrading.com
>>>
>>> _______________________________________________
>>> R-SIG-Finance at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
>>> -- Subscriber-posting only. If you want to post, subscribe first.
>>> -- Also note that this is not the r-help list where general R questions
>>> should go.
>>
>>
More information about the R-SIG-Finance
mailing list