Home > Enterprise >  I want to calculate daily returns in the stocks
I want to calculate daily returns in the stocks

Time:04-05

    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

I want to divide stock price of today by stock price of yesterday . The first row will result in Nan or empty . It is calculating for daily returns .

I want to divide stock price of today by stock price of yesterday . The first row will result in Nan or empty . It is calculating for daily returns .

CodePudding user response:

Assuming that you have all consecutive dates:

df['Closing_Date'] = pd.to_datetime(df['Closing_Date'])
df2 = df.set_index('Closing_Date')

df2.div(df2.shift(1))

Or if you really want to rely on the previous date:

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)

output:

              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
  • Related