Back to Community
Talib EMA documentation question
import talib

def initialize(context):  
    context.my_sid = sid(24)

def handle_data(context, data):  
    price_history = history(bar_count=7, frequency='1d', field='price')  
    my_sid_series = price_history[context.my_sid]  
    ema_result = talib.EMA(my_sid_series)  
    print ema_result  
    record(ema=ema_result[-1])  

i just changed the bar_count to 7, why the plot gives me nothing? ema_result are all NAN ?
Any ideas?

9 responses

Hello Eric,

Unless you specify the 'timeperiod' parameter talib.EMA will produce it's first result on the 30th bar i.e. bar-count=30. To use a bar count of seven try:

import talib

def initialize(context):  
    context.my_sid = sid(24)

def handle_data(context, data):  
    price_history = history(bar_count=7, frequency='1d', field='price')  
    my_sid_series = price_history[context.my_sid]  
    ema_result = talib.EMA(my_sid_series, timeperiod=7)  
    print ema_result  
    record(ema=ema_result[-1])  

P.

Hi, Trying to implement talib ema as you explained. i think i have the Ema setup correctly but formula wont run. Im trying to get it to short when price closes below EMA, keep that position (without adding to it) until buy signal occurs, then go long and stay long (without adding to pos.) until short signal happens again.

The formula was running without errors when i used the default .mavg(value) but the values of it seemed to be wrong, so wanted to go over to talib.

Thanks

import talib

def initialize(context):  
    context.security = symbol('AAPL')

def handle_data(context, data):  
    price_history = history(bar_count=11, frequency='1d', field='price')  
    maseries = price_history[context.security]  
    maverage = talib.EMA(maseries, timeperiod=11)  
    current_price = data[context.security].price  
    position = context.portfolio.positions[context.security].amount

    if current_price < maverage and position == 0:  
        order_target_percent(context.security, -1)  
       # log.info("SHORT %s" % (context.security.symbol))  
    elif current_price > maverage and position <= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER SHORT %s" % (context.security.symbol))  
    if current_price > maverage and position == 0:  
        order_target_percent(context.security, 1)  
       # log.info("LONG %s" % (context.security.symbol))  
    elif current_price < maverage and position >= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER LONG %s" % (context.security.symbol))  

Hello Darell,

You didn't say what error you were getting. Was it 'The truth value of an array with more than one element is ambiguous'? If so you need to use the most recent value in the 'maverage' series. You may also want to run once per day.

P.

Clone Algorithm
95
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
import talib

def initialize(context):  
    context.security = symbol('AAPL')

    # Create a variable to track the date change
    context.yesterday = None
    
    
def handle_data(context, data):  
    # Check for start of a new day
    if get_datetime().date() == context.yesterday:
        return
    context.yesterday = get_datetime().date()
    
    price_history = history(bar_count=11, frequency='1d', field='price')  
    maseries = price_history[context.security]  
    maverage = talib.EMA(maseries, timeperiod=11)[-1]  
    current_price = data[context.security].price  
    position = context.portfolio.positions[context.security].amount

    if current_price < maverage and position == 0:  
        order_target_percent(context.security, -1)  
       # log.info("SHORT %s" % (context.security.symbol))  
    elif current_price > maverage and position <= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER SHORT %s" % (context.security.symbol))  
    if current_price > maverage and position == 0:  
        order_target_percent(context.security, 1)  
       # log.info("LONG %s" % (context.security.symbol))  
    elif current_price < maverage and position >= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER LONG %s" % (context.security.symbol))  
There was a runtime error.

Hi
- Yes, the error was ambiguous, but i see you fixed that and how
- Once per day does not work since it sais History can only be used on minute mode
- Did i have the Long/Short position part right, so that it would hold the Short pos. until Long triggers (without adding to pos. each day as long as signal is valid)

Added plots for talib Ema, standard Ma and Price. Its really weird since they are not what any charting soft will show - they are basically static so theres something really wrong with the formula. 11Day Ema should have varying values. Included the code this time

