2011-03-01 34 views
1

我想要获得Matplotlib和Numpy的一些牵引力,但它不是很容易。Matplotlib和Numpy Math

我在做一个小项目开始处理Matplotlib和numpy的,但我被困...

下面是代码:

# 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(2010,10,1) 
today = enddate = datetime.date.today() 
ticker = 'uso' 

# 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') 

# Get when ma20 crosses ma50 
equal = np.round(ma20,1)==np.round(ma50,1) 
dates_cross = (dates[equal]) 
prices_cross = (prices[equal]) 

# Get when ma20 > ma50 
ma20_greater_than_ma50 = np.round(ma20,1) > np.round(ma50,1) 
dates_ma20_greater_than_ma50 = (dates[ma20_greater_than_ma50]) 
prices_ma20_greater_than_ma50 = (prices[ma20_greater_than_ma50]) 

print dates_ma20_greater_than_ma50 
print prices_ma20_greater_than_ma50 

现在我需要做这样的事情:

store the price of the "price_cross" 
see if one day after the "ma20_greater_than_ma50" statment is true, if true store the price as "price of the one day after" 
now do "next price_cross" - "price of the one day after" (price2 - price1) for all occurences 

我该怎么做这个数学和更重要的。我如何获得Matplotlib和Numpy的牵引力。我应该买什么书?

给我一些线索。

最好的问候,

回答

5

我同意乔希,但想添加matplotlib画廊:

http://matplotlib.sourceforge.net/gallery.html

我的大部分地块的开始直接复制了接近我想要的东西,然后修改它适合我的需要。 matplotlib画廊有很多这样的例子。

1

matplotlib和numpy有一个巨大的有用函数列表,你应该在执行之前总是谷歌。

例如请参阅matplotlib movavg函数。