How to create muli-index columns reflecting different calculation results from a data frame

36 Views Asked by At

I have a data frame "Hist" in which I'd like to add another level for different RSI calculations from the ta library. This is an excerpt my current data frame with stock prices:

Hist.head()

Date          AAPL    AMC       AYX
6/15/2020    85.75   5.80    142.94 
6/16/2020    88.02   5.56    145.69 
6/17/2020    87.90   5.42    150.99 
6/18/2020    87.93   5.63    160.78 
6/19/2020    87.43   5.52    163.56

And this is an example of the data frame I'd like to create using a loop of the RSI method for both 5 day and 14 day results:

indicator_rsi = RSIIndicator(close=Hist["Ticker"], window=5) # Calculates RSI for 5 days
Hist['RSI_5'] = indicator_rsi.rsi()


      Stock Prices                    RSI_5                  RSI_14     
Date          AAPL    AMC       AYX    AAPL     AMC     AYX    AAPL     AMC     AYX
6/15/2020    85.75   5.80    142.94      ##      ##      ##      ##      ##      ## 
6/16/2020    88.02   5.56    145.69      ##      ##      ##      ##      ##      ## 
6/17/2020    87.90   5.42    150.99      ##      ##      ##      ##      ##      ## 
6/18/2020    87.93   5.63    160.78      ##      ##      ##      ##      ##      ## 
6/19/2020    87.43   5.52    163.56      ##      ##      ##      ##      ##      ##
1

There are 1 best solutions below

0
On

IIUC, you can try something like this:

df = df.set_index('Date') #Move Date into the index if not there already
w_list = [5, 15] # list of windows
pd.concat([df.apply(RSIIndicator, w=i) for i in w_list], axis=1, 
           keys=[f'RSI_{i}' for i in w_list])

Output:

               RSI_5                        RSI_15                   
                AAPL       AMC      AYX       AAPL       AMC      AYX
Date                                                                 
6/15/2020  85.750000  5.800000  142.940  85.750000  5.800000  142.940
6/16/2020  86.885000  5.680000  144.315  86.885000  5.680000  144.315
6/17/2020  87.223333  5.593333  146.540  87.223333  5.593333  146.540
6/18/2020  87.400000  5.602500  150.100  87.400000  5.602500  150.100
6/19/2020  87.406000  5.586000  152.792  87.406000  5.586000  152.792

Here, I am using pd.concat with axis=1 and the keys parameter to create a multiindex for the column headers. These numbers are simulated using rolling mean calculation not your actual RSIIndicator function.