In brief, i want to understand how to make the formula to these rules
1. Take trades based on talib EMA (Daily)
2. Flip between long and short positions (without adding to position [either long or short] once its been established)

Thanks for your time

Clone Algorithm
15
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
import talib

def initialize(context):  
    context.security = symbol('VXX')

    # Create a variable to track the date change
    context.yesterday = None
    
    
def handle_data(context, data):  
    # added for comparison the standard ma
    mavg_standard = data[context.security].mavg(11)
    
    # Check for start of a new day
    if get_datetime().date() == context.yesterday:
        return
    context.yesterday = get_datetime().date()
    
    price_history = history(bar_count=11, frequency='1d', field='price')  
    maseries = price_history[context.security]  
    maverage = talib.EMA(maseries, timeperiod=11)[-1]  
    current_price = data[context.security].price  
    position = context.portfolio.positions[context.security].amount

    if current_price < maverage and position == 0:  
        order_target_percent(context.security, -1)  
       # log.info("SHORT %s" % (context.security.symbol))  
    elif current_price > maverage and position <= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER SHORT %s" % (context.security.symbol))  
    if current_price > maverage and position == 0:  
        order_target_percent(context.security, 1)  
       # log.info("LONG %s" % (context.security.symbol))  
    elif current_price < maverage and position >= 0:  
        order_target_percent(context.security, 0)  
        # log.info("COVER LONG %s" % (context.security.symbol)
        
        record(Price=current_price)
        record(Ema=maverage)
        record(MaStandard=mavg_standard)
There was a runtime error.

Darell,
It looks like you have the right idea. the plot will not show you the values on a minute to minute scale. If I'm reading this correctly, you want to reverse the position when the price crosses the ema, if that's the case, the only thing I see is that you go to a zero position, then wait for the signal again before reversing it. This example reverses the position right away, I also plotted the position size.

You are not adding/subtracting to the position once it's established because you use the current position size to make your decision, it's good practice to do it that way (and check for open orders).

David

Clone Algorithm
72
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
import talib

def initialize(context):  
    context.security = symbol('VXX')
    set_benchmark(context.security)
    
    # Create a variable to track the date change
    context.yesterday = None
    
    
def handle_data(context, data):  
    # added for comparison the standard ma
    mavg_standard = data[context.security].mavg(11)
    record(position=context.portfolio.positions[context.security].amount)
    # Check for start of a new day
    if get_datetime().date() == context.yesterday:
        return
    context.yesterday = get_datetime().date()
    
    price_history = history(bar_count=11, frequency='1d', field='price')  
    maseries = price_history[context.security]  
    maverage = talib.EMA(maseries, timeperiod=11)[-1]  
    current_price = data[context.security].price  
    position = context.portfolio.positions[context.security].amount

    if current_price < maverage and position >= 0:  
        order_target_percent(context.security, -1)  
       # log.info("SHORT %s" % (context.security.symbol))  
    # elif current_price > maverage and position <= 0:  
        # order_target_percent(context.security, 0)  
        # # log.info("COVER SHORT %s" % (context.security.symbol))  
    if current_price > maverage and position <= 0:  
        order_target_percent(context.security, 1)  
       # log.info("LONG %s" % (context.security.symbol))  
    # elif current_price < maverage and position >= 0:  
        # order_target_percent(context.security, 0)  
        # # log.info("COVER LONG %s" % (context.security.symbol)
        
    record(Price=current_price)
    record(Ema=maverage)
    record(MaStandard=mavg_standard)
There was a runtime error.

David and Peter, thanks for your time

What is the benefit of using talib's ewma instead of pandas ewma?

No benefit really, I'm not sure if one is faster than the other. I personally prefer to use pandas if they have a built in function for what I'm using. The benefit of talib is that it has things like RSI and other indicators that pandas doesn't natively support.

Why is talib EMA different than what other charting platforms like tradingview? i compared both emas at same position, and the difference was of 1$ change, do anybody knows?