Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Execution of moving average slope idea

Hi guys,

This is my first code and I struggle with 2/3 entries.
The idea is to run a function at every schedule that loops through every stock, creates a normalized slope for its 200 day moving average and buys the highest (note: which is within 2 standard deviations of the mean of all slopes).

Problem #1: to calculate the slope of the MA, I need to get yesterdays MA in the loop. I use
moving_average_yesterday = moving_average.iloc[-1]
but this gives me an error. How can I go about it?

Problem #2: how do I tell in the order function to liquidate everything and buy full portfolio worth of the selected stock?

Would be very grateful for any help!

2 responses

Have some code to hard sell all shares (stock by stock).

Stick this in your if statement:

number_of_shares = context.portfolio.positions[stock.sid].amount  
order(stock, -number_of_shares)  

Beautiful! Thank you John, I hope that solves one of the issues.

That's how my last two lines look now

number_of_shares = context.portfolio.positions[stock.sid].amount
order(stock, -number_of_shares)

order_percent(max_slope[1], 1)