I'm doing some vetting of strategy efficiency and coded up some simple P&L metrics. When I run and tabulate the running P&L from my code I get vastly different results than what I get from the backtest engine.
I extracted the P&L measurements from the log statements and dropped them into excel and matched the recorded metric in the Quantopian chart. Now, I realize that I can't technically get the true P&L for a trade as I'm not privy to the actual closing price of the trade. But I should be able to get close. And I'm not. At least, I don't think so.
If you run this strat, you'll see the PandL line. This comes from keeping a running PnL value and incrementing (decrementing) from it on the close of every trade. Again, I won't be completely accurate - but what I'm seeing is nowhere close.
So, what's going on here?
Simple strat logic:
produce custom metric
smooth it twice.
when fast ma moves above slow ma,
- close open position
- buy
when fast ma moves below slow ma,
- close open position
- sell
if unrealized position P&L > 100
- close trade
Here's how I'm retrieving the P&L at the time of the trade:
def GetPositionPandL(context, data, securityID):
openQty = context.portfolio.positions[securityID].amount
if (openQty == 0):
return 0
entryPrice = context.portfolio.positions[securityID].cost_basis
currentPrice = data[securityID].close_price
entryNotional = entryPrice * openQty
currentNotional = currentPrice * openQty
if ( openQty > 0):
return currentNotional - entryNotional
else:
return entryNotional - currentNotional