I have a pandas DataFrame with years as index, one column with stock ID, a second column with returns. The DataFrame has ~200k rows. I want to add 3 additional columns, with the cumulative returns of each stock in the next 5, 10 and 20 years respectively. To this purpose, I am grouping by the ID column and applying a function to the grouped object, which I show in a simple example below. I knew this was going to take some time, but as of now the code has been in execution for 23 hours and is still running.
I have 2 questions then:
- Why exactly is python taking so much time to execute the code? Where is the bottleneck?
- Any ideas on how can I change the code to make it faster?
Here is my code, applied to a simpler example.
In [1]: import pandas as pd
In [2]: simple_df = pd.DataFrame([[1,1,1,2,2],[0.1,0.05,0.15,0.3,0.2]], columns=[2010,2011,2012,2011,2012], index=['ID','Return']).T
In [3]: simple_df
Out[3]:
ID Return
2010 1.0 0.10
2011 1.0 0.05
2012 1.0 0.15
2011 2.0 0.30
2012 2.0 0.20
In [4]: grouped = simple_df.groupby('ID', sort=False)
In [5]: create_df = lambda x: pd.DataFrame({i: x.Return.shift(-i) for i in range(0,3)})
In [6]: df_1 = grouped.apply(create_df)
In [7]: df_1
Out[7]:
0 1 2
2010 0.10 0.05 0.15
2011 0.05 0.15 NaN
2012 0.15 NaN NaN
2011 0.30 0.20 NaN
2012 0.20 NaN NaN
In [8]: df_2 =(df_1+1).cumprod(axis=1)-1
In [9]: df_2
Out[9]:
0 1 2
2010 0.10 0.1550 0.32825
2011 0.05 0.2075 NaN
2012 0.15 NaN NaN
2011 0.30 0.5600 NaN
2012 0.20 NaN NaN
In [10]: simple_df['Return_3y'] = df_2.iloc[:,2]
In [11]: simple_df
Out[11]:
ID Return Return_3y
2010 1.0 0.10 0.32825
2011 1.0 0.05 NaN
2012 1.0 0.15 NaN
2011 2.0 0.30 NaN
2012 2.0 0.20 NaN