On the Profit by Symbol Traded, first of all, fantastic, it is exactly what I wanted to see, and secondly I'm seeing a problem with (same-day) reversals whereby a reversal from long to short produces a profit about equal to - the position size.
I'm definitely seeing total profits not equal total profits in the back test, so one idea would be to put a line in somewhere that is like:
if calculated_profits != backtest.profits:
print_in_bold_letters('Profit Error SomeWhere')
Looking at the code, grouby_consecutive aggregates tnx so that, even if you start with:
Day Qty
1 +100
2 -100
2 -100
it ends up looking like:
Day Qty
1 +100
2 -200
Then when you close the trade you are netting the full $ amount of the day 2 tnx against the full $ amount of the day 1 tnx which probably messes things up going forward so a following tnx of:
Day Qty
3 +100
would open a new trade instead of closing the last one.
Maybe one way to fix it, would be to force a new tnx when there is a reversals at the end of groupby, something like:
prev_shares = 0
for tnx in tnx.sorted_by_symbol_and_date()
total_shares += tnx.shares
if(prev_shares > 0 and total_shares < 0 or prev_shares > 0 and total_shares < 0) then
....split reversal tnx into 2 pieces, -prev_shares in 1, and the rest in the other
So it ends up looking like:
Day Qty Sequence
1 +100 1
2 -100 2
2 -100 3
3 +100 4
Then, the rest of it might work fine with a small change incorporate the sequence