Python - Finance Matplotlib related
I'm new to python and I'm testing the finance matploblib module.
I need to get the price and date values when the ma20 = ma50
Give me a clue on how to do this.
Here is my code:
# 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(2005,1,1)
today = enddate = datetime.date.today()
ticker = 'nvda'
# Catch CSV
fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
# From CSV to REACARRAY
r = mlab.csv2rec(fh); fh.close()
# Order by Desc
r.sort()
### Met开发者_开发知识库hods 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)
else:
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')
plot.plot(prices)
plot.plot(ma20)
plot.plot(ma50)
plot.show()
Since you are using numpy, you can use numpy's boolean indexing for arrays:
equal = ma20==ma50
print(dates[equal])
print(prices[equal])
'equal' is a boolean array of the same length as dates and prices. Numpy then picks from dates and prices only those entries where equal==True, or, equivalently, ma20==ma50.
精彩评论