Home > OS >  Create dataframe of log returns from a dataframe of stock prices - Python
Create dataframe of log returns from a dataframe of stock prices - Python

Time:12-21

I have a dataframe with dates (30/09/2022 to 31/11/2022) and 15 stock prices (wrote 5 as reference) for each of these dates (excluding weekends). My initial idea was to select each column as a vector and proceed with the calculations, but is there a faster way to get the log returns of each stock?

Current Data:

   Date   |  A  |  B  |  C  |  D  |  E  |
 30/09/22 |100.5|151.3|233.4|237.2|38.42|
 01/10/22 |101.5|148.0|237.6|232.2|38.54|
 02/10/22 |102.2|147.6|238.3|231.4|39.32|
 03/10/22 |103.4|145.7|239.2|232.2|39.54|

I would like to keep the format of the table, but replacing the prices for the logarithmic returns.

CodePudding user response:

You can use:

df.set_index('Date').pipe(lambda d: np.log(d.div(d.shift()))).reset_index()

Output:

       Date         A         B         C         D         E
0  30/09/22       NaN       NaN       NaN       NaN       NaN
1  01/10/22  0.009901 -0.022052  0.017835 -0.021305  0.003119
2  02/10/22  0.006873 -0.002706  0.002942 -0.003451  0.020037
3  03/10/22  0.011673 -0.012956  0.003770  0.003451  0.005580
  • Related