Python analytics

| | No TrackBacks

These use the numpy library, I believe. I adapted them to work in a more vanilla python way as I could not get my head around numpy.

Exponential moving average

def ema(s, n):
    """
    returns an n period exponential moving average for
    the time series s

    s is a list ordered from oldest (index 0) to most recent
    (index -1) n is an integer

    returns a numeric array of the exponential moving average
    """
    s = array(s)
    ema = []
    j = 1
    #get n sma first and calculate the next n period ema
    sma = sum(s[:n]) / n
    multiplier = 2 / float(1 + n)
    ema.append(sma)
    #EMA(current) = ( (Price(current) - EMA(prev) ) xMultiplier) + EMA(prev)
    ema.append(( (s[n] - sma) * multiplier) + sma)
    #now calculate the rest of the values
    for i in s[n+1:]:
        tmp = ( (i - ema[j]) * multiplier) + ema[j]
        j = j + 1
        ema.append(tmp)
    return ema

Simple moving average

def movavg(s, n):
    """
    returns an n period moving average for the time series s
       
    s is a list ordered from oldest (index 0) to most recent (index -1)
    n is an integer

        returns a numeric array of the moving average

    See also ema in this module for the exponential moving average.
    """
    s = array(s)
    c = cumsum(s)
    return (c[n-1:] - c[:-n+1]) / float(n-1)

No TrackBacks

TrackBack URL: http://www.iwebthereforeiam.com/cgi-bin/mt/mt-tb.cgi/231

Leave a comment

Verification (needed to reduce spam):

Pages

OpenID accepted here Learn more about OpenID
Powered by Movable Type 4.32-en

About this Entry

This page contains a single entry by Hugh Brown published on April 26, 2007 5:13 AM.

Excel: Find unique values in column was the previous entry in this blog.

Third party python packages is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.