Hi IIya,


Brilliant! Many Thanks for your help.

Maybe Brian may want to include this in the demos of quantstrat ?

Anyhow, I will start thinking about how to optimize the strategy and produce 
heat-maps for a range of values.



Amarjit



 

________________________________
 From: Ilya Kipnis <ilya.kip...@gmail.com>
To: amarjit chandhial <a.chandh...@btinternet.com>; 
"r-sig-finance@r-project.org" <r-sig-finance@r-project.org> 
Sent: Friday, 4 April 2014, 1:27
Subject: Re: [R-SIG-Finance] Fwd: quantstrat - stochastic oscillator 
overbought-oversold (OBOS) strategy
  


Hi Amarjit,

I rewrote your demo and added a chart.Posn at the end. My impression is that it 
seems as good as any decent strategy on a single instrument. And on a little 
sidenote trivia, Google just had a stock split, so the ticker everyone will 
want to use in order to get at the original Google shares is GOOGL, not GOOG.

In any case, here's the demo, complete with the osMaxDollar function I wrote:

***********************


library(quantstrat)

osMaxDollar <- function(data, timestamp, orderqty, ordertype, orderside, 
                                portfolio, symbol, prefer="Open", tradeSize,
                                maxSize, integerShares=FALSE,
                                ...) {
  pos <- getPosQty(portfolio, symbol, timestamp)
  if(prefer=="Close") {
    price <- as.numeric(Cl(mktdata[timestamp,]))
  } else {
    price <- as.numeric(Op(mktdata[timestamp,])) 
  }
  posVal <- pos*price
  if (orderside=="short") {
    dollarsToTransact <- max(tradeSize, posVal-maxSize)
  } else {
    dollarsToTransact <- min(tradeSize, maxSize-posVal) 
  }
  qty <- dollarsToTransact/price
  if(integerShares) {
    if(qty > 0) {
      qty <- floor(qty)
    } 
    if(qty < 0) {
      qty <- ceiling(qty) 
    }
  }
  return(qty)
}

rm(list=ls(.blotter), envir=.blotter)
initDate='2009-12-31'
initEq=10000

currency('USD') 
Sys.setenv(TZ="UTC")

symbols <- c("GOOGL")

stock(symbols, currency="USD", multiplier=1)
getSymbols(symbols, src='yahoo',  
           index.class=c("POSIXt","POSIXct"),
           from = "2010-01-01", to="2013-12-31", adjust=TRUE)

strategy.st="GOOGstoch" 
portfolio.st="GOOGstoch"
account.st="GOOGstoch"

rm.strat(portfolio.st) 
rm.strat(strategy.st)
initPortf(portfolio.st, symbols=symbols, initDate=initDate, currency='USD')
initAcct(account.st, portfolios=portfolio.st, initDate=initDate, 
currency='USD', initEq=initEq) 
initOrders(portfolio.st, initDate=initDate)
strategy(strategy.st, store=TRUE)

################## indicators and parameters ############## 

nFastK = 20
nFastD = 3
nSlowD = 5
maType="SMA"
.orderqty=1000
.txn=0

add.indicator(strategy.st, name = "stoch", 
              arguments = list(HLC = quote(HLC(mktdata)), nFastK=nFastK, 
                               nFastD=nFastD,nSlowD=nSlowD, maType=maType) 
              )


################### signals ###################3#######
add.signal(strategy.st, name="sigThreshold",
           arguments = list(threshold=0.20,
                            column="slowD.stoch.ind",
                            relationship="gt",
                            cross=TRUE),
           label="slowD.stoch.ind.gt.20") 

add.signal(strategy.st,
           name="sigThreshold",
           arguments = list(threshold=0.80,
                            column="slowD.stoch.ind", 
                            relationship="lt",
                            cross=TRUE),
           label="slowD.stoch.ind.lt.80")

add.signal(strategy.st, 
           name="sigThreshold",
           arguments = list(threshold=0.80,
                            column="slowD.stoch.ind",
                            relationship="gte", 
                            cross=TRUE),
           label="slowD.stoch.ind.gte.80")

add.signal(strategy.st,
           name="sigThreshold", 
           arguments = list(threshold=0.20,
                            column="slowD.stoch.ind",
                            relationship="lte",
                            cross=TRUE), 
           label="slowD.stoch.ind.lte.20")

################# long rules ########################

add.rule(strategy.st, 
         name='ruleSignal',
         arguments = list(sigcol="slowD.stoch.ind.gte.80",
                          sigval=TRUE,
                          orderqty='all', 
                          ordertype='market',
                          TxnFees=.txn,
                          orderside='long',
                          #pricemethod='market', 
                          replace=FALSE),
         label='Exit2SHORT', type='exit', path.dep=TRUE)

stratstoch <- add.rule(strategy.st, 
                       name='ruleSignal',
                       arguments = list(sigcol="slowD.stoch.ind.gt.20",
                                        sigval=TRUE,
                                        orderqty=100, 
                                        ordertype='market',
                                        TxnFees=0, 
                                        orderside='long',
                                        #pricemethod='market',
                                        tradeSize=.orderqty,
                                        maxSize=initEq,
                                        replace=FALSE, 
                                        osFUN=osMaxDollar), 
                       label='EnterLONG', type='enter', path.dep=TRUE)

############# short rules ################## 

stratstoch <- add.rule(strategy.st,
                       name='ruleSignal',
                       arguments = list(sigcol="slowD.stoch.ind.lte.20", 
                                        sigval=TRUE,
                                        orderqty='all',
                                        ordertype='market',
                                        TxnFees=.txn, 
                                        orderside='short',
                                        #pricemethod='market',
                                        replace=FALSE), 
                       label='Exit2LONG', type='exit', path.dep=TRUE)

stratstoch <- add.rule(strategy.st,
                       name='ruleSignal', 
                       arguments = list(sigcol="slowD.stoch.ind.lt.80",
                                        sigval=TRUE,
                                        orderqty=100,
                                        ordertype='market',
                                        TxnFees=0,  
                                        orderside='short',
                                        #pricemethod='market', 
                                        replace=FALSE,
                                        tradeSize=-.orderqty,
                                        maxSize=initEq,
                                        osFUN=osMaxDollar), 
                       label='EnterSHORT', type='enter', path.dep=TRUE)

########## apply strategy ########

t1 <- Sys.time()
out <- applyStrategy(strategy=strategy.st,portfolios=portfolio.st) 
t2 <- Sys.time()
print(t2-t1)

########### update portfolio #########
updatePortf(portfolio.st)
dateRange <- time(getPortfolio(portfolio.st)$summary)[-1] 
updateAcct(portfolio.st,dateRange)
updateEndEq(account.st)

(tStats <- tradeStats(Portfolios = portfolio.st)) 
attributes(tStats)
tstats1 <- as.data.frame(t(tStats))
tstats1
tStats$Portfolio
tStats$Gross.Profits

rets1 <- PortfReturns(account.st) 
head(rets1,40)
tail(rets1,30)

#eqrets1<-na.omit(rets1) don't need this--no NAs in rets1
eqrets1<-cumsum(rets1)
tail(eqrets1,10)

chart.Posn(portfolio.st, "GOOGL")




On Thu, Apr 3, 2014 at 2:06 PM, amarjit chandhial <a.chandh...@btinternet.com> 
wrote:


