如果您正在自学 Python,请继续使用自己的阅读器来实现csv
,然后自己计算平均计算。这是一个很好的练习。
但是,如果您想减少编码并花更多时间进行分析,请使用类似pandas
(或至少numpy
)的东西。该pandas
库擅长此类数据分析。
以下 ipython 会话显示了使用pandas
. (如果您不使用 ipython,那么这是我强烈建议您学习的另一个工具。)在本次会议中,我阅读了一个包含 Apple 股票数据的 CSV 文件。数据文件“aapl.csv”如下所示:
Date,Open,High,Low,Close,Volume,Adj Close
2013-02-25,453.85,455.12,442.57,442.80,13276100,442.80
2013-02-22,449.25,451.60,446.60,450.81,11798600,450.81
2013-02-21,446.00,449.17,442.82,446.06,15970800,446.06
2013-02-20,457.69,457.69,448.80,448.85,17010800,448.85
2013-02-19,461.10,462.73,453.85,459.99,15563700,459.99
2013-02-15,468.85,470.16,459.92,460.16,13990900,460.16
2013-02-14,464.52,471.64,464.02,466.59,12688400,466.59
...
1984-09-14,27.62,28.50,27.62,27.87,8826400,3.13
1984-09-13,27.50,27.62,27.50,27.50,7429600,3.09
1984-09-12,26.87,27.00,26.12,26.12,4773600,2.94
1984-09-11,26.62,27.37,26.62,26.87,5444000,3.02
1984-09-10,26.50,26.62,25.87,26.37,2346400,2.97
1984-09-07,26.50,26.87,26.25,26.50,2981600,2.98
导入熊猫库:
In [1]: import pandas as pd
使用“日期”列作为索引将数据读入 DataFrame:
In [2]: aapl = pd.read_csv('aapl.csv', index_col=0, parse_dates=True)
按升序对索引进行排序:
In [3]: aapl = aapl.sort()
先看看前几条记录:
In [4]: aapl.head()
Out[4]:
Open High Low Close Volume Adj Close
Date
1984-09-07 26.50 26.87 26.25 26.50 2981600 2.98
1984-09-10 26.50 26.62 25.87 26.37 2346400 2.97
1984-09-11 26.62 27.37 26.62 26.87 5444000 3.02
1984-09-12 26.87 27.00 26.12 26.12 4773600 2.94
1984-09-13 27.50 27.62 27.50 27.50 7429600 3.09
将数据重采样为每月。默认情况下,使用每日值的平均值:
In [5]: monthly = aapl.resample('1M')
In [6]: monthly.head()
Out[6]:
Open High Low Close Volume Adj Close
Date
1984-09-30 26.981250 27.333125 26.606250 26.738750 4807300.000000 3.007500
1984-10-31 25.035652 25.313478 24.780435 24.806957 5559408.695652 2.788696
1984-11-30 24.545238 24.782857 24.188095 24.236190 5749561.904762 2.724286
1984-12-31 27.060000 27.378500 26.841000 26.947500 6195360.000000 3.031500
1985-01-31 29.520000 29.855909 29.140000 29.253182 10353818.181818 3.289091
绘制每月数据的“关闭”列:
In [7]: monthly.plot(y='Close')
Out[7]: <matplotlib.axes.AxesSubplot at 0x45ff4d0>
查看“关闭”列:
In [8]: monthly['Close']
Out[8]:
Date
1984-09-30 26.738750
1984-10-31 24.806957
1984-11-30 24.236190
1984-12-31 26.947500
1985-01-31 29.253182
1985-02-28 28.089474
1985-03-31 22.741429
1985-04-30 21.425238
1985-05-31 19.656818
1985-06-30 16.399000
1985-07-31 17.185455
1985-08-31 15.098636
1985-09-30 15.738500
1985-10-31 16.940000
1985-11-30 19.460000
...
2011-12-31 392.930476
2012-01-31 428.578000
2012-02-29 497.571000
2012-03-31 577.507727
2012-04-30 606.003000
2012-05-31 564.673182
2012-06-30 574.562381
2012-07-31 601.068095
2012-08-31 642.696087
2012-09-30 681.568421
2012-10-31 634.714286
2012-11-30 564.345714
2012-12-31 532.055000
2013-01-31 497.822381
2013-02-28 459.026875
Freq: M, Name: Close, Length: 342
这是该方法生成的图plot
: