我问过如何迭代多个 csv 文件(例如 100 个不同的股票代码文件)并立即计算它们的每日收益。我想知道如何为每个文件调用这些返回的最大/最小值并打印报告。以下是 Trenton McKinney 先生创建的词典:import pandas as pdfrom pathlib import Path# create the path to the filesp = Path('c:/Users/<<user_name>>/Documents/stock_files')# get all the filesfiles = p.glob('*.csv')# created the dict of dataframesdf_dict = {f.stem: pd.read_csv(f, parse_dates=['Date'], index_col='Date') for f in files}# apply calculations to each dataframe and update the dataframe# since the stock data is in column 0 of each dataframe, use .ilocfor k, df in df_dict.items(): df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100问候并感谢您的帮助!
1 回答
米脂
TA贡献1836条经验 获得超3个赞
data_dict = dict() # create an empty dict here
for k, df in df_dict.items():
df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100
# aggregate the max and min of Return
mm = df_dict[k]['Return %'].agg(['max', 'min'])
# add it to the dict, with ticker as the key
data_dict[k] = {'max': mm.max(), 'min': mm.min()}
# convert to a dataframe if you want
mm_df = pd.DataFrame.from_dict(data_dict, orient='index')
# display(mm_df)
max min
aapl 8.70284 -4.90070
msft 6.60377 -4.08443
# save
mm_df.to_csv('max_min_return.csv', index=True)
添加回答
举报
0/150
提交
取消