我有一个 dataframe,其中索引列是股票代码。我的问题是,如何遍历股票代码列表并向 dataframe 添加一列,其中包含每个代码的股票价格?
这就是我的想法...
import pandas as pd
from pandas import DataFrame
from matplotlib import pyplot as plt
import pandas.io.data as web
import datetime as dt
start = '2005-01-01'
end = dt.datetime.today()
for index, row in df.iterrows():
df['Price'] = web.DataReader(df['Symbol'], 'yahoo', start, end)
我的数据框看起来像这样......
In [1]: %run screen.py
symbol core
16 LEA 1
17 GT 1
18 TEN 1
19 HELE 1
20 CTB 1
请您参考如下方法:
DataReader 返回一系列价格,所以我刚刚请求了过去几天的收盘价。然后我使用 .iloc[-1, :] 获取最后一行的所有价格,这将是最近的收盘价。
today = dt.date.today()
prices = web.DataReader(df.symbol, 'yahoo',
start=today + dt.timedelta(-5), end=today)['Close'].iloc[-1, :]
您现在需要将价格转换为 DataFrame,以便将其合并到您的原始 DataFrame:
prices = pd.DataFrame(prices)
close_date = prices.columns[0]
prices.columns = ['closing_price']
df = df.merge(prices, how='left', left_on='symbol', right_index=True)
df['close date'] = close_date
>>> df
symbol core closing_price close date
0 LEA 1 113.150002 2015-10-06
1 GT 1 30.389999 2015-10-06
2 TEN 1 47.900002 2015-10-06
3 HLE 1 77.950000 2015-10-06
4 CTB 1 39.840000 2015-10-06
