我可以从yahoo finance加载多个股票代码,但是在将新列保存到csv之前我无法添加新列

时间:2016-09-18 01:34:11

标签: python csv pandas dataframe

以下代码首先从pnls中的yahoo finance上传数据。它成功实现了这一目标。然后我有代码,我想在pnls中为已加载的数据添加列。这部分不成功。最后,我想将pnl保存到csv文件,如果列更改不在代码中,它会成功。

我需要回答的问题是,在将pnl保存到csv之前,如何成功进行多列更改?

from pandas_datareader import data as dreader
import pandas as pd
from datetime import datetime
import numpy as np

# Symbols is a list of all the ticker symbols that I am downloading from yahoo finance
symbols = ['tvix','pall','pplt','sivr','jju','nib','jo','jjc','bal','jjg','ld','cdw','gaz','jjn','pgm',
           'sgg','jjt','grn','oil','gld','corn','soyb','weat','uhn','uga','bunl','jgbl','bndx','aunz',
           'cemb','emhy','vwob','ald','udn','fxa','fxb'] 

#This gets the data from yahoo finance 
pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols}

 # These are the new columns that I want to add
pnls['PofChg'] = ((pnls.Close - pnls.Open) / (pnls.Open)) * 100 
pnls['U_D_F']  = np.where(pnls.PofChg > 0 , 'Up', np.where(pnls.PofChg == 0, 'Flat', 'Down'));pnls
pnls['Up_Down']   = pnls.Close.diff()
pnls['Close%pd']  = pnls.Close.pct_change()*100


# This saves the current ticker to a csv file
for df_name in pnls:
    pnls.get(df_name).to_csv("{}_data.csv".format(df_name), index=True, header=True)

这是我运行代码时出现的错误

Traceback (most recent call last):
  File "YahooFinanceDataGetter.py", line 14, in <module>
    pnls['PofChg'] = ((pnls.Close - pnls.Open) / (pnls.Open)) * 100
AttributeError: 'dict' object has no attribute 'Close'
Press any key to continue . . .

1 个答案:

答案 0 :(得分:1)

该行

pnls = {i:dreader.DataReader(i,'yahoo','1985-01-01',datetime.today()) for i in symbols}

构建一个python dict(使用dictionary comprehension)。要检查这一点,您可以运行以下命令:

assert type(pnls) == dict

这是错误消息告诉您的内容:AttributeError: 'dict' object has no attribute 'Close'

DataFrames实际上是字典的值。要对它们应用转换,您可以迭代字典的values()

for df in pnls.values():
    df = ((df.Close - df.Open) / (df.Open)) * 100 
    ...