Home > Mobile >  comparing in a multiindex pandas
comparing in a multiindex pandas

Time:10-15

I have the following code which determines if a stock has a 52 week high:

import pandas as pd
from pandas_datareader import data as web
import numpy as np

tickers = 'goog', 'fb', 'aapl', 'tsla'
df = web.DataReader(tickers, 'yahoo')
for t in tickers:
    df['52wk'] = df['High'][t].asfreq('D').rolling(window=52*7, min_periods=1).max()
    df['52weekhigh'] =  np.where(df['High'][t] >= df['52wk'][t].shift(-1), 'True', 'False')

I am having trouble with the last line where i compare the previous row of stock's 52wk high with current stock [high]. It gives the following error:

KeyError: 'goog'

Could you please advise why am i not able to access goog

CodePudding user response:

You need to use the MultiIndex in the assignment as well:

for t in tickers:
    df[('52wk', t)] = df['High'][t].asfreq('D').rolling(window=52*7, min_periods=1).max()
    df[('52weekhigh', t)] =  np.where(df['High'][t] >= df['52wk'][t].shift(-1), 'True', 'False')
  • Related