>
>
>
>Hi IIya,
>
>
>
>
>1) Yes agreed, I need to use prefer=open hence I can include the present day 
>in PnL calculations.
>
>
>
>
>2) Also I believe that I need to do the following: 
>To EXIT a trade have replace=TRUE i.e. replace any imminent open orders (as 
>exit rules have priority)
>To ENTER a trade have replace=FALSE i.e. not replacing any imminent exit orders
>Agreed? 
>
>
>
>
>3) I am aware quantstrat works on the basis of  ' signal -> entering an order 
>-> transacting -> and recording a PnL', hence instant execution is mitigated 
>and an additional lag is needed in calculation of PnL.
>
>
>
>
>4)  I understand your osFixedDollarOneLot  function gives an approx. fixed 
>dollar amount per trade with varying quantities per trade i.e. 
>osFixedDollarOneLot in my example, will have each entry with a value of $1000 
>(not exactly) per trade (1% of $100,000) with varying quantities for each 
>trade. 
>
>
>
>
>However, I cannot write an osMaxDollar function though ;-), It's probably 
>about getting the orderqty right:
>
>
>
> osMaxDollar <- function(data, timestamp, orderqty, ordertype, orderside, 
>portfolio, symbol, prefer="Open", tradeSize,, ...)  { 
>
>
> pos <- getPosQty(portfolio, symbol, timestamp)
> ClosePrice <- as.numeric(Cl(mktdata[timestamp,]))
>
> OpenPrice <- as.numeric(Op(mktdata[timestamp,])) 
>
>
> CurrentPosValue <- (pos * ClosePrice))
>
>
> tempPortfolio <- getPortfolio(portfolio)
>
>
>
>
>#if you have a position on, do nothing
>
>
>  if (abs(pos) != 0 ) {
>    return (0)
>
>
>
>
> orderqty = tradeSize/price
>
>  } else {
>               if(prefer=="Close") {
>                  price <- ClosePrice
>               } else {
>                 price <- OpenPrice
>              
 }
>               }
>               if(orderside=="short") {
>                  return (-orderqty)
>               } else {
>                  return (orderqty)
>  }
>}
>
>
>
>
>Attached is the strategy thus far incorporating osFixedDollarOneLot function 
>and  aforementioned clarifications.
>
>
>Please help with osMaxDollar function, and make any more improvements. 
>Thereafter, I'd like to try an optimization (intraday) of this strategy.
>
>
>
>
>
>
>Amarjit
>
>
>
>
>
>
>
>
>
> 
> From: Ilya Kipnis <ilya.kip...@gmail.com>
>To: "r-sig-finance@r-project.org" <r-sig-finance@r-project.org> 
>Sent: Thursday, 3 April 2014, 10:01
>Subject: [R-SIG-Finance] Fwd: quantstrat - stochastic oscillator 
>overbought-oversold (OBOS) strategy
> 
>
>forwarding this to the R-finance list so as to notify that a response was
>given.
>
>********
>
>Also, another thing (and I think this may be the problem you're
>referencing)--I'm looking at your return stream, and it makes absolutely no
>sense to me (EG on 2013-12-20, you have a return of -14.40), but then I
>realized that your initial equity was $10,000. However, what you wind up
>doing is buying up to 10,000 *SHARES* of Google. I think what you were
>going for is that you want to buy (or short) $1000 DOLLARS of Google at any
>one point, and have a maximum investment of $10000 DOLLARS.
>
>In quantstrat, the quantity you buy isn't a dollar value, but a quantity of
>the object at hand. I.E. if you say to "buy 1000", you're buying 1000
>SHARES of Google, not 1000 DOLLARS. Currently, there isn't any
 osMaxDollar
