我是python的新手,我正在测试财务matploblib模块。
当ma20 = ma50
时,我需要获取价格和日期值告诉我如何做到这一点。
这是我的代码:
# 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()
### 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)
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()
答案 0 :(得分:3)
由于你正在使用numpy,你可以对数组使用numpy的布尔索引:
equal = ma20==ma50
print(dates[equal])
print(prices[equal])
'equal'是一个与日期和价格长度相同的布尔数组。 Numpy然后从日期和价格中选择那些等于== True的条目,或等价地,ma20 == ma50。