When I test futures in Chinese market, as the margin is not fixed margin, I customized the comminfo below:
class ComminfoFuturesPercent(bt.CommInfoBase):
'''write by myself,using in the future backtest,it means we should give a percent comminfo to broker'''
params = (
('stocklike', False),
('commtype', bt.CommInfoBase.COMM_PERC),
('percabs', True),
)
def _getcommission(self, size, price, pseudoexec):
return abs(size) * price * self.p.mult * self.p.commission
def get_margin(self, price):
return price * self.p.mult * self.p.margin
The margin wiill be calulated as notional value * margin ratio
On day 1, say my initial cash is 10000, and I buy 1 RB contract and hold, one contract contains 10 tons of RB, and price is 3000 per ton , with the margin ratio 10%, I will pay 1 * 10 * 3000 * 10%= 3000 as the margin, and 7000 cash left on my account. Commision was ignored for simplicity.
On day 2, say the price rises to 3100, the profit is: (3100-3000) * 1 * 10 = 1000, according to mark to market rule, I expect the cash should be added up to 8000, and the margin still be 3000, the total portfolio value shoud be 11000. But if I use the following methods, I got something weird:
self.broker.getvalue(datas=RB Data) returns 3100, on day 1 this method returned 3000 which is exactly the same as the initial margin, but on day 2 obviously it recalculate the margin with the latest price. The problem is the profit was already mark to market as a 1000 add-up to cash. It doesn't make sense for me to aslo inscrease the margin.
self.broker.getcash() returns 8000 no problem, that's what I expected.
self.broker.getvalue() returns 11100, As this method simply returns a sum of above, it over estimate the value of my portfolio.
So my question is, how can I get the correct value of my portfilo? Thanks.
]]>