>rule to my knowledge that exists in quantstrat (which isn't to say it can't
>be written, as I'm using something similar for one of my backtests that
>basically only allows for a certain dollar amount tradeSize to be invested,
>and if there's a position outstanding, to not touch it). Your custom rule
>basically would have to take into account the existing position quantity
>multiplied by a certain price (close, probably), and add on an additional
>amount so long as it does not violate your dollar constraint. Basically, a
>more general version of my function.
>
>For reference, here's my function:
>
>osFixedDollarOneLot <- function(data, timestamp, orderqty, ordertype,
>orderside,
>                                portfolio, symbol, prefer="Open",
>tradeSize, ...) {
>  pos <- getPosQty(portfolio, symbol,
 timestamp)
>  #if you have a position on, do nothing
>  if (abs(pos) != 0 ) {
>    return (0)
>  } else {
>    if(prefer=="Close") {
>      price <- as.numeric(Cl(mktdata[timestamp,]))
>    } else {
>      price <- as.numeric(Op(mktdata[timestamp,]))
>    }
>  }
>  if (orderside=="short") {
>    return (-tradeSize/price)
>  } else {
>    return (tradeSize/price)
>  }
>}
>
>And here's a rule calling it:
>
>
>add.rule(strategy.st, name="ruleSignal",
>         arguments=list(sigcol="longEntry",
>                        sigval=TRUE,
>                        orderqty=100, #this does nothing in our case, since
>we use a different
 rule
>                        ordertype="market",
>                        orderside="long",
>                        replace=FALSE,
>                        prefer="Open",
>                        tradeSize=.tradeSize,
>                        osFUN=osFixedDollarOneLot),
>         type="enter", path.dep=TRUE)
>
>And here's the trade size I defined earlier.
>
>.tradeSize=100 #$100 per trade
>
>What I think your intention was is that you want to order in $1000 trade
>sizes, up to a maximum of committing at most $10,000 long or short at any
>given time.
 In order to do this, you would need to write a custom rule that
>takes into account the current dollar value of your position, and your
>desired additional outlay, in a similar way to what I did with mine (but
>your function will probably have to be a lot more involved, since I just
>check whether or not I have a position, as opposed to its value, and how
>much more I can pile on).
>
>And one last thing--because quantstrat works on a next-bar basis, I
>recommend that you prefer="Open" on all of your rules, otherwise you see
>the signal at day t, but only buy on the close of day t+1, and so, miss an
>entire day's worth of edge.
>
>Hope this helps.
>
>-Ilya
>
>
>
>On Thu, Apr 3, 2014 at 4:15 AM, Ilya Kipnis <ilya.kip...@gmail.com> wrote:
>
>> Hi Amarjit,
>>
>> With stop and reverses, I've found that you want to keep
 replace on FALSE.
>> I spotted two such cases in your script. Can you confirm that you want
>> these to remain this way?
>>
>> -Ilya
>>
>>
>> On Thu, Apr 3, 2014 at 4:00 AM, amarjit chandhial <
>> a.chandh...@btinternet.com> wrote:
>>
>>>
>>>
>>> I think quite a lot folks are interested in this.
>>>
>>> So, a reminder.
>>>
>>>
>>> Amarjit
>>>
>>>
>>>
>>>
>>>
>>> ________________________________
>>>  From: amarjit chandhial <a.chandh...@btinternet.com>
>>> To: "r-sig-finance@r-project.org" <r-sig-finance@r-project.org>
>>> Sent: Monday, 31 March 2014, 9:34
>>> Subject: [R-SIG-Finance] quantstrat - stochastic oscillator
>>> overbought-oversold (OBOS) strategy
>>>
>>>
>>>
>>>
>>> All,
>>>
>>>
>>> I have tried to implement a traditional (80/20) stochastic oscillator
>>> overbought-oversold (OBOS) strategy in quantstrat.
>>>
>>> The script runs, however it may actually be wrong!
>>>
>>> I'd like to get this working correctly.
>>>
>>>
>>> Amarjit
>>>
>>>
>>>
>>>
>>> #
>>> # Stochastic Oscillator
>>> #
>>> #
>>> # 3 types of Stochastics
>>> #
>>> # (1) nfastk (Stochastic nfastk (%K)) is calculated
 as:
>>> #
>>> #     %K = (Current Close - Lowest Low)/(Highest High - Lowest Low)
>>> #
>>> #     where,
>>> #     Current Close is the most recent close,
>>> #     Lowest Low is the lowest low over the last n-periods,
>>> #     Highest High is highest high over the last n-periods
>>> #
>>> #
>>> # (2) nfastD (Stochastic nfastD (%D)) is a m-period moving average of
>>> Stochastic nfastk (%K) )
>>> # (3) nslowD (Stochastic nslowD) is a p-period moving average of
>>> Stochastic nfastD (%D) )
>>> #
>>> #
>>> # Stochastics generate signals via:
>>> #
>>> # (a) Crossover
>>> # (b) Over-Bought Over-Sold (OBOS)
>>> #
>>> #
>>> # (b) OBOS
>>> #
>>> # Traditionally:
>>> # --------------
>>> #
>>> #
 Use 80% as the OVERBOUGHT threshold and 20% as the OVERSOLD threshold
