Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Chaotic deals

My algo makes chaotic, inexplicable deals. Could anyone point at the bug?

import talib  
import numpy as np  
import pandas as pd  
from quantopian.algorithm import order_optimal_portfolio  
import quantopian.optimize as opt


def initialize(context):  
    context.appl = sid(24)  
def handle_data(context, data):  
    history= data.history(context.appl, fields="price", bar_count=2000*60, frequency="1m")#.resample('H').last()  
    history = history.dropna()    

    #calculations EMAs  
    long_ema_last = pd.Series(talib.EMA(history,timeperiod=1000)).iloc[-1]  
    long_ema_previous = pd.Series(talib.EMA(history,timeperiod=60)).iloc[-2]  


    short_ema_last = pd.Series(talib.EMA(history, timeperiod=60*60)).iloc[-1]  
    short_ema_previous = pd.Series(talib.EMA(history, timeperiod=60*60)).iloc[-2]  

    # open conditions  
    golong = (long_ema_last/long_ema_previous > 1) and (short_ema_last / short_ema_previous > 1)  
    goshort = (long_ema_last/long_ema_previous < 1) and (short_ema_last / short_ema_previous < 1)


    if golong:  
        log.info("conditions to GO LONG")  
        order_target_percent(context.appl, 1)  

    if goshort:  
        log.info("conditions to GO SHORT")  
        order_target_percent(context.appl, -1)  


    # exit conditions  
    if (not goshort and not golong):  
            log.info("conditions to EXIT")  
            order_target_percent(context.appl, 0)  
1 response

You should generally check for any open orders before ordering more. This is taken care of behind the scenes if one uses the 'order_optimal_portfolio' method but needs to be accounted for when using 'order_target_percent'.

Take a look at these couple of posts
https://www.quantopian.com/posts/order-target-percent-ordering-too-much
https://www.quantopian.com/posts/new-orders-filled-without-of-my-control

Good luck!