A top investment site online said few investors understand margin as well as they should. That includes me.
Drop this code with one paste into an existing algorithm at the end of initialize() to chart any overnight margin where fees can run high.
schedule_function(margin_overnight, date_rules.every_day(), time_rules.market_open()) context.margin_ttl = 0 context.mdays = 0.0 # a count of days for margin average def margin_overnight(context, data): ''' Chart overnight margin, current, total and average per day. Intraday margin is ignored. ''' if context.mdays: margin_one_night = abs(min(0, context.portfolio.cash)) # Margin held overnight context.margin_ttl += margin_one_night margin_average = context.margin_ttl / context.mdays record(Margin = margin_one_night) # Last night's carried margin record(Mrgn_Ttl = context.margin_ttl) # Total overnight margin record(Mrgn_Avg = margin_average) # Average overnight margin record(PnL = context.portfolio.pnl) # Actual profit context.mdays += 1.0
Why does this matter? Realistic evaluation of algorithms and comparison can only be done with knowledge of their amount of margin. If you start with $1 and buy a share of SPY every day, your returns will appear astronomical, the returns curve in that case is unfortunately an illusion, most of the apparent profit would be stock value owed eventually in cash back to the broker, even without considering the fees. About 600% returns below.
And what are the fees?
Margin | Interactive Brokers
Overnight Margin Calculations. Stocks have additional margin requirements when
held overnight. For overnight margin requirements for stocks, click the Stocks ...
Adjusted Gross Margin - Investopedia
Adjusted gross margin goes one step further than gross margin
because it includes these inventory carrying costs,
which greatly affect the bottom line of a product's profitability.
Can anyone add some broker fees to the code?
|Returns||1 Month||3 Month||6 Month||12 Month|
|Alpha||1 Month||3 Month||6 Month||12 Month|
|Beta||1 Month||3 Month||6 Month||12 Month|
|Sharpe||1 Month||3 Month||6 Month||12 Month|
|Sortino||1 Month||3 Month||6 Month||12 Month|
|Volatility||1 Month||3 Month||6 Month||12 Month|
|Max Drawdown||1 Month||3 Month||6 Month||12 Month|