matrices are not aligned error message

John picture John · Sep 5, 2016 · Viewed 7.8k times · Source

I have the following dataframe of returns

ret
Out[3]: 
Symbol            FX      OGDC       PIB       WTI
Date                                              
2010-03-02  0.000443  0.006928  0.000000  0.012375
2010-03-03 -0.000690 -0.007873  0.000171  0.014824
2010-03-04 -0.001354  0.001545  0.000007 -0.008195
2010-03-05 -0.001578  0.008796 -0.000164  0.015955

And the following weights for each symbol:

df3
Out[4]: 
  Symbol    Weight
0   OGDC  0.182022
1    WTI  0.534814
2     FX  0.131243
3    PIB  0.151921

I am trying to get a weighted return for each day and tried:

port_ret = ret.dot(df3)

but I get the following error message:

ValueError: matrices are not aligned

My objective is to have a weighted return for each date such that, for example 2010-03-02 would be as follows:

weighted_ret = 0.000443*.131243+.006928*.182022+0.000*0.151921+0.012375*.534814 = 0.007937512

I am not sure why I am getting this error but would be very happy for an alternative solution to the weighted return

Answer

Boud picture Boud · Sep 5, 2016

You have two columns in your weight matrix:

df3.shape
Out[38]: (4, 2)

Set the index to Symbol on that matrix to get the proper dot:

ret.dot(df3.set_index('Symbol'))
Out[39]:
              Weight
Date
2010-03-02  0.007938
2010-03-03  0.006430
2010-03-04 -0.004278
2010-03-05  0.009902