Back to Community
TA-lib SAR Help

Hi everyone,

It's my first time on Quantopian, and my partner and I are trying to implement a simple SAR indicator based algorithm for practice. Our methodology is as follows:

def handle_data(context, data):  
    # Implement your algorithm logic here.

    # data[sid(X)] holds the trade event data for that security.  
    # context.portfolio holds the current portfolio state.

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

    # TODO: implement your own logic here.  
    # Configuring SAR indicator conditions  
    high = history(30, '1d', 'high')  
    low = history(30, '1d', 'low')  
    optInAcceleration = .01  
    optInMaximum = .20  
    # Initializing the initial portfolio conditions  
    current_positions = context.portfolio.positions  
    for stock in data:  
        # Initializing necessary values for each iteration  
        max_positions = context.max_universe  
        cash = context.portfolio.cash  
        position_allocation = cash / max_positions  
        current_position_value = context.portfolio.positions[stock].amount  
        stock_price = data[stock].price  
        SAR = talib.SAR(high[stock], low[stock], optInAcceleration, optInMaximum)  
        is_current_position = current_position_value != 0  
        bullish_sar = SAR[29] < stock_price  
        bearish_sar = SAR[29] > stock_price  
        if bullish_sar:  
             if is_current_position:  
                 order(stock, -1 * context.portfolio.positions[stock].amount)  
             else:  
                 order_value(stock, position_allocation)  
        elif bearish_sar:  
            if is_current_position:  
                order_target_percent(stock, 0)  
            else:  
                order_value(stock, -1 * position_allocation)  

1) If SAR is bullish, AND there is no current position in the stock, go long.
2) If SAR is bullish, and there IS a position in the stock, sell to close.

1) If SAR is bearish, AND there is no current position in the stock, go short.
2) If SAR Is bearish, and there IS a position in the stock, buy to close.

The problem is, SAR doesn't seem to be behaving properly and neither is our algorithm. We keep getting compounding amounts of our position, and portfolio cash doesn't seem to be updating. The backtests reflect an exponential degree of capital allocated to one position.

Any help is appreciated! Ask any questions, I'd glad to clarify various things.