Mark to market problem duiring futures backtesting
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 1103000*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)110 = 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, for futures, this method returns the margin, but 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 add the margin.
- self.broker.getcash() returns 8000 no problem, that's what I expected.
- self.broker.getvalue() returns 11100, As this 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.
@stillwater sorry, a typo, the day 1 initial margin calculation should be 1103000*10% = 3000
@stillwater oops, I don't know why the '*' character was not showing on my topic and reply, I just wanna clarify that the initial margin on day 1 was calculated as : 1 multiply 10 multiply 3000 multiply 10% = 3000