我問過如何迭代多個 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
提交
取消