我想计算每天 returns 的股票
I want to calculate daily returns in the stocks
Closing_Date AAL_Close AAPL_Close
665 2015-01-12 49.580002 27.312500
666 2015-01-13 50.400002 27.555000
667 2015-01-14 49.410000 27.450001
668 2015-01-15 49.410000 26.705000
669 2015-01-16 49.810001 26.497499
我想用今天的股价除以昨天的股价。第一行将导致 Nan 或 empty 。它每天计算 returns .
我想用今天的股价除以昨天的股价。第一行将导致 Nan 或 empty 。它每天计算 returns .
假设您有所有连续的日期:
df['Closing_Date'] = pd.to_datetime(df['Closing_Date'])
df2 = df.set_index('Closing_Date')
df2.div(df2.shift(1))
或者如果你真的想依赖之前的日期:
df['Closing_Date'] = pd.to_datetime(df['Closing_Date'])
df2 = df.set_index('Closing_Date')
df2.div(df2.reindex(df2.index-pd.Timedelta('1d')).values)
输出:
AAL_Close AAPL_Close
Closing_Date
2015-01-12 NaN NaN
2015-01-13 1.016539 1.008879
2015-01-14 0.980357 0.996189
2015-01-15 1.000000 0.972860
2015-01-16 1.008096 0.992230
Closing_Date AAL_Close AAPL_Close
665 2015-01-12 49.580002 27.312500
666 2015-01-13 50.400002 27.555000
667 2015-01-14 49.410000 27.450001
668 2015-01-15 49.410000 26.705000
669 2015-01-16 49.810001 26.497499
我想用今天的股价除以昨天的股价。第一行将导致 Nan 或 empty 。它每天计算 returns .
我想用今天的股价除以昨天的股价。第一行将导致 Nan 或 empty 。它每天计算 returns .
假设您有所有连续的日期:
df['Closing_Date'] = pd.to_datetime(df['Closing_Date'])
df2 = df.set_index('Closing_Date')
df2.div(df2.shift(1))
或者如果你真的想依赖之前的日期:
df['Closing_Date'] = pd.to_datetime(df['Closing_Date'])
df2 = df.set_index('Closing_Date')
df2.div(df2.reindex(df2.index-pd.Timedelta('1d')).values)
输出:
AAL_Close AAPL_Close
Closing_Date
2015-01-12 NaN NaN
2015-01-13 1.016539 1.008879
2015-01-14 0.980357 0.996189
2015-01-15 1.000000 0.972860
2015-01-16 1.008096 0.992230