braverock / blotter

blotter provides transaction infrastructure for defining transactions, portfolios and accounts for trading systems and simulation. Provides portfolio support for multi-asset class and multi-currency portfolios. Actively maintained and developed.
114 stars 50 forks source link

Error in updatePortf() when using multiple currencies #117

Open evgeniavolkova opened 2 years ago

evgeniavolkova commented 2 years ago

Sometimes updatePortf() throws

Error in NextMethod(.Generic) : 
  number of items to replace is not a multiple of replacement length

After searching for the source of the error, found that it's caused by the line CcyMult <- CcyMult[index(TmpPeriods)].

It produces duplicate redundant dates in CcyMult when dates (and a number of rows in CcyMult) are already aligned with TmpPeriods. After executing this line the number of rows in CcyMult becomes greater than in TmpPeriods, which causes the error mentioned above.

A possible and ugly fix:

if ((nrow(CcyMult) != nrow(TmpPeriods))){
    CcyMult <- CcyMult[index(TmpPeriods)]
}

It helps to avoid the error, but there should be a better solution.

joshuaulrich commented 2 years ago

Thanks for the report! Can you give a small, reproducible example that triggers the issue?

evgeniavolkova commented 2 years ago

It looks like the problem is in intraday deals.

devtools::install_github("braverock/blotter")
library('blotter')
library('quantmod')

options("getSymbols.warning4.0"=FALSE)
from ="2022-01-01"
to ="2022-01-15"
symbols = c("AAPL")
currency("USD")
currency("RUB")
getSymbols(symbols, from=from, to=to, 
           adjust=TRUE)
stock(symbols, currency="USD", multiplier=1)
getSymbols("RUB=X",src="yahoo",from="2022-01-01")
RUBUSD = `RUB=X`

initPortf('p', symbols = symbols, currency = 'RUB')

addTxn(Portfolio = 'p', Symbol = 'AAPL', TxnDate = as.Date("2022-01-04"),
       TxnQty = 1, TxnPrice = 179.70)
addTxn(Portfolio = 'p', Symbol = 'AAPL', TxnDate = as.Date("2022-01-04"),
       TxnQty = -1, TxnPrice = 179.70)

updatePortf('p')