如何迭代股票代码的DataFrame列并添加股票价格列?

时间:2015-10-07 14:25:58

标签: python pandas dataframe

我有一个dataframe w /索引列是股票代码。我的问题是,如何遍历股票代码列表并在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

1 个答案:

答案 0 :(得分: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,以便将其合并到原始数据框中:

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