Skip to content
Back to formatted view

Raw Message

Message-ID: <CAPPM_gS2q556GLmwxd+bMqM7eGzJNqFjCyagsunskY-aG3c7SA@mail.gmail.com>
Date: 2015-04-18T17:05:27Z
From: Joshua Ulrich
Subject: Specify time segment to calculate indicator and trade ?
In-Reply-To: <1428549429045-4705639.post@n4.nabble.com>

On Wed, Apr 8, 2015 at 10:17 PM, domodo <1111938 at qq.com> wrote:
> hi,guys.
> quantstrat is very powerful and convient when coding strategy and backtest
> it with indicator and pre-define price pattern.but i'm not familiar with
> specify the strategy to trade in a segment of trading-time,below are two
> cases:
> 1)establish position from 10:00 to 14:00 only,and close position with
> technical exits

Using quantstrat, you can limit rule execution to a specific time of
day via add.rule's timespan argument.  In this case you would set it
to timepan="T10:00/T14:00".

> 2)get the highest and lowest price of the first hour of a day
>
You can also do this with time-of-day subsetting.  For example:
apply.daily(xtsData["T09:30/T10:30", "Close"], range)

> for example,the strategy below is about price and single sma cross over.
> for case 1,i should store price series' date&time in varible 'datetime' as:
> [code]
> datetime <- as.POSIXlt(index(C))
> [/code]
>
> set entry time segment as:
> [code]
> entrytime1 <- 10
> entrytime2 <- 14
> [/code]
>
> and add some code below to judge whether the entry signal is in trading time
> :
> [code]
> signal <- ifelse(lag(C)>lag(MA) & lag(C,2)<lag(MA,2),1,
>                  ifelse(lag(C)&lt;lag(MA) &amp; lag(C,2)>lag(MA,2),-1,0))
>
> signal <- ifelse(signal>0 & datetime$hour>entrytime1 &
> datetime$hour<entrytime2,1,0)
> signal &lt;- ifelse(signal&lt;0 &amp; datetime$hour>entrytime1 &
> datetime$hour<entrytime2,-1,0)
> [/code]
>
> but the code above is not so elegant at all,and low-efficient.
>
> for the case 2,i should code a function to calculate the first hour's
> highest &amp; lowest price of each day,my idea in this function is similiar
> to code for case 1,that's, store price series's date&amp;time as a POSIXlt
> variable 'datetime',and judge whether hour == 10,min == 15,sec==0,but this
> idea is also rough and low-efficient.
>
> any help or tips please ?
>
> below is the example strategy
>
> [code]
> library(blotter)
> library(quantstrat)
>
> #initialize environtments
> currency(&quot;USD&quot;)
> startdate &lt;- '2012-01-18 09:14:00'
> finaldate &lt;- '2012-01-19 15:14:00'
>
> future(&quot;if2&quot;, currency = &quot;USD&quot;, multiplier = 300,
> tick_size = 0.2)
> Sys.setenv(TZ = &quot;UTC&quot;)
> rm(list=ls(envir=.blotter),envir=.blotter)
> b.strategy &lt;- &quot;strategy&quot;
>
> try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
> initPortf(b.strategy, &quot;if2&quot;, initDate = startdate)
> initAcct(b.strategy, portfolios = b.strategy, initDate = startdate, initEq =
> 1000000)
>
> ifBAC2 &lt;- read.table(&quot;C:/ifBAC2.csv&quot;, head = F, sep =
> &quot;,&quot;)
> coredata &lt;- ifBAC2[3:6]
> rownames(coredata) &lt;- as.POSIXlt(paste(ifBAC2[,1],ifBAC2[,2]))
> ifxts &lt;- as.xts(coredata)
> colnames(ifxts) &lt;-
> c(&quot;open&quot;,&quot;high&quot;,&quot;low&quot;,&quot;close&quot;)
> if2 &lt;- ifxts['2012-01-18 09:15:00/2012-01-19 15:14:00']
> if2$SMA15 &lt;- SMA(Cl(if2),15)
>
> #custom theme
> myTheme &lt;- chart_theme()
> myTheme$col$dn.col &lt;- &quot;lightgreen&quot;
> myTheme$col$up.col &lt;- &quot;red&quot;
> myTheme$col$dn.border &lt;- &quot;grey&quot;
> myTheme$col$up.border &lt;- &quot;grey&quot;
>
> MA &lt;- if2$SMA15
> C &lt;- Cl(if2)
> O &lt;- Op(if2)
>
> #trading signal judgement
> signal &lt;- ifelse(lag(C)>lag(MA) & lag(C,2)<lag(MA,2),1,
>                  ifelse(lag(C)&lt;lag(MA) &amp; lag(C,2)>lag(MA,2),-1,0))
> signal[is.na(signal)] <- 0
>
> #Bar-by-bar treatment
> for( i in 1:nrow(if2) )
> {
>   currentDate <- time(if2)[i]
>
>   equity<-getEndEq(b.strategy, currentDate)
>   Posn <- getPosQty(b.strategy, Symbol='if2', Date=currentDate)
>   #cat(as.character(i),"position on current bar is ",Posn, append = FALSE)
>
>   if(!is.na(MA[i]))
>   {
>     if( Posn == 0 & signal[i] == 1 ) { #no marketposition, and long signal
> occurs
>       #long entry
>       openprice <- as.double((Op(if2[currentDate])))
>       unitsize <- abs(as.numeric(trunc(equity/(openprice*300*0.15))))
>       addTxn(b.strategy, Symbol='if2', TxnDate=currentDate,
>              TxnPrice=openprice, TxnQty = unitsize ,
> TxnFees=-openprice*300*0.00005*unitsize, verbose = F)
>     }
>     else if( Posn != 0 & signal[i] == -1 ) {
>       #exit position
>       openprice <- as.double((Op(if2[currentDate])))
>       unitsize  <- abs(getPosQty(b.strategy, Symbol='if2',
> Date=currentDate))
>       addTxn(b.strategy, Symbol='if2', TxnDate=currentDate,
>              TxnPrice=openprice, TxnQty = -unitsize ,
> TxnFees=-openprice*300*0.00005*unitsize, verbose = F)
>     }
>   }
>
>   updatePortf(b.strategy, Dates = currentDate)
>   updateAcct(b.strategy, Dates = currentDate)
>   updateEndEq(b.strategy, Dates = currentDate)
> }
>
> chart.Posn(b.strategy, Symbol = "if2", theme = myTheme, TA =
> "add_SMA(n=15,col=4)")
>
> txns <- getTxns(Portfolio = b.strategy, Symbol = "if2")
> tstats <- tradeStats(Portfolio = b.strategy, Symbol = "if2")
> [/code]
>
> data format is as below
>
> [code]
>
> 2012/1/18       9:15:00 2577.6  2580.6  2573.6  2577.2
> 2012/1/18       9:16:00 2577.2  2583.6  2577    2583.2
> 2012/1/18       9:17:00 2583.4  2583.8  2580.6  2580.8
> 2012/1/18       9:18:00 2580.8  2581.4  2576.4  2577
> 2012/1/18       9:19:00 2577    2582    2576.6  2580.4
> 2012/1/18       9:20:00 2580.4  2581.4  2578.2  2581
> 2012/1/18       9:21:00 2580.8  2580.8  2578.8  2580
> 2012/1/18       9:22:00 2580.2  2581    2579.4  2579.8
> 2012/1/18       9:23:00 2580    2584.4  2579.8  2583.6
> 2012/1/18       9:24:00 2583.8  2585.2  2576    2576.2
> 2012/1/18       9:25:00 2577    2579.8  2576.8  2579
> 2012/1/18       9:26:00 2578.8  2584.2  2578.8  2581.2
> 2012/1/18       9:27:00 2581    2582.2  2580.6  2581.6
> 2012/1/18       9:28:00 2581.6  2581.6  2578.8  2579.4
> 2012/1/18       9:29:00 2580    2583    2579.8  2581.4
>
> [/code]
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Specify-time-segment-to-calculate-indicator-and-trade-tp4705639.html
> Sent from the Rmetrics mailing list archive at Nabble.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.



-- 
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com
R/Finance 2015 | www.rinfinance.com