>>> #
>>> # Buy Long when indicator crosses ABOVE 20%
>>> # Sell Short when indicator crosses BELOW 80%
>>> #
>>> # In otherwords, this strategy implements:
>>> # (i) EnterLONG when indicator >20%
>>> # (ii) Exit2SHORT when indicator >=80%
>>> # (iii) EnterSHORT when indicator <80%
>>> # (iv) Exit2LONG when indicator <= 20%
>>> #
>>> # I have used nslowD as the indicator.
>>> #
>>> #
>>>
>>> ###############################################################################################
>>>
>>>  library(quantstrat)
>>>
>>>  suppressWarnings(rm("order_book.stoch",pos=.strategy))
>>>  suppressWarnings(rm("account.stoch","portfolio.stoch",pos=.blotter))
>>> 
 suppressWarnings(rm("account.st","portfolio.st
>>> ","stock.str","stratstoch","initDate",
>>>                      "initEq",'start_t','end_t'))
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # INITILIASATION
>>> #
>>> #
>>> # Initialize currency
>>> # Initialize instruments
>>> # Load historic data
>>> # Set parameters
>>>
>>> #correct for TZ issues if they crop up
>>>  oldtz<-Sys.getenv('TZ')
>>>  if(oldtz=='') {
>>>   Sys.setenv(TZ="GMT")
>>>  }
>>>  Sys.timezone()
>>>
>>>  currency("USD")
>>>  symbols = c("GOOG")
>>>
>>> #establish trade-able instruments
>>>  for(symbol in
 symbols){
>>>     stock(symbol, currency="USD",multiplier=1)
>>>     getSymbols(symbol, from="2010-01-01", to="2013-12-31")
>>>  }
>>>
>>> #view data
>>>  class(GOOG)
>>>  head(GOOG)
>>>  tail(GOOG)
>>>
>>> #Set initial values
>>>  initDate='2009-12-31'
>>>  initEq=10000
>>>
>>> #
>>> # parameters
>>> #
>>>   nFastK = 20
>>>   nFastD = 3
>>>   nSlowD = 5
>>>   maType="SMA"
>>>   .qty=1000
>>>   .txn=0
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # INITILIASATION
>>> #
>>> #
>>> # Initialize Portfolio
>>> # Initialize Account
>>> # Initialize
 Orders
>>> #
>>> # Initialize a strategy object
>>>
>>>  port.st <- 'stoch'
>>>  acct.st <- 'stoch'
>>>
>>>  initPortf(port.st, symbols=symbols, initDate=initDate)
>>>  initAcct(port.st, portfolios=port.st, initDate=initDate, initEq=initEq)
>>>  initOrders(portfolio=port.st, initDate=initDate)
>>>
>>> #Initialize a strategy object
>>>  stratstoch <- strategy("stratstoch")
>>>
>>> #set max pos --- not implemented
>>>  for(symbol in symbols){
>>>  addPosLimit(port.st, symbol, initDate, 1000, 1 )
>>>  }
>>>
>>>  print("setup completed")
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # DEFINE STRATEGY
>>> #
>>> #
>>>
 # Add
>>> #
>>> # (A) Indicators
>>> # (B) Signals
>>> # (C) Rules
>>> #
>>> #####
>>> #
>>> # (A) Add an indicator (ONE)
>>> #
>>>  stratstoch <- add.indicator(strategy = stratstoch,
>>>                              name = "stoch",
>>>                              arguments = list( HLC = quote(HLC(mktdata)),
>>>                                                nFastK=nFastK,
>>>                                               
 nFastD=nFastD,
>>>                                                nSlowD=nSlowD,
>>>                                                maType=maType) )
>>>
>>> #
>>> # stochastic indicator produces 3 indicators described above, with column
>>> headers
>>> # (1) fastK.stoch.ind
>>> # (2) fastD.stoch.ind
>>> # (3) slowD.stoc.ind
>>> #
>>> #####
>>> #
>>> # (B) Add FOUR signals
>>> #
>>> #
>>> # There are FOUR signals: (am using slowD.stoc.ind)
>>> #
>>>
>>> #The first is when stoch is GREATER THAN 0.20
>>>  stratstoch <- add.signal(strategy =
 stratstoch,
>>>                         name="sigThreshold",
>>>                         arguments = list(threshold=0.20,
>>>                                          column="slowD.stoch.ind",
>>>                                          relationship="gt",
>>>                                          cross=TRUE),
>>>                         label="slowD.stoch.ind.gt.20")
>>>
>>> #The second is when stoch
 is GREATER THAN OR EQUAL TO 0.80
>>>  stratstoch <- add.signal(strategy = stratstoch,
>>>                         name="sigThreshold",
>>>                         arguments = list(threshold=0.80,
>>>                                          column="slowD.stoch.ind",
>>>                                          relationship="gte",
>>>                                          cross=TRUE),
>>>                   
      label="slowD.stoch.ind.gte.80")
