我计算单个股票的回报如下:
data = pd.read_csv(r'**file**.csv')
data.index = data.Date
data['Return %'] = data['AAPL'].pct_change(-1)*100
data
out put:
Date AAPL Return %
Data
2020-09-11 2020-09-11 56.00 0.000000
2020-09-10 2020-09-10 56.00 -3.879162
2020-09-09 2020-09-09 58.26 2.138850
2020-09-08 2020-09-08 57.04 -2.211555
2020-09-04 2020-09-04 58.33 0.882048
2020-09-03 2020-09-03 57.82 -3.585126
2020-09-02 2020-09-02 59.97 -0.133222
现在,我保存了许多其他 csv 文件作为股票代码,我想使用这些代码中的每一个来执行上述相同的计算。
最重要的是,我想打印每个符号回报的最佳日期的报告。
如果需要更多详细信息,请告诉我。
提前致谢!
- I think the best option for your data is to read the files into a dictionary of dataframes.
- Use
pathlib
and .glob
创建所有文件的列表
- 使用字典理解来创建数据帧的字典。
- 字典可以用字典的标准方式迭代,
dict.items()
.
-
df_dict[k]
寻址每个数据帧,其中k
是 dict 键,即文件名。
- 从你上次question https://stackoverflow.com/questions/63864337,我期望
.csv
要读入的文件Date
列,而不是两列。
- The numeric data for each file should be in the column at index 0, after
Date
is set as the index.
- 由于每个文件的列名称不同,因此最好使用.iloc https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iloc.html解决该专栏。
-
:
表示所有行并且0
是数值数据的列索引。
-
df_dict.keys()
将返回所有键的列表
- 单独访问数据框
df_dict[key]
.
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)