Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How do I keep this from making my portfolio seriously overdrawn?

The backtest indicates that this algorithm becomes incredibly overdrawn. First why? Second how? and third how can I fix this? thanks

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
def initialize(context):  
    context.aapl = sid(24)  
    context

# Will be called on every trade event for the securities you specify.  
def handle_data(context, data):  
    # Implement your algorithm logic here.  

    averageapple = data[context.aapl].mavg(1)  
    amountofshares = round(context.portfolio.cash / data[context.aapl].price, 0)  
    numbersn = amountofshares  
    # data[sid(X)] holds the trade event data for that security.  
    # data.portfolio holds the current portfolio state.

    # Place orders with the order(SID, amount) method.

    # TODO: implement your own logic here.  
    if data[context.aapl] == averageapple:  
      order(context.aapl, +amountofshares)  

    if data[context.aapl] > averageapple:  
         order(context.aapl, - numbersn)  
1 response

I think this functionality still needs to be added in to Quantopian (someone correct me if I'm wrong?)

Take a look at the order management in John L's anti-gravity algo.

Imagine your cash is $10. I think the problem comes from shorting shares (for which context.portfolio.cash increases), which are then used to go long, and the subsequent covering of the short (for which context.portfolio.cash decreases) then means you have gone overdrawn.