>>>
>>> #The third is when stoch is LESS THAN 0.80
>>>  stratstoch <- add.signal(strategy = stratstoch,
>>>                         name="sigThreshold",
>>>                         arguments = list(threshold=0.80,
>>>                                column="slowD.stoch.ind",
>>>                                relationship="lt",
>>>                                cross=TRUE),
>>>                        
 label="slowD.stoch.ind.lt.80")
>>>
>>> #The fourth is when stoch is LESS THAN OR EQUAL TO 0.20
>>>  stratstoch <- add.signal(strategy = stratstoch,
>>>                         name="sigThreshold",
>>>                         arguments = list(threshold=0.20,
>>>                                          column="slowD.stoch.ind",
>>>                                          relationship="lte",
>>>                                         
 cross=TRUE),
>>>                         label="slowD.stoch.ind.lte.20")
>>>
>>>
>>> ####
>>> #
>>> # (C) Add FOUR Rules
>>> #
>>> ### NOTE
>>> ### --------
>>> ### we use osMaxPos to put trade on in layers, or to a maximum position
>>> (not implemented)
>>>
>>> #
>>> # LONG orderside
>>> # note: if we are LONG (indicator is from <20 to (>20 & <80) ) and
>>> indicator falls back to <=20, we remain LONG
>>> #
>>>  stratstoch <- add.rule(strategy = stratstoch,
>>>                      name='ruleSignal',
>>>                      arguments = list(sigcol="slowD.stoch.ind.gte.80",
>>>     
                                  sigval=TRUE,
>>>                                       orderqty='all',
>>>                                       ordertype='market',
>>>            TxnFees=.txn,
>>>                                       orderside='long',
>>>                                       pricemethod='market',
>>>                             
          replace=TRUE),
>>>                      label='Exit2SHORT', type='exit', path.dep=TRUE)
>>>
>>>  stratstoch <- add.rule(strategy = stratstoch,
>>>                       name='ruleSignal',
>>>                       arguments = list(sigcol="slowD.stoch.ind.gt.20",
>>>                                        sigval=TRUE,
>>>                                        orderqty=+.qty,
>>>                                 
       ordertype='market',
>>>             TxnFees=0,
>>>                                        orderside='long',
>>>                                        pricemethod='market',
>>>                                        replace=FALSE,
>>>                                        osFUN=osMaxPos),
>>>                       label='EnterLONG', type='enter', path.dep=TRUE)
>>>
>>> #
>>> # SHORT
 orderside
>>> # note: if we are SHORT (indicator is from >80 to (<80 & >20) ), and
>>> indicator rises back to >=80, we remain SHORT
>>> #
>>>  stratstoch <- add.rule(strategy = stratstoch,
>>>                       name='ruleSignal',
>>>                       arguments = list(sigcol="slowD.stoch.ind.lte.20",
>>>                                        sigval=TRUE,
>>>                                        orderqty='all',
>>>                                     
   ordertype='market',
>>>             TxnFees=.txn,
>>>                                        orderside='short',
>>>                                        pricemethod='market',
>>>                                        replace=TRUE),
>>>                        label='Exit2LONG', type='exit', path.dep=TRUE)
>>>
>>>  stratstoch <- add.rule(strategy = stratstoch,
>>>                      name='ruleSignal',
>>>     
                 arguments = list(sigcol="slowD.stoch.ind.lt.80",
>>>                              sigval=TRUE,
>>>                                       orderqty=-.qty,
>>>                                       ordertype='market',
>>>                 TxnFees=0,
>>>                                       orderside='short',
>>>                                      
 pricemethod='market',
>>>                                       replace=FALSE,
>>>                                        osFUN=osMaxPos),
>>>                      label='EnterSHORT', type='enter', path.dep=TRUE)
>>>
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # BAR-BY-BAR PROCESSING
>>> #
>>> #Process the indicators and generate trades / Apply strategy to portfolio
>>>  start_t<-Sys.time()
>>>  out<-try(applyStrategy(strategy=stratstoch,
>>>                   
      portfolios=port.st))
>>>  end_t<-Sys.time()
>>>  print("Strategy Loop:")
>>>  print(end_t-start_t)
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # UPDATE PORTFOLIO ACCOUNT & EQUITY
>>> #
>>>
>>>  updatePortf(Portfolio=port.st
>>> ,Dates=paste('::',as.Date(Sys.time()),sep=''))
>>>  updateAcct(acct.st)
>>>  updateEndEq(acct.st)
>>>
>>>  for(symbol in symbols){
>>>     x11()
>>>     chart.Posn(Portfolio=port.st,Symbol=symbol)
>>>  }
>>>
>>>
>>> ###############################################################################################
>>>
>>>
 
