pandas 尝试循环股票价格收盘时出现Python错误

ttygqcqt  于 2023-02-20  发布在  Python
关注(0)|答案(1)|浏览(126)

我尝试循环股票价格csv,以添加列,如投资组合权重等,以便在一个 Dataframe 中建立一个投资组合进行分析。然而,当循环时,我得到了一个错误,我不明白:

gsk_df = web.DataReader("GSK.L", 'yahoo', start=start, end=end)
ocdo_df = web.DataReader("OCDO.L", 'yahoo', start=start, end=end)
rbs_df = web.DataReader("RBS.L", 'yahoo', start=start, end=end)
svt_df = web.DataReader("SVT.L", 'yahoo', start=start, end=end)
iii_df = pd.read_csv("iii (1).csv", parse_dates=['Date'])

#close of each stock

bp_close = bp_df["Adj Close"]
gsk_close = gsk_df["Adj Close"]
ocdo_close = ocdo_df["Adj Close"]
rbs_close = rbs_df["Adj Close"]
svt_close = svt_df["Adj Close"]
iii_close = iii_df["Adj Close"]

#adding normalised returns for portfolio
for stock_df in (bp_close, gsk_close, ocdo_close, rbs_close, svt_close, iii_close):
    stock_df['Norm return'] = stock_df['Adj Close']/stock_df.iloc[0]['Adj Close']

#adding portfolio weights

for stock_df, allocation in zip((bp_close, gsk_close, ocdo_close, rbs_close, svt_close, iii_close),[.0881,.233,.160,.0776,.304,.137]):
    stock_df['Allocation']=stock_df['Norm return']*allocation
    
#portfolio position value column
for stock_df in (bp_close, gsk_close, ocdo_close, rbs_close, svt_close, iii_close):
    stock_df['Position'] = stock_df['Allocation']*6503800000
    
print(bp_close.head())

下面是错误:
键错误:"调整关闭"

I had to change the "Adjusted_close" heading to "Adj close" in the iii csv as it was from another data set and the for loop would not function with different column headers. Thanks for the help.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/iFv6N.jpg
rekjcdws

rekjcdws1#

假设这些系列的列名为stock,您可以通过将它们连接到 Dataframe 中并避免KeyError来避免循环

stocks = ['GSK.L', 'OCDO.L', 'RBS.L', 'SVT.L']
df = web.DataReader(stocks, 'yahoo',start,end).reset_index(drop=True)
iii_df = pd.read_csv("iii (1).csv", parse_dates=['Date']) # reset_index if needed

stock_df = pd.concat([df, iii_close], axis=1, ignore_index=True)
stock_df['Norm return'] = stock_df / stock_df.loc[0]
stock_df['Allocation'] = stock_df['Norm return'] * [.0881,.233,.160,.0776,.304,.137]
stock_df['Position'] = stock_df['Allocation'] * 6503800000

相关问题