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

Hi,

I would like to put an order criteria, I basically am trying to ask the algo to identify whenever

n period of MACD < (n-1) period of MACD across large numbers of day.

Why do i get a invalid index to scalar variable?? appreciate!

macd[stock][-1]<macd[stock][-2]

import talib
import numpy as np
import pandas as pd

def initialize(context):

context.stocks = symbols('MMM')  
context.pct_per_stock = 1.0  
schedule_function(rebalance, date_rules.every_day(), time_rules.market_close(minutes=1))  

def rebalance(context, data):

prices = data.history(context.stocks,'price',200, '1d')  


macd = prices.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)  


for stock in context.stocks:  
    current_position = context.portfolio.positions[stock].amount  


    if macd[stock] > 0 and macd[stock][-1]<macd[stock][-2]:  
        order_target_percent(stock, context.pct_per_stock)  


    elif macd[stock] < 0 and current_position > 0:  
        order_target(stock, 0)  


record(macd=macd[symbol('MMM')])

def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):

macd, signal, hist = talib.MACD(prices,  
                                fastperiod=fastperiod,  
                                slowperiod=slowperiod,  
                                signalperiod=signalperiod)  
return macd[-1] - signal[-1]  
1 response

Invalid index to scalar variable means that you are trying to find on a date time index a scalar variable.

Try this one: macd.ix[-1, stock] and macd.ix[-2, stock]