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]  
Clone Algorithm
47
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 595e8158aaee4c5352d1705f
There was a runtime error.
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]