-2

I want to create a dataframe that takes stock1, stock2 and optimal as the index;

while the mean, std, sharpe, weight, wealth are the columns. I have already generated the respective column values. I need help in generating the expected output.

Input:

stock1 = pd.Series({
                            'mean': mean1,
                            'std': std1,
                            'sharpe': mean1 / std1,
                            'weight': w1,
                            'wealth': stk1_wealth
                          })

stock2 = pd.Series({
                            'mean': mean2,
                            'std': std2,
                            'sharpe': mean2 / std2,
                            'weight': w2,
                            'wealth': stk2_wealth
                          })

optimal = pd.Series({
                            'mean': returns,
                            'std': volatility,
                            'sharpe': sharpe,
                            'weight': w1+w2,
                            'wealth': opt_wealth
                             })

stats_df = stk1_stats_df.append(stk2_stats_df).append(optimal_stats_df)

Actual output:

mean       0.00155525
std         0.0113922
sharpe       0.136519
weight       0.479314
wealth    [[14555.0]]
mean       0.00188339
std         0.0124908
sharpe       0.150783
weight       0.520686
wealth    [[15756.0]]
mean       0.00172611
std        0.00957114
sharpe       0.180345
weight              1
wealth          15180
dtype: object

Expected output:

           mean      std      sharpe     weight       wealth
stock1   0.0016   0.0113      0.1365       0.48      14555.0
stock2   0.0018   0.0124      0.1507       0.52      15756.0
optimal  0.0017   0.0096      0.1803       1.0       15180.0
  • I'm not sure how to apply, because I got this error message: `ValueError: Length of passed values is 3, index implies 5.` – Zoarkado Zenos Aug 16 '20 at 17:10
  • 1
    It applies because you are trying to use `pd.Series` as a row in a `pd.DataFrame`, and that is what the question is about. – Algebra8 Aug 16 '20 at 17:12
  • 1
    The `ValueError` could be from some other part of your code. Conceptually, the recipe proposed in the first answer should solve your problem. – Algebra8 Aug 16 '20 at 17:12

1 Answers1

1

Assuming you want to create a brand new DataFrame from the Series objects, you need to include their index in the construction of the dataframe.

>>> pd.DataFrame([stock1, stock2, optimal], index=['stock1', 'stock2', 'optimal'])
         mean  std  sharpe  weight  wealth
stock1   10.0  5.0     2.0     3.0    30.0
stock2   44.0  5.0     2.0     3.0    30.0
optimal  56.0  5.0     2.0     3.0    30.0
Algebra8
  • 1,115
  • 1
  • 10
  • 23