对于我的硕士论文,我需要计算给定事件日期的x个股票的预期回报。我编写了以下代码,它符合我的意图(将Fama和法国因素与事件日期样本相匹配)。但是,当我尝试将其导出到Excel时,我似乎无法获得正确的输出。即它不包含列标题,如日期,fama和amp;的名称。法国因素和相应的行。
有人有解决方法吗?任何改进都很高兴。这是我的代码:
import pandas as pd
# Data import
ff_five = pd.read_excel('C:/Users/MBV/Desktop/cmon.xlsx',
infer_datetime_format=True)
df = pd.read_csv('C:/Users/MBV/Desktop/4.csv', parse_dates=True,
infer_datetime_format=True)
# Converting dates to datetime
df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True)
# Creating an empty placeholder
end_date = []
# Iterating over the event dates, creating a start and end date 60 months
apart
for index, row in df.iterrows():
end_da = row['Date']-pd.DateOffset(months=60)
end_date.append(end_da)
end_date_df = pd.DataFrame(data=end_date)
m = pd.merge(end_date_df,df,left_index=True,right_index=True)
m.columns = ['Start','End']
ff_factors = []
for index, row in m.iterrows():
ff_five['Date'] = pd.to_datetime(ff_five['Date'])
time_range= (ff_five['Date'] > row['Start']) & (ff_five['Date'] <=
row['End'])
df = ff_five.loc[time_range]
ff_factors.append(df)
编辑: 以下是我尝试从python获取数据的方法。
ff_factors_df = pd.DataFrame(data=ff_factors)
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('estimation_data.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
ff_factors_df.to_csv(writer, sheet_name='Sheet1')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
答案 0 :(得分:1)
要将数据帧输出到csv或excel应该可以使用
完成ff_five.to_excel('Filename.xls')
如果您想要csv,请将excel更改为csv。
好的,我试图解释你想要做的事情而不是很清楚。但是,如果我正确地解释它,您正在尝试根据其他数据创建一些添加列。您可以将它们作为新列放入,而不是创建单独的列表,然后只输出您想要的列。这样的事情可能(必须做出一些假设并创建一些假数据,看看这是否在正确的轨道上):
import pandas as pd
ff_five = pd.DataFrame()
ff_five['Date'] = ["2012-11-01", "2012-11-30"]
df = pd.DataFrame()
df['Date'] = ["2012-12-01", "2012-12-30"]
df['Date'] = pd.to_datetime(df['Date'])
df['End'] = df['Date'] - pd.DateOffset(months=60)
df.columns = ['Start', 'End']
ff_five['Date'] = pd.to_datetime(ff_five['Date'])
df['ff_factor'] = (ff_five['Date'] > df['Start']) & (ff_five['Date'] <= df['End'])
df.to_excel('estimation_data.xlsx', sheet_name='Sheet1')