Advertisement
Guest User

Minimisation at a specific point

a guest
Apr 14th, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. def objective_function(params):
  2.     interp_func = interp1d(STK, params, kind='cubic', fill_value='extrapolate')
  3.     interpolated_ivs = interp_func(STK)
  4.     return np.sum((interpolated_ivs - IV) ** 2)
  5.  
  6. def constraint(params):
  7.     interp_func = interp1d(STK, params, kind='cubic', fill_value='extrapolate')
  8.     atm_IV = interp_func(CMP)
  9.     min_IV = min(interp_func(np.arange(min(STK), max(STK) + 0.0001, 0.0001)))
  10.     return atm_IV - min_IV
  11.  
  12. initial_params = IV
  13.  
  14. constraints = {'type': 'ineq', 'fun': constraint}
  15.  
  16. result = minimize(objective_function, initial_params, constraints=constraints)
  17.  
  18. if result.success:
  19.     optimized_params = result.x
  20.     adj_interp_func = interp1d(STK, optimized_params, kind='cubic', fill_value='extrapolate')
  21.  
  22.     interpolated_strikes = np.round(np.arange(min(STK), max(STK) + 0.0001, 0.0001),4)
  23.     interpolated_ivs = np.round(adj_interp_func(interpolated_strikes),4)
  24.    
  25.     for i in range(len(interpolated_strikes)):
  26.         delta_call = black_scholes_delta(CMP, interpolated_strikes[i], DTE_N, r, sigma, 'C')
  27.         delta_put = black_scholes_delta(CMP, interpolated_strikes[i], DTE_N, r, sigma, 'P')
  28.         call_deltas.append(delta_call)
  29.         put_deltas.append(delta_put)
  30.    
  31.     del_25_c_strike = interpolated_strikes[np.argmin(np.abs(np.array(call_deltas)-0.25))]
  32.     del_25_p_strike = interpolated_strikes[np.argmin(np.abs(np.array(put_deltas)+0.25))]
  33.    
  34.     strikes_reqd = [CMP, del_25_c_strike, del_25_p_strike]
  35.     IV_reqd = []
  36.     for i in strikes_reqd:
  37.         IV_reqd.append(interpolated_ivs[np.argmin(np.abs(interpolated_strikes-i))])
  38. else:
  39.     print("Optimization failed:", result.message)
  40.    
  41. print(f"Strikes - ATM, 25_Delta_Call, 25_Delta_Put are: {strikes_reqd}")
  42. print(f"IVs - ATM, 25_Delta_Call, 25_Delta_Put are: {IV_reqd}")
  43.  
  44. # Plot the original data and the interpolated curve
  45. plt.figure(figsize=(8, 4))
  46. plt.plot(interpolated_strikes, interpolated_ivs, label='Adjusted Interpolated Curve')
  47. plt.scatter(STK, IV_N, color='red', label='Market Data')
  48. plt.title('Interpolated IV_F1 vs. F1')
  49. plt.xlabel('F1')
  50. plt.ylabel('IV_F1')
  51. plt.legend()
  52. plt.grid(True)
  53. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement