Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trying to build a simple mean reversion algo

Hi everyone!

I'm pretty a newbie. I'm trying to code an algo exploiting what seems to me a behaviour I see in market.
I think that there are "waves" in the market affecting similar stocks, in this case technological stocks : when a "positive" wave hits the market all these stocks tend to go up or down, according to the direction of this "wave". Sometimes, while staring at the books of these stocks, I see some of them taking a direction and other lagging behind, the ones lagging behind tend to go up as the others in the group.
In this particular case the one lagging behind would be AMD, and the other ones in the pool Intel, Nvidia and TTWO.

How would you set the 2 main parameters of my simple algo, the number of minute bars and the % change in the price of the securities triggering an order? Any general suggestion?

Thanks

1 response

You're already setting those in the algorithm, are you asking help optimizing those two values to a specific data set?

The code is a tad verbose, the following code block is equivalent to yours but it's easier to read (and to maintain).
Notice how it's actually comprised of just four lines:

_threshold = 0.0025  
_bars = 20

_timeframe = '1d'  
_field = 'price'


def initialize(context):  
    context.securities = {  
        'amd': sid(351),  
        'intel': sid(3951),  
        'nvidia': sid(19725),  
        'ttwo': sid(16820),  
        'nasdaq': sid(19920),  
    }

    set_benchmark(context.securities['amd'])  
    set_commission(commission.PerTrade(cost=0.0))  
    set_slippage(slippage.FixedSlippage(spread=0.00))


def handle_data(context, data):  
    securities = context.securities  
    # Argument of pct_change is (_bars-1) in order to have one numeric result  
    fetched = history(_bars, _timeframe, _field).pct_change(_bars - 1)  
    changes = {security.symbol: fetched[security][-1] for security in fetched}

    #print("%r" % changes)

    # Values in a set are all smaller than a value T if the maximum value of  
    # the set is smaller than T, they are all bigger than a value T if the  
    # maximum value of the set is bigger than T  
    condition_long = (min(changes.values()) > _threshold)  
    condition_short = (max(changes.values()) < -_threshold)

    if condition_long:  
        order_target(securities['amd'], +10000)

    elif condition_short:  
        order_target(securities['amd'], -10000)  

Read a pandas tutorial, it's got lots of nice features.

edit: fix typo