


Dear Simon,


This does work now, although I'm not decided I understand why ?

Here's the complete code:-




# Load required libraries
require(quantstrat)
# Try to clean up in case the demo was run previously
suppressWarnings(rm("account.faber","portfolio.faber",pos=.blotter))
suppressWarnings(rm("ltaccount", "ltportfolio", "ClosePrice", "CurrentDate", "equity", 
            "GSPC", "stratFaber", "initDate", "initEq", "Posn", "UnitSize", "verbose"))
suppressWarnings(rm("order_book.faber",pos=.strategy))
##### PLACE DEMO AND TEST DATES HERE #################
#
#if(isTRUE(options('in_test')$in_test))
#  # use test dates
#  {initDate="2011-01-01" 
#  endDate="2012-12-31"   
#  } else
#  # use demo defaults
#  {initDate="1999-12-31"
#  endDate=Sys.Date()}

 Sys.setenv(TZ='UTC')

# Set initial values
initDate='1997-12-31'
initEq=1e5
# Set up instruments with FinancialInstruments package
currency("USD")
symbols = c("XLF", "XLP", "XLE", "XLY", "XLV", "XLI", "XLB", "XLK", "XLU")
#symbols = c("XLF", "XLP")
for(symbol in symbols){ # establish tradable instruments
    stock(symbol, currency="USD",multiplier=1)
}
# Load data with quantmod
#getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1998-01-01')
### Download monthly data instead?
### GSPC=to.monthly(GSPC, indexAt='endof')
getSymbols(symbols, src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
for(symbol in symbols) {
    x<-get(symbol)
    x<-to.monthly(x,indexAt='lastof',drop.time=TRUE)
    indexFormat(x)<-'%Y-%m-%d'
    colnames(x)<-gsub("x",symbol,colnames(x))
    assign(symbol,x)
}
# Initialize portfolio and account
initPortf('faber', symbols=symbols, initDate=initDate)
initAcct('faber', portfolios='faber', initDate=initDate, initEq=100000)
initOrders(portfolio='faber', initDate=initDate)
# set intial position limits
posval<-initEq/length(symbols)
for(symbol in symbols){
    pos<-round((posval/first(getPrice(get(symbol)))[,1]),-2)
    addPosLimit('faber',symbol,initDate, maxpos=pos,minpos=-pos)
}
print("setup completed")
# Initialize a strategy object
strategy("faber", store=TRUE)
# Add an indicator
add.indicator('faber', name = "SMA", arguments = list(x = quote(Cl(mktdata)), n=10), label="SMA10")
# There are two signals:
# The first is when monthly price crosses over the 10-month SMA
add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="gte"),label="Cl.gt.SMA")
# The second is when the monthly price crosses under the 10-month SMA
add.signal('faber',name="sigCrossover",arguments = list(columns=c("Close","SMA10"),relationship="lt"),label="Cl.lt.SMA")
# There are two rules:
# The first is to buy when the price crosses above the SMA
add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.gt.SMA", sigval=TRUE, orderqty=100000, osFUN='osMaxPos', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='enter', path.dep=TRUE)
# The second is to sell when the price crosses below the SMA
add.rule('faber', name='ruleSignal', arguments = list(sigcol="Cl.lt.SMA", sigval=TRUE, orderqty='all', ordertype='market', orderside='long', pricemethod='market',TxnFees=-5), type='exit', path.dep=TRUE)
# add quaterly rebalancing
add.rule('faber', 'rulePctEquity',
        arguments=list(rebalance_on='quarters',
                trade.percent=1/length(symbols),
                refprice=quote(last(getPrice(mktdata)[paste('::',pindex[i],sep='')][,1])),
                digits=0
        ),
        type='rebalance',
        label='rebalance'
)
# Process the strategy and generate trades
start_t<-Sys.time()
out<-applyStrategy.rebalancing(strategy='faber' , portfolios='faber')
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)
# look at the order book
#print(getOrderBook('faber'))
start_t<-Sys.time()
updatePortf(Portfolio='faber',Dates=paste('::',as.Date(Sys.time()),sep=''))
updateAcct('faber')
end_t<-Sys.time()
print("trade blotter portfolio update:")
print(end_t-start_t)
# hack for new quantmod graphics, remove later
themelist<-chart_theme()
themelist$col$up.col<-'lightgreen'
themelist$col$dn.col<-'pink'
dev.new()
layout(mat=matrix(1:(length(symbols)+1),ncol=2))
for(symbol in symbols){
    chart.Posn(Portfolio='faber',Symbol=symbol,theme=themelist,TA="add_SMA(n=10,col='darkgreen')")
}
ret1 <- PortfReturns('faber')
ret1$total<-rowSums(ret1)
ret1
if("package:PerformanceAnalytics" %in% search() || require("PerformanceAnalytics",quietly=TRUE)){
 getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='1999-01-01')
 SPY<-to.monthly(SPY)
 SPY.ret<-Return.calculate(SPY$SPY.Close)
 index(SPY.ret)<-index(ret1)
 dev.new()
 charts.PerformanceSummary(cbind(ret1$total,SPY.ret), geometric=TRUE, wealth.index=TRUE)
}
faber.stats<-tradeStats('faber')[,c('Net.Trading.PL','Max.Drawdown','Num.Trades','Profit.Factor','Std.Dev.Trade.PL','Largest.Winner','Largest.Loser','Max.Equity','Min.Equity')]
faber.stats





