[Numpy-discussion] How to get the prices of Moving Averages Crosses?

Andre Lopes lopes80andre@gmail....
Tue Mar 1 10:07:23 CST 2011


I'm new to Numpy. I'm doing some tests with some Stock Market Quotes

My struggle right now is "how to get the values of the moving averages
crosses", I send an image in attach to illustrate what I'm trying to

I'm using the this computation to get when the moving averages
crosses, but when I look at the graph, the values doesn't seem ok.

# Get when the ma20 cross ma50
equal = np.round(ma20,2)==np.round(ma50,2)
dates_cross  = (dates[equal])
prices_cross = (prices[equal])

The full code is this:
# Modules
import datetime
import numpy as np
import matplotlib.finance as finance
import matplotlib.mlab as mlab
import matplotlib.pyplot as plot

# Define quote
startdate = datetime.date(2008,10,1)
today = enddate = datetime.date.today()
ticker = 'uso'

# Catch CSV
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)

r = mlab.csv2rec(fh); fh.close()
# Order by Desc

### Methods Begin
def moving_average(x, n, type='simple'):
    compute an n period moving average.

    type is 'simple' | 'exponential'

    x = np.asarray(x)
    if type=='simple':
        weights = np.ones(n)
        weights = np.exp(np.linspace(-1., 0., n))

    weights /= weights.sum()

    a =  np.convolve(x, weights, mode='full')[:len(x)]
    a[:n] = a[n]
    return a
### Methods End

prices = r.adj_close
dates = r.date
ma20 = moving_average(prices, 20, type='simple')
ma50 = moving_average(prices, 50, type='simple')

# Get when the ma20 cross ma50
equal = np.round(ma20,2)==np.round(ma50,2)
dates_cross  = (dates[equal])
prices_cross = (prices[equal])

# Ver se a ma20 > ma50
# ma20_greater_than_ma50 = np.round(ma20,2) > np.round(ma50,2)
# dates_ma20_greater_than_ma50  = (dates[ma20_greater_than_ma50])
# prices_ma20_greater_than_ma50 = (prices[ma20_greater_than_ma50])

print dates_cross
print prices_cross
#print dates_ma20_greater_than_ma50
#print prices_ma20_greater_than_ma50


Someone can give me some clues?

Best Regards,
-------------- next part --------------
A non-text attachment was scrubbed...
Name: moving_averages_cross.PNG
Type: image/png
Size: 28319 bytes
Desc: not available
Url : http://mail.scipy.org/pipermail/numpy-discussion/attachments/20110301/57e73b78/attachment-0001.png 

More information about the NumPy-Discussion mailing list