2011-02-28 35 views
1

我是新來的蟒蛇,我正在測試財務matploblib模塊。Python - 財務Matplotlib相關

我需要得到的價格和日期值時,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() 

回答

3

由於使用numpy的,則可以使用numpy的的布爾索引數組:

equal = ma20==ma50 
print(dates[equal]) 
print(prices[equal]) 

「等於」是相同的長度的一個布爾值陣列日期和價格。 Numpy然後從日期和價格中挑選只有等於== True或者等價於ma20 == ma50的條目。

+0

這是numpy數組中最酷的功能之一。 –

+0

感謝您的回覆。它有效,但只捕獲一個事件,有可能捕獲所有事件?最好的問候, –

+1

問題是小數,等於np.round(ma20,2)== np.round(ma50,2) –