0

I imported a csv file and calculate asset value and volatility of a stock.

df = pd.read_csv (r'test.csv')
df['ret_col'] = np.log(df.price) - np.log(df.price.shift(1))
df['sigma_e'] = np.std(df.ret_col)
T = 1

My function is:

def equation(x):
    d1 = (np.log(x[0]/df.face_val_debt) + (df.r_f+x[1]**2/2)*T)/(x[1] * np.sqrt(T))
    d2 = d1 - x[1] * np.sqrt(T)
    res1 = x[0] * norm.cdf(d1) - np.exp(-df.r_f*T) * df.face_val_debt * norm.cdf(d2) - df.v_e
    res2 = x[0] * norm.cdf(d1) * x[1] - df.v_e * df.sigma_e
    return(res1**2+res2**2)

for i, row in df.iterrows():
    x0 = [row["v_e"], row["sigma_e"]]
    result = minimize(equation, x0)
    result
    df.at[i, "v_a"] = list(result['x'])[0]
    df.at[i, "sigma_a"] = list(result['x'])[1]

The error is ValueError: can only convert an array of size 1 to a Python scalar when running minimize(equation, x0). Could anyone explain what is the problem in this case? Thanks.

Hoang Yen
  • 1
  • 1
  • if you are using scipy's minimize you should tag the question appropiately. Have you tried passing x0 as an np.array instead of a list? – Manu Valdés Jan 17 '21 at 07:35
  • Hi Manu, thanks for your reply. I change the line " result = minimize(equation, np.array(x0)) " but now I got an error " ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." – Hoang Yen Jan 17 '21 at 11:40
  • all the references to df in equation are whole columns; I'm not sure this is what you want. you can run equation(x0) to figure out what line is the problem – Manu Valdés Jan 17 '21 at 11:54
  • One more thing is in case V_equity > default_point, initial asset value is set to V_equity then it works fine and results the same as Solver's in Excel. However, in case V_equity < default_point, if initial asset value is set to V_equity, then it results V_asset = V_equity and Solver also cannot solve it. Then I add the condition that initial asset value is set to default_point, then it results V_asset = default_point. Does anyone experience that and how should we set initial guess for asset value in this case? Your comment is highly appreciated. Thank you. – Hoang Yen Jan 25 '21 at 13:25

1 Answers1

0

I put the function after the loop so it works fine. Thank you for your hint.

for i, row in df.iterrows():

def equation(x):

    d1 = (np.log(x[0]/row["default_point"]) + 
    (row["arf_rate"]+x[1]**2/2)*T)/(x[1] * np.sqrt(T))
    
    d2 = d1 - x[1] * np.sqrt(T)
    
    res1 = x[0] * norm.cdf(d1) - np.exp(-row["arf_rate"]*T) * 
    row["default_point"] * norm.cdf(d2) - row["V_equity"]
    
    res2 = (x[0] * norm.cdf(d1) * x[1])/row["asigma_equity"] - 
    row["V_equity"]
    
    return(res1**2+res2**2)
Hoang Yen
  • 1
  • 1