###############################################################################################
>>> #
>>> # REPORTING
>>> #
>>> #
>>>  print(getOrderBook(port.st))
>>>  View(getTxns(Portfolio=port.st, Symbol=symbols))
>>>
>>> #
>>> # export various data files
>>> #
>>> #Stochastic indicators
>>>  mktdata <- mktdata
>>>  head(mktdata,30)
>>> #write.zoo(mktdata, file="stochOSC_OverboughtOversold_mktdata.txt")
>>>  x11()
>>>  plot(mktdata$slowD.stoch.ind)
>>>
>>> #Everything regarding the Portfolio
>>>  thePortfolio <- getPortfolio(port.st)
>>>  thePortfoliosummary <- thePortfolio$summary
>>>  thePortfoliosummary
>>> #write.zoo(thePortfoliosummary,
>>>
 file="stochOSC_OverboughtOversold_thePortfoliosummary.txt")
>>>
>>> #
>>> # getPortfolio chart
>>> #
>>>  library(lattice)
>>>  x11()
>>>  plot(xyplot(getPortfolio('stoch')$summary))
>>>
>>> #
>>> # tradeStats
>>> #
>>>
>>>  tstats <- tradeStats(port.st, symbols)
>>>  attributes(tstats)
>>>  tstats1 <- as.data.frame(t(tstats))
>>>  tstats1
>>>  tstats$Portfolio
>>>  tstats$Gross.Profits
>>>
>>>
>>> ###############################################################################################
>>> #
>>> # RETURNS & EQUITY
>>> # ----------------
>>> #
>>>
>>> #
>>> # Method 1: Standard (PortfReturns function)
>>> #
>>> #returns from strategy
>>>  rets1
 <- PortfReturns(Account='stoch')
>>>  head(rets1,40)
>>>  tail(rets1,30)
>>> #write.zoo(rets1, file="rets1.txt")
>>>
>>> #cumulative returns (equity curve)
>>>  eqrets1<-na.omit(rets1)
>>>  eqrets1<-cumsum(rets1)
>>>  tail(eqrets1,10)
>>>
>>> #GEOMETRIC=F, as summing PortfReturns
>>> #plot cumulative returns
>>>  x11()
>>>  charts.PerformanceSummary(rets1,geometric=F,wealth.index=T)
>>>
>>>
>>>
>>>
>>> R> sessionInfo()
>>> R version 3.0.3 (2014-03-06)
>>> Platform: x86_64-w64-mingw32/x64 (64-bit)
>>>
>>> locale:
>>> [1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United
>>> Kingdom.1252
>>> [3] LC_MONETARY=English_United Kingdom.1252
>>> LC_NUMERIC=C
>>> [5]
 LC_TIME=English_United Kingdom.1252
>>>
>>> attached base packages:
>>> [1] stats     graphics  grDevices utils     datasets  methods   base
>>>
>>> other attached packages:
>>>  [1] lattice_0.20-28
>>> quantstrat_0.8.2           foreach_1.4.1
>>>  [4] blotter_0.8.18             PerformanceAnalytics_1.1.4
>>> FinancialInstrument_1.1.9
>>>  [7] quantmod_0.4-1             Defaults_1.1-1
>>> TTR_0.22-0.1
>>> [10] xts_0.9-7                  zoo_1.7-11
>>>
>>> loaded via a namespace (and not attached):
>>> [1] codetools_0.2-8 grid_3.0.3
>>> iterators_1.0.6
>>>     [[alternative HTML version deleted]]
>>>
>>>
>>>
 _______________________________________________
>>> R-SIG-Finance@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.
>>>         [[alternative HTML version deleted]]
>>>
>>>
>>> _______________________________________________
>>> R-SIG-Finance@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.
>>>
>>
>>
>
>    [[alternative HTML version deleted]]
>
>_______________________________________________
>R-SIG-Finance@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.
>
>
>    
        [[alternative HTML version deleted]]

_______________________________________________
R-SIG-Finance@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.

Reply via email to