简体   繁体   中英

How index MultiIndex dataframe to get matrices in pandas?

I have this original df with 2 stocks and their returns for 5 consecutive trading days.

d = {'1': [-0.015, 0.026, 0.031, 0.012, 0.045], '2': [-0.011, 0.032, -0.007, -0.007, 0.012]}
df = pd.DataFrame(data = d)
df.index.name = 'Ticker #'
df
            
Ticker #    1     2
0       -0.015  -0.011
1        0.026   0.032
2        0.031  -0.007
3        0.012  -0.007
4        0.045   0.012

Then I created a rolling windows for covariance matrices for df , stored in df2 :

df2 = df.rolling(2).cov().dropna()
df2
                    1            2
  Ticker #          
1   1         8.405000e-04  8.815000e-04
    2         8.815000e-04  9.245000e-04
2   1         1.250000e-05 -9.750000e-05
    2        -9.750000e-05  7.605000e-04
3   1         1.805000e-04 -1.084202e-19
    2        -1.084202e-19  1.355253e-20
4   1         5.445000e-04  3.135000e-04
    2         3.135000e-04  1.805000e-04

I want to multiply each matrix created from each rolling window to a 2D array arr where:

arr = np.array([[1, 2], [3, 4], [5,6], [7,8]])

and the formula is formula = arr.T*df2*arr where I want it to product an array of 4 values. How can I subset or index df2 so that I can multiply each matrix element by its corresponding array element?

For obtaining the individuals matrices you can use pd.roll , withnp.cov , for example:

import pandas as pd
import numpy as np

d = {'1': [-0.015, 0.026, 0.031, 0.012, 0.045],
     '2': [-0.011, 0.032, -0.007, -0.007, 0.012]}
df = pd.DataFrame(data=d)
df.index.name = 'Ticker #'

np_res = pd.DataFrame(np.vstack([np.cov(roll.T) for roll in df.rolling(2)])).dropna()
pd_res = df.rolling(2).cov().dropna()

print(np.allclose(np_res, pd_res))

Output

True

To multiply by the array, do:

arr = np.array([[1, 2], [3, 4], [5,6], [7,8]])

def multiply(c, a):
    if np.isnan(c).any():
        return c
    return (c @ a.T) @ a


res = pd.DataFrame(np.vstack([multiply(np.cov(roll.T), arr) for roll in df.rolling(2)]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM