Can someone help me take a look at this code? The very basic algorithm is in the comments at the start of the file. It is a strategy from Laurens Bendsdorp's book. 

The orders results are very odd, they do not make any sense to me.

I'm rusty on python and not optimizing for code quality here, just trying to get something working as expected in other backtesting software. 

Is the risk management looking right? It should only ever have 10 positions with around 100% of portfolio invested. I don't understand how I frequently get errors that I've run out of margin. That should not be possible.