[R-SIG-Finance] incorrectly storing results from `blotter` when using `foreach`
Nick White
n-e-w at qtradr.net
Mon Nov 17 13:22:04 CET 2014
Hi all,
I've been messing around with using foreach loops to speed up blotter a
bit...but I can't seem to get the results to store after I run the parallel
job.
Using Guy Yollin's blotter for-loop example (at
http://www.r-programming.org/files/blotter.pdf)
I convert the for-loop to a foreach-loop using the following code (marked
between 3 #'s):
====================================================
### My changes to Guy's for-loop code:
foreach( i = 1:nrow(SPY),.combine=rbind, .packages=c('xts','blotter') )
%dopar%
{
### Rest of the code as usual...
# update values for this date
CurrentDate <- time(SPY)[i]
equity = getEndEq(b.strategy, CurrentDate)
ClosePrice <- as.numeric(Cl(SPY[i,]))
Posn <- getPosQty(b.strategy, Symbol='SPY', Date=CurrentDate)
UnitSize = as.numeric(trunc(equity/ClosePrice))
MA <- as.numeric(SPY[i,'SMA10m'])
# change market position if necessary
if( !is.na(MA) ) # if the moving average has begun
{
if( Posn == 0 ) { # No position, test to go Long
if( ClosePrice > MA ) {
# enter long position
addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = UnitSize , TxnFees=0) }
} else { # Have a position, so check exit
if( ClosePrice < MA ) {
# exit position
addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0)
} else {
if( i==nrow(SPY) ) # exit on last day
addTxn(b.strategy, Symbol='SPY', TxnDate=CurrentDate,
TxnPrice=ClosePrice, TxnQty = -Posn , TxnFees=0)
}
}
}
updatePortf(b.strategy,Dates=CurrentDate)
updateAcct(b.strategy,Dates=CurrentDate)
updateEndEq(b.strategy,CurrentDate)
}
====================================================
On a linux box using `htop` I can see the job execute across each processor
but then running something like
`chart.Posn(b.strategy,"SPY")`
which when, say, charting the position spits the error:
Error in chart.Posn(b.strategy, "SPY") :
no transactions/positions to chart
So, obviously I'm not reconstituting the results correctly after the
foreach loop runs...i've tried a few different calls but without much luck.
Any pointers as to where I'm going wrong?
[[alternative HTML version deleted]]
More information about the R-SIG-Finance
mailing list