Brian
Brian

Reputation: 737

How to iterate DataFrame column of stock symbols and add a column with the stock price?

I have a dataframe w/ the index column being stock symbols. My question is, how do I loop through the list of stock symbols and add a column to the dataframe with the stock price for each symbol?

Here is where my mind went...

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)

my dataframe looks like this...

In [1]: %run screen.py
   symbol core
16    LEA    1
17     GT    1
18    TEN    1
19   HELE    1
20    CTB    1

Upvotes: 2

Views: 1514

Answers (1)

Alexander
Alexander

Reputation: 109546

The DataReader returns a series of prices, so I've just requested the closing price over the last few days. I then use .iloc[-1, :] to take all prices on the last row which would be the most recent close.

today = dt.date.today()
prices = web.DataReader(df.symbol, 'yahoo', 
                        start=today + dt.timedelta(-5), end=today)['Close'].iloc[-1, :]

You now need to convert the prices to a DataFrame in order to merge it to your original 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

Upvotes: 1

Related Questions