Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Algo Closing None-existing Positions

I am a newb, first and foremost, and starting out fresh. Currently I am trying to build out an Algo that simply follows a 30,60 MAVG.

Right out of the gate, my algo tries dumping position I do not (or should not) have; if my buy criteria is 30MAVG > 60MAVG, and the backtest starts out with just the opposite, I should NOT be sitting on any open positions. However, sell my close criteria is 30MAVG < 60MAVG, it tries to dumping my order amount, which in this case is +/-100%.

What is even odder is that I am getting some returns before any positions are actually opened, aka 30MAVG < 60MAVG (about 75-days into the backtest).

Any I missing something or is this something to do with the IDE?

Additionally, I am trying to figure out how to restricting the number of open orders to X so I am not constantly buying—even if X is a fraction of my overall portfolio—and the buy amount to the current value of said stock:

current_value = data.current(context.stock, "price")

order(context.stock, current_value*1)  

Thanks for any and all help!

1 response

Michael,

Welcome.

Your algo seems to be doing exactly what it's coded to do, but maybe you didn't intend.

First, you questioned "my algo tries dumping position I do not (or should not) have". Your code has exactly two order methods:

order(context.stock, 1)  
order(context.stock, -1)  

Those methods buy and sell, respectively, exactly one share of context.sid (in this case sid(14001)). Selling a share of a stock you don't hold assumes you want to short that stock. The algo isn't 'dumping' stocks you don't own it's simply taking a short position. You probably want to use one of the other order methods like order_target_percentage and then couple it with a check like

if context.sid in context.portfolio.positions:  
    order logic....  

Also note that the 'handle_data' function is automatically called every minute. Your algo tries to buy or sell exactly one share of context.sid every minute (depending on moving_avg30 > or < moving_avg60) . Look at the transactions tab when you run a full backtest and you can see better what your algorithm is doing.

Another note. The poor performance (almost a straight line down) is probably because of commissions. Unless you specifically set a preferred commission the backtest defaults to $0.0075 per share with a $1 minimum cost per trade. Trading 1 share at a time costs you $1.00. Sometimes for initial backtesting it's helpful to set the commission to $0 (just remember to set it back to something realistic unless you are trading on Robinhood).

Good luck,

Dan