Robot-Wealth / rsims

R package for financial simulation
Other
38 stars 16 forks source link

us_tiered_commission does not work with NA's or zeros for unadjusted prices #16

Open jbhunter52 opened 3 months ago

jbhunter52 commented 3 months ago

I get this error when using the rsims::us_tiered_commission function as a commission function.

Error in if (post_trade_equity < post_trade_margin) { : missing value where TRUE/FALSE needed

I have a universe of assets in which some have no data for earlier dates. I have tried using zeros and NA's for the unadjusted_prices, however it still getting the error. I believe in my case post_trade_equity is NA, resulting in the error, as a result of commissions being NA.

I believe this is due to a divide by zero error in the us_tiered_commission function. As an example, the below will produce an NA

shares_traded <- 0 prices <- 0 unadjprices <- NA max_pct_per_order <- 0.01 min_dollars_per_order <- 0.35 dollars_per_share <-0.0035 rsims::us_tiered_commission(shares_traded, prices, unadjprices, max_pct_per_order, min_dollars_per_order, dollars_per_share)

tradevalue <- shares_traded prices commissions <- pmin(abs(tradevalue)/unadjprices dollars_per_share, max_pct_per_order * abs(tradevalue)) commissions[commissions < min_dollars_per_order & abs(shares_traded) > 0] <- min_dollars_per_order commissions

jbhunter52 commented 3 months ago

Modifying a custom function seems to work for me. Just adding the replacement of NA's with zero at the end of the function fixes the issue.

us_tiered_commission <- function(shares_traded, prices, unadjprices, max_pct_per_order, min_dollars_per_order, dollars_per_share) {
  # x dollars per share
  # min y dollars per order
  # max z% of tradevalue
  tradevalue <- shares_traded * prices
  commissions <- pmin(abs(tradevalue)/unadjprices * dollars_per_share, max_pct_per_order*abs(tradevalue))  # scale by unadjusted close to get actual commissions on a given tradevalue
  commissions[commissions < min_dollars_per_order & abs(shares_traded) > 0] <- min_dollars_per_order
  commissions[is.na(commissions)] <- 0
  commissions
}
robotmasterkris commented 3 months ago

Brilliant thank you for posting your fix! I'll get that incorporated into the next release.