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

Hi, I am new to python, but have programmed before in other languages. I don't see any examples of how to calculate exponential moving average (EMA) or even simple moving averages. In the help page it mentions "matype" parameter and gives a brief description of

Moving average types
Some of the TA-Lib methods have an integer matype parameter. Here's the list of moving average types:
0: SMA (simple)
1: EMA (exponential)
2: WMA (weighted)
3: DEMA (double exponential)
4: TEMA (triple exponential)
5: TRIMA (triangular)
6: KAMA (Kaufman adaptive)
7: MAMA (Mesa adaptive)
8: T3 (triple exponential T3)

but it simply don't give any examples of how to code them in. Thanks in advance

3 responses

talib can be tough to wrap one's head around, it takes different inputs for different sets of indicators.
There are some examples in the Source tab at https://www.quantopian.com/posts/talib-indicators
and searches like this can be pretty productive, limiting the results to quantopian.com:

https://www.google.com/#q=%22import+talib%22+site:quantopian.com

If you want to use a simple moving average, you can use the built-in mavg() function:

context.stock = symbol('AAPL')

# get the 5 day simple moving average  
mavg = data[context.stock].mavg(5)  
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

One could diddle with the simple framework I proposed. (Never really heard from the group whether expando style properties was a bad pattern or not.)

See this post technical-framework.

The idea of the framework was to attach at runtime properties for any indicator one desired to calculate

   data[stock].SMA = sma[stock][-1]  

and then to use those properties at will:

    for stock in data:  
        if (data[stock].SMA < data[stock].close_price):  
            # do stuff  

But the essence for your use was the below code. Changing the MAType and providing any additional arguments based on the MAType should provide with a means of isolating the MA calculation.

LongMAPeriods = 200

def initialize(context):  
    schedule_function(CalculateLongMA)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
def CalculateLongMA(context, data):  
    closes   = history(LongMAPeriods, "1d", "close_price")  
    closes   = closes.dropna(axis=1)  
    valid    = [sid for sid in closes if sid in data]  
    closes   = closes[valid]  
    sma      = closes.apply(talib.MA, timeperiod = LongMAPeriods, matype = MAType.SMA).dropna()  
    for stock in sma:  
        data[stock].Trigger += 1 if data[stock].close_price > sma[stock][-1] else 0  
        data[stock].SMA = sma[stock][-1]

class MAType():  
    SMA   = 0; EMA   = 1; WMA   = 2; DEMA  = 3; TEMA  = 4;  
    TRIMA = 5; KAMA  = 6; MAMA  = 7; T3    = 8