本文介绍了从数据框字典中调用报告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是以前的,我问过如何遍历多个csv文件(例如100个不同的股票代码文件)并一次计算其每日收益.我想知道如何为每个文件的返回值调用最大/最小值,并打印报告.
I'm my previous question, I have asked how to iterate over multiple csv files (like 100 different files of stocks symbols) and calculate their daily returns at once. I would like to know how to call max/min values for these returns for each file and print a report.
以下是根据特伦顿·麦金尼先生创建的词典:
Here is the creation of dictionaries as per Mr. Trenton McKinney:
import pandas as pd
from pathlib import Path
# create the path to the files
p = Path('c:/Users/<<user_name>>/Documents/stock_files')
# get all the files
files = p.glob('*.csv')
# created the dict of dataframes
df_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 .iloc
for k, df in df_dict.items():
df_dict[k]['Return %'] = df.iloc[:, 0].pct_change(-1)*100
致谢,谢谢您的帮助!
推荐答案
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)
这篇关于从数据框字典中调用报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!