我是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()发布于 2011-03-01 01:18:14
由于您使用的是numpy,因此可以对数组使用numpy的布尔索引:
equal = ma20==ma50
print(dates[equal])
print(prices[equal])‘'equal’是一个与日期和价格长度相同的布尔数组。然后,Numpy从日期中挑选,并只为那些包含equal==True或ma20==ma50的条目定价。
https://stackoverflow.com/questions/5144426
复制相似问题