Regards,
Amarjit



 

________________________________
 From: Simon Otziger <simon@volemont.com>
To: Gei Lin <gmonaie@gmail.com> 
Cc: "r-sig-finance@r-project.org" <r-sig-finance@r-project.org> 
Sent: Saturday, 29 March 2014, 9:45
Subject: Re: [R-SIG-Finance] quantstrat demo(faber_rebal)
  

Dear Gei,

Thanks for the swift reply. Replacing timestamp by pindex[i] in the
add.rule doesn't solve the problem. Does the quick fix work for you?
The downloaded data doesn't have any missing values.

Simon

library(quantstrat)
Sys.setenv(TZ = "America/New_York")
source("faber_rebal.R")

[1] "setup completed"
Error in if (is.na(price)) stop("order at timestamp ", timestamp, "
must not have price of NA") :
  argument is of length zero

# add quaterly rebalancing
add.rule('faber', 'rulePctEquity',
        arguments=list(rebalance_on='quarters',
                trade.percent=1/length(symbols),

refprice=quote(last(getPrice(mktdata)[paste('::',pindex[i],sep='')][,1])),
                digits=0
        ),
        type='rebalance',
        label='rebalance'
)

On Fri, Mar 28, 2014 at 11:36 PM, Gei Lin <gmonaie@gmail.com> wrote:
> Looking at applyStrategy.rebalancing(), timestamp is being passed here to
> the function rulePctEquity, so it can be used *inside* rulePctEquity, but
> you can't reference it in passing arguments because it isn't defined inside
> applyStrategy.rebalancing(), it is floating around as the value pindex[i]
>
> ruleProc(s$rules$rebalance, timestamp = pindex[i],
>                       path.dep = TRUE, ruletype = "rebalance",
>                       ..., mktdata = md_subset, parameters = parameters,
>                       portfolio = portfolio, symbol = symbol)
>
> Quick fix, replace "timestamp" in the add.rule with "pindex[i]" which has
> the intended value and won't be missing.
>
> # add quarterly rebalancing
>> add.rule('faber', 'rulePctEquity',
> +         arguments=list(rebalance_on='quarters',
> +                 trade.percent=1/length(symbols),
> +
> refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')][,1])),
> +                 digits=0
> +         ),
> +         type='rebalance',
> +         label='rebalance'
> + )
>
>
> On Fri, Mar 28, 2014 at 5:00 PM, Simon Otziger <simon@volemont.com> wrote:
>>
>> Dear list members,
>>
>> I'm trying to run the demo(faber_rebal) from the Quantstrat package
>> (R-Forge Rev. 1590):
>> library(quantstrat)
>> Sys.setenv(TZ = "America/New_York")
>> demo(faber_rebal)
>>
>> The demo stops on line 133 with the error message:
>> > out<-applyStrategy.rebalancing(strategy='faber' , portfolios='faber')
>> Error in paste("::", timestamp, sep = "") :
>>   cannot coerce type 'closure' to vector of type 'character'
>>
>> I guess it's a namespace/masking clash with the timestamp() function
>> of the R.utils package. Another quantstrat user posted the same issue
>> in the R-Forge forums, see
>>
>> https://r-forge.r-project.org/forum/forum.php?thread_id=28525&forum_id=1032&group_id=316
>>
>> Any idea how to fix it?
>>
>> Thanks,
>> Simon
>>
>>
>> > sessionInfo()
>> R version 3.0.3 (2014-03-06)
>> Platform: x86_64-pc-linux-gnu (64-bit)
>>
>> locale:
>>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
>>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
>>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
>>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
>>  [9] LC_ADDRESS=C               LC_TELEPHONE=C
>> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
>>
>> attached base packages:
>> [1] stats     graphics  grDevices utils     datasets  methods   base
>>
>> other attached packages:
>>  [1] quantstrat_0.8.0           foreach_1.4.1
>>  [3] blotter_0.8.17             PerformanceAnalytics_1.1.0
>>  [5] FinancialInstrument_1.1.9  quantmod_0.4-0
>>  [7] Defaults_1.1-1             TTR_0.22-0
>>  [9] 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 lattice_0.20-27
>> [5] tools_3.0.3
>>
>> _______________________________________________
>> 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.
>
>
>
>
> --
>
> Don't quit. Suffer now and live the rest of your life as a champion.
>
>                                                 - Muhammad Ali
>
> The world is full of obvious things which nobody by any chance observes.
>
>                                                 - Sir Arthur Conan Doyle
>
> Towering genius disdains a beaten path. It seeks regions hitherto
> unexplored.
>
>                                                 - Abraham Lincoln

_______________________________________________
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]]

