Problem with automargin / margin and expected PnL
-
Hi everyone,
I found something very strange while using the automargin (margin=True) in commissionInfo during a backtest, that I cannot understand. When I sell, profits and loss are less than expected. The opposite happen when I buy, p&l are more than expected.
To replicate this as simple as possible, I used a dataframe of size 29 * 3 (date, open, close, with open = close, starting from 1 to 29),
startcash=1000
. I buy (or sell) the first day and keep until the end.-
with
CommissionInfo(commission = 0, margin = True, mult = 10, automargin = 1)
cerebro.broker.getvalue()
returns 757 (sell) / 1297 (buy) -
with
CommissionInfo(commission = 0, margin = 1, mult = 10)
cerebro.broker.getvalue()
returns 730 (sell) / 1270 (buy) -
if I set
automargin=1, mult =10
, I observe10% difference between automargin & margin (long +10%, short -10%) -
automargin=2, mult=10
, it's 20% -
... (automargin/mult) * 100 %
Maybe I missed something, maybe I don't really know how works commissions in backtrader, but I would like to know why both previous results are different.
Thank you in advance !
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt import pandas as pd import datetime class TestStrat(bt.Strategy): params = (('position', 0),) def next(self): if self.p.position == 0: self.sell(self.data) # self.buy(self.data) self.p.position = 1 cerebro = bt.Cerebro() startcash = 1000.0 cerebro.broker.setcash(startcash) df = pd.DataFrame(data = { 'date': [datetime.datetime(2000,1,i) for i in range(1,30)], 'open': [i for i in range(1,30)], 'close': [i for i in range(1,30)] }) df = df.set_index('date').sort_index() data = bt.feeds.PandasData(dataname = df) cerebro.adddata( data ) cerebro.broker.addcommissioninfo(bt.CommissionInfo(commission = 0, margin = True, mult = 10, automargin=1)) # cerebro.broker.addcommissioninfo(bt.CommissionInfo(commission = 0, margin = 1, mult = 10)) cerebro.addstrategy(TestStrat) cerebro.addobserver(bt.observers.Broker) strats = cerebro.run() print(cerebro.broker.getvalue())
-
-
:'(
-
Hi,
It seems to be a bug.
See this Pull Request for a fix:
https://github.com/backtrader/backtrader/pull/387@backtrader could you check please?