This is a good example of closing before buying. something we could all benefit from, closing any positions we would be closing ahead of any buying rather than in the same minute.
Among the advantages, we have more control over what's happening, cope better with partial fills, reduce margin and see a more true picture of what our strategies can do, providing for a more solid footing on which to make further improvements to them.
To answer: The buy of context.shy is set to 100% so I added a return to prevent more ordering after that, which would account for some of the 48k margin in the original. Some might also be due to partial fills, very common out there and invisible unless we apply some code to see them. I've added that here.
I think of data.can_trade() as avoiding stocks with no price in a given minute and delistings, you can read more about that for definitive answers.
At the risk of overwhelming readers, I'll share with you what I'm seeing. Here's the gist of it:
The original code appears to have higher returns and doesn't really. It used 58k to make 40k, a profit/risk of about 70%.
Mine uses basically just the starting 10k to make 34k for profit/risk of 343%.
Original leverage hit 2.37. Mine 1.00.
With these changes, if it can handle starting capital of 50k (close to what yours risked), then PnL can be ~170k.
Again, the original risked ~50k, made 40k, could have risked 50k and made 170k.
Clone and try it, I'm curious how far off the prediction would be.
2017-03-21 13:00 _pvr:198 INFO PvR 0.0194 %/day cagr 0.1 Portfolio value 50269 PnL 40269
2017-03-21 13:00 _pvr:199 INFO Profited 40269 on 58022 activated/transacted for PvR of 69.4%
2017-03-21 13:00 _pvr:200 INFO QRet 402.69 PvR 69.40 CshLw -48022 MxLv 2.37 RskHi 58022 MxShrt -3228
2017-03-21 13:00 pvr:286 INFO 2003-01-15 to 2017-03-21 $10000 2017-03-24 21:02 US/Eastern
Runtime 0 hr 40.4 min
With close() before buying
2017-03-21 13:00 _pvr:210 INFO PvR 0.0962 %/day cagr 0.1 Portfolio value 44398 PnL 34398
2017-03-21 13:00 _pvr:211 INFO Profited 34398 on 10013 activated/transacted for PvR of 343.5%
2017-03-21 13:00 _pvr:212 INFO QRet 343.98 PvR 343.53 CshLw -13 MxLv 1.00 RskHi 10013 MxShrt 0
2017-03-21 13:00 pvr:298 INFO 2003-01-15 to 2017-03-21 $10000 2017-03-24 19:24 US/Eastern
Runtime 0 hr 33.4 min
Run my version and analyze the orders in the logging window to help spot ways to improve the strategy. I left out:
if context.track: track_orders(context, data)
... at the end of close(), you'll want to add that so that track_orders will let you know when those sells are entered. Right now it only shows when they go thru. And delete the pf_list stuff, didn't work, I deleted most of it and missed those two lines.