简体   繁体   English

尝试遍历股票价格时出现 Python 错误关闭

[英]Python error when trying to loop through stock price closes

I am trying to loop through stock price csvs in order to add columns such as portfolio weight etc. in order to build a portfolio to analyse in one dataframe.我正在尝试遍历股票价格 csvs 以添加投资组合权重等列,以便在一个数据框中构建投资组合进行分析。 When looping however, I get an error which I do not understand:但是,在循环时,我收到一个我不明白的错误:

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())

Here is the error:这是错误:

runfile('C:/Users/Joe Shiafa Pierce/.spyder-py3/portfolio.py', wdir='C:/Users/Joe Shiafa Pierce/.spyder-py3')
Traceback (most recent call last):

  File "<ipython-input-82-6a3db40a9a10>", line 1, in <module>
    runfile('C:/Users/Joe Shiafa Pierce/.spyder-py3/portfolio.py', wdir='C:/Users/Joe Shiafa Pierce/.spyder-py3')

  File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Joe Shiafa Pierce/.spyder-py3/portfolio.py", line 34, in <module>
    stock_df['Norm return'] = stock_df['Adj Close']/stock_df.iloc[0]['Adj Close']

  File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\pandas\core\series.py", line 868, in __getitem__
    result = self.index.get_value(self, key)

  File "C:\Users\Joe Shiafa Pierce\Anaconda3\lib\site-packages\pandas\core\indexes\datetimes.py", line 958, in get_value
    raise KeyError(key)

KeyError: 'Adj Close'

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.我不得不将 iii csv 中的“Adjusted_close”标题更改为“Adj close”,因为它来自另一个数据集,并且 for 循环无法在不同的列标题下运行。 Thanks for the help.谢谢您的帮助。

在此处输入图片说明

assuming these series have the stock as their column name, you can avoid the loops by concatenating them into a dataframe and avoiding the KeyError假设这些系列以股票作为其列名,您可以通过将它们连接到一个数据帧并避免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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM