如果你只是迭代股票,你可以直接调用它stocks
DataReader(stocks, 'yahoo', datetime(2013, 1, 1), datetime(2013, 8, 1))
您不需要迭代,因为get_data_yahoo
它会为您完成。你会得到 a Panel
,你可以像 a dict
of DataFrame
s 一样使用它。你甚至不需要打电话stocks.keys()
,因为
for key in dict(a=1, b=2, c=3):
print key
将打印
a
b
c
结果如下:
In [3]: p = DataReader(stocks, 'yahoo', datetime.datetime(2013, 1, 1), datetime.datetime(2013, 8, 1))
In [4]: p
Out[4]:
<class 'pandas.core.panel.Panel'>
Dimensions: 6 (items) x 147 (major_axis) x 31 (minor_axis)
Items axis: Open to Adj Close
Major_axis axis: 2013-01-02 00:00:00 to 2013-08-01 00:00:00
Minor_axis axis: AAPL to WDC
如果您希望能够通过属性访问访问股票代码,请执行
In [7]: p.swapaxes('items', 'minor').AAPL
Out[7]:
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 147 entries, 2013-01-02 00:00:00 to 2013-08-01 00:00:00
Data columns (total 6 columns):
Open 147 non-null values
High 147 non-null values
Low 147 non-null values
Close 147 non-null values
Volume 147 non-null values
Adj Close 147 non-null values
dtypes: float64(6)
编辑:操纵结果要比填充 a并用它做一些事情要容易得多。Panel
dict
你可以用它做各种有趣的事情。metric
以下是按、stock
和分组的百分比变化date
:
In [127]: df = p.to_frame(filter_observations=False)
In [128]: res = df.stack().reset_index()
In [129]: res.columns = ['date', 'metric', 'stock', 'value']
In [130]: res.set_index('date').groupby(['metric', 'stock']).apply(lambda x: x.value.pct_change()).stack()
Out[130]:
metric stock date
Adj Close AAPL 2013-01-03 -0.013
2013-01-04 -0.028
2013-01-07 -0.006
2013-01-08 0.003
2013-01-09 -0.016
2013-01-10 0.012
2013-01-11 -0.006
2013-01-14 -0.036
2013-01-15 -0.032
2013-01-16 0.042
2013-01-17 -0.007
2013-01-18 -0.005
2013-01-22 0.010
2013-01-23 0.018
2013-01-24 -0.124
...
Volume WDC 2013-07-12 -0.083
2013-07-15 -0.179
2013-07-16 -0.302
2013-07-17 -0.168
2013-07-18 0.589
2013-07-19 0.003
2013-07-22 0.049
2013-07-23 0.526
2013-07-24 0.176
2013-07-25 0.616
2013-07-26 -0.363
2013-07-29 -0.357
2013-07-30 0.554
2013-07-31 -0.252
2013-08-01 -0.158
Length: 27010, dtype: float64
天空是极限pandas
!