I have two data frames with the same date index and column names. I want to search after the n largest values each row, then go back to the other dataframe and search for the values one day later (one row below).
This is about financial data. I want to test the forward performance of the n best stocks regarding an indicator value of these stocks. So I search first for the n-largest indicator values of these stocks each day (first dataframe) and try to get the performance data (second dataframe) of them one day later or one row below. example:
import pandas as pd
df = pd.DataFrame({
'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'],
'a':[24, 11.2, 10.3, 16],
'b':[10.5, 12, 11.4, 13],
'c':[11, 11.6, 13, 15],
'd':[17, 10.5, 13, 15],
'e':[22, 21, 14.5, 13],
'f':[12.7, 10, 10, 10],
'g':[14, 13, 13, 12],
'h':[13.8, 19, 13, 12],
'i':[11, 14, 10.4, 16.3],
'j':[10, 10, 19, 15.6]})
df = df.set_index('Date')
df1 = pd.DataFrame({
'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04'],
'a':[0, 1.2, 0.3, 6],
'b':[0.5, 2, 1.4, 3],
'c':[2, 1.6, 3, 5],
'd':[7, 0.5, 2.4, 5],
'e':[4, 2, 4.5, 1],
'f':[2.7, 0, 0, 0],
'g':[4, 3, 3, 2],
'h':[3.8, 1, 9, 2],
'i':[1, 4, 0.4, 6.3],
'j':[0, 0, 9, 5.6]})
df1 = df1.set_index('Date')
In the next step I would filter the e.g. 3 largest values each row.
df_test = df.apply(pd.Series.nlargest,axis=1, n=3)
or I filter after the column names which are the 3 largest stocks each day
df_large = df.apply(lambda s: s.abs().nlargest(3).index.tolist(), axis=1)
df_large = df_large.to_frame()
df_large [['Top1', 'Top2', 'Top3']] = pd.DataFrame(df_large[0].values.tolist(),index=df_large.index)
df_large = df_large.drop([0], axis=1)
But I don't know if I'm on the right way. I simply don't how to connect the new dataframe with the one I want to take the performance data the day after. Maybe there is a easier way (for sure there will be)
At the end I want to have a result like this:
