Matplotlib与Numpy数学

1 投票
4 回答
1414 浏览
提问于 2025-04-16 12:44

我正在尝试学习Matplotlib和Numpy这两个库,但感觉有点困难。

我正在做一个小项目,想要开始使用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?我应该买哪些书呢?

请给我一些建议。

祝好,

4 个回答

2

这里有一个可以开始的列表,你可以浏览一下,找到对你最重要的部分:

  1. Python教程 http://docs.python.org/tutorial/
  2. Numpy用户指南 http://docs.scipy.org/doc/
  3. Matplotlib用户指南 http://matplotlib.sourceforge.net/users/index.html
  4. Numpy/Scipy的额外文档来源 http://www.scipy.org/Additional_Documentation

你可能还想订阅一下numpy和/或matplotlib的邮件列表。

3

我觉得你不一定需要去买书。更好(而且更便宜)的办法是看看网上的教程,比如:

这个链接

http://matplotlib.sourceforge.net/examples/index.html

你可以从这些文档中找资料,或者搜索相关的关键词来拼凑出你需要的信息。从你提供的代码来看(假设是你写的),你对numpy有一些了解。不过,如果你想得到更具体的帮助,你需要更详细地描述你遇到的问题。

5

我同意Josh的看法,但我想补充一下matplotlib的图库:

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

我大多数的图表都是直接复制一些接近我想要的样子,然后再根据我的需求进行修改。matplotlib的图库里有很多这样的例子。

撰写回答