def _vis_proposals(im, dets, thresh=0.5): """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return class_name = 'obj' im = im[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(im, aspect='equal') for i in inds: bbox = dets[i, :4] score = dets[i, -1] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2] - bbox[0], bbox[3] - bbox[1], fill=False, edgecolor='red', linewidth=3.5)) ax.text(bbox[0], bbox[1] - 2, '{:s} {:.3f}'.format(class_name, score), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') ax.set_title(('{} detections with ' 'p({} | box) >= {:.1f}').format(class_name, class_name, thresh), fontsize=14) plt.axis('off') plt.tight_layout() plt.draw()
center = np.array([0.1,-0.15,0.]) widths_vec = np.ones(3) obs = PolygonalObstacle(center, widths_vec) fig, ax = plt.subplots() plot_rectangle(ax, center[idx], widths_vec[idx]) plt.xlim([-1.5*widths_vec[idx[0]],2.5*widths_vec[idx[0]]]) plt.ylim([-1.5*widths_vec[idx[1]],2.5*widths_vec[idx[1]]]) if idx[0] == 0: plt.xlabel('x') elif idx[0] == 1: plt.xlabel('y') else: plt.xlabel('z') if idx[1] == 0: plt.ylabel('x') elif idx[1] == 1: plt.ylabel('y') else: plt.ylabel('z') cursor = Cursor(ax, obs) fig.canvas.mpl_connect('motion_notify_event', cursor.mouse_move) plt.draw() plt.show()
def showGraph_Heston(self): mpl = self.oMplCanvas_Heston.canvas [s1, s2, s3, s4] = mpl.axes S0 = self.S0_Heston K = self.K_Heston r = self.r_Heston q = self.q_Heston σ = self.σ_Heston t = self.t_Heston κ = self.κ_Heston θ = self.θ_Heston ρ = self.ρ_Heston v0 = self.v0_Heston Δt = self.Δt self.S_Heston = self.SN_Heston[self.path_Heston] s1.clear() s1.set_title('Heston Stochastic Volatility Model $S_t$', fontsize=11, color='brown') s1.yaxis.set_tick_params(labelright=False, labelleft=True) s1.axvline(x=self.t_Heston, color="blue", alpha=0.5, linewidth=2) s1.grid(True) s1.plot(self.S_Heston, 'b', lw=0.5, label='present value') s2.clear() s2.set_title(r'$ln{\frac{S_{t+Δt}}{S_t}}$', fontsize=14, color='brown') s2.axvline(x=self.t_Heston, color="blue", alpha=0.5, linewidth=2) s2.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format)) #s2.axvline(x=self.t, color="blue", alpha=0.5, linewidth=1) s2.grid(True) M = self.S_Heston[t] # these are the returns for the given path returns = [ log(self.S_Heston[t + 1]) - log(self.S_Heston[t]) for t in range(0, self.S_Heston.size - 1) ] s2.plot(returns, 'r', lw=0.5, label='return') #s2.axvline(x=slope, color="g", alpha=0.75, linewidth=2) #s2.plot(x, z_put, 'b-.', lw=1.5, label='payoff') ########################################### # Plot s3: return distribution histogram ########################################### returns = [] for i in range(self.N): ret = [ log(self.SN_Heston[i, t + 1]) - log(self.SN_Heston[i, t]) for t in range(0, self.S_Heston.size - 1) ] returns.append(ret) self.returns_Heston = returns #returns = [ log(self.S_Heston[t+1]) - log(self.S_Heston[t]) for t in range(0, self.S_Heston.size-1)] #returns_dist_at_t = [ log(self.SN[:, t+1]) - log(self.SN[:, t]) for t in range(0, self.SN.size-1)] # we want the simulated return distribution at time a particular time t in range(0, self.S_Heston.size-1) returns = [ log(self.SN_Heston[:, self.t_Heston]) - log(self.SN_Heston[:, self.t_Heston - 1]) ] s3.clear() s3.hist(returns, density=False, bins=20, orientation='vertical', alpha=0.40, color='green') s3.set_title(r"Return Distribution", fontsize=11, color='brown') s3.yaxis.set_ticks_position("right") s3.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) s3.grid(True) s3.tick_params(axis='both', which='major', labelsize=6) s3.set_xlabel('Return', fontsize=8, color='brown') ############################################################### # Plot s4: stochastic volatility distribution histogram ############################################################### volatility_at_t = self.volatility_Heston[:, self.t_Heston] s4.clear() s4.hist(volatility_at_t, bins=25, density=True, orientation='vertical', alpha=0.70, color='orange') s4.set_title(r"Stochastic Volatility Distribution", fontsize=11, color='brown') s4.xaxis.set_major_formatter(FuncFormatter('{0:.1}'.format)) s4.grid(True) s4.tick_params(axis='both', which='major', labelsize=6) s4.set_xlabel('volatility', fontsize=8, color='brown') ### draw all graphs mpl.fig.set_visible(True) mpl.draw()
def showGraph(self): mpl = self.oMplCanvas.canvas [s1, s2, s3, s4] = mpl.axes S0 = self.S0 K = self.K r = self.r q = self.q σ = self.σ t = self.t λ = self.λ γ = self.γ δ = self.δ Δt = self.Δt self.S = self.SN[self.path_Merton] s1.clear() s1.grid(True) s1.set_title('Metron Jump Diffusion $S_t$', fontsize=14, color='brown') s1.yaxis.set_tick_params(labelright=False, labelleft=True) s1.axvline(x=self.t, color="blue", alpha=0.5, linewidth=2) s1.plot(self.S, 'b', lw=0.5, label='present value') s2.clear() s2.set_title(r'$ln{\frac{S_{t+Δt}}{S_t}}$', fontsize=14, color='brown') s2.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format)) s2.axvline(x=self.t, color="blue", alpha=0.5, linewidth=2) s2.grid(True) M = self.S[t] returns = [ log(self.S[t + 1]) - log(self.S[t]) for t in range(0, self.S.size - 1) ] s2.plot(returns, 'r', lw=0.5, label='return') #s2.axvline(x=slope, color="g", alpha=0.75, linewidth=2) #s2.plot(x, z_put, 'b-.', lw=1.5, label='payoff') ########################################### # Plot s3: return distribution histogram ########################################### returns = [] for i in range(self.N): ret = [ log(self.SN[i, t + 1]) - log(self.SN[i, t]) for t in range(0, self.S.size - 1) ] returns.append(ret) self.returns = returns #returns = [ log(self.S[t+1]) - log(self.S[t]) for t in range(0, self.S.size-1)] #returns_dist_at_t = [ log(self.SN[:, t+1]) - log(self.SN[:, t]) for t in range(0, self.SN.size-1)] returns = [log(self.SN[:, self.t]) - log(self.SN[:, self.t - 1])] s3.clear() s3.hist(returns, density=True, bins=20, orientation='vertical', alpha=0.40, color='green') s3.set_title(r"Return Distribution", fontsize=11, color='brown') s3.yaxis.set_ticks_position("right") s3.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) s3.grid(True) s3.tick_params(axis='both', which='major', labelsize=6) s3.set_xlabel('Return', fontsize=8, color='brown') ############################################################### # Plot s4: No. of jumps distribution histogram ############################################################### s4.set_visible(True) s4.clear() data_simulated_poisson = [ self.poisson_jumps[n, :self.t + 1].sum() for n in range(0, self.N) ] s4.hist( data_simulated_poisson, bins=range(0, max (6,max(data_simulated_poisson)+1)), \ density=True, rwidth=0.5, align='left', facecolor='orange', alpha=0.75) s4.set_title(r"Poisson Jump Distribution", fontsize=11, color='brown') #s4.xaxis.set_major_formatter(FuncFormatter('{0}'.format)) s4.yaxis.set_major_formatter(FuncFormatter('{0:.0%}'.format)) s4.xaxis.set_major_locator(MaxNLocator(integer=True)) s4.grid(True) s4.tick_params(axis='both', which='major', labelsize=6) s4.set_xlabel('No. of jumps', fontsize=8, color='brown') mpl.fig.set_visible(True) mpl.draw()
def update_line(hl, new_data): hl.set_xdata(numpy.append(hl.get_xdata(), new_data[0])) hl.set_ydata(numpy.append(hl.get_ydata(), new_data[1])) hl.set_zdata(numpy.append(hl.get_zdata(), new_data[2])) plt.draw()
def showGraph(self, graphtype): mpl = self.oMplCanvas.canvas [[s1, s2], [s3, s4]] = mpl.axes mpl2 = self.oMplCanvas_Theta_T2M.canvas s5 = mpl2.axes[0] if self.greek != 'Θ' or not self.check_Theta_T2M.isChecked(): window.oMplCanvas_Theta_T2M.hide() else: window.oMplCanvas_Theta_T2M.show() #S0 = 100; K = 100; r = 0.025; q = 0.005; σ = 0.2; T = 1.0 K = self.K r = self.r q = self.q σ = self.σ T = self.T slope = self.slope x = np.linspace(40, 160, 51) y_call = bsm.bs_call_price(x, K, r, q, σ, T) y_put = bsm.bs_put_price(x, K, r, q, σ, T) z_call = bsm.payoff_call(x, K) z_put = bsm.payoff_put(x, K) # call parabola print(f"Parabola K={K}, r={r}, q={q}, σ={σ}, T={T}") a, b, d = bsm.taylor_parabola(slope, K, r, q, σ, T, category='call') print(f'a={a:.2f}, b={b:.2f}, d={d:.2f}') taylor2_call = a * x * x + b * x + d a, b = bsm.taylor_linear(slope, K, r, q, σ, T, category='call') taylor1_call = a * x + b # put parabola a, b, d = bsm.taylor_parabola(slope, K, r, q, σ, T, category='put') taylor2_put = a * x * x + b * x + d a, b = bsm.taylor_linear(slope, K, r, q, σ, T, category='put') taylor1_put = a * x + b greek_call = None greek_put = None if graphtype == 'Δ': greek_call = delta_call = np.exp(-q * T) * bsm.N( bsm.d1(x, K, r, q, σ, T)) greek_put = delta_put = -np.exp( -q * T) * bsm.N(-bsm.d1(x, K, r, q, σ, T)) elif graphtype == 'Γ': greek_call = greek_put = gamma_call = bsm.gamma(x, K, r, q, σ, T, category='call') elif graphtype == 'V': greek_call = greek_put = vega_put = bsm.vega(x, K, r, q, σ, T, category='put') elif graphtype == 'Θ': greek_call = theta_call = bsm.theta(x, K, r, q, σ, T, category='call') greek_put = theta_put = bsm.theta(x, K, r, q, σ, T, category='put') elif graphtype == 'ρ': greek_call = rho_call = bsm.rho(x, K, r, q, σ, T, category='call') greek_put = rho_put = bsm.rho(x, K, r, q, σ, T, category='put') fac = 0.6 # shrink factor for Taylor polynomials s1.clear() s1.set_title('Call', fontsize=14, color='brown') s1.yaxis.set_tick_params(labelright=False, labelleft=True) s1.set_xlabel('$S_0$') s1.grid(True) s1.plot(x, y_call, 'r', lw=1.5, label='value') s1.axvline(x=slope, color="g", alpha=0.5, linewidth=1) s1.plot(x, z_call, 'b-.', lw=1.5, label='payoff') s1.plot(slope, bsm.bs_call_price(slope, K, r, q, σ, T), 'black', marker="o") s1.annotate( f"Δ = {bsm.delta(slope, K, r, q, σ, T, category='call'):.3f}", xy=[slope - 20, bsm.bs_call_price(slope, K, r, q, σ, T) + 5]) s1.annotate( f"Γ = {bsm.gamma(slope, K, r, q, σ, T, category='call'):.3f}", xy=[slope - 20, bsm.bs_call_price(slope, K, r, q, σ, T) + 0]) if self.check_Taylor.isChecked(): if self.check_Taylor1.isChecked(): s1.plot(shrink(x, fac), shrink(taylor1_call, fac), 'orange', lw=1.0, label='Taylor 1st order') if self.check_Taylor2.isChecked(): s1.plot(shrink(x, fac), shrink(taylor2_call, fac), 'grey', lw=1.0, label='Taylor 2nd order') legend = s1.legend(loc='upper left', shadow=True, fontsize='medium') s2.clear() s2.set_title('Put', fontsize=14, color='brown') s2.set_xlabel('$S_0$') s2.grid(True) s2.plot(x, y_put, 'r', lw=1.5, label='value') s2.axvline(x=slope, color="g", alpha=0.5, linewidth=1) s2.plot(x, z_put, 'b-.', lw=1.5, label='payoff') s2.plot(slope, bsm.bs_put_price(slope, K, r, q, σ, T), 'black', marker="o") s2.annotate( f"Δ = {bsm.delta(slope, K, r, q, σ, T, category='put'):.3f}", xy=[slope + 5, bsm.bs_put_price(slope, K, r, q, σ, T) + 5]) s2.annotate( f"Γ = {bsm.gamma(slope, K, r, q, σ, T, category='put'):.3f}", xy=[slope + 5, bsm.bs_put_price(slope, K, r, q, σ, T) + 0]) if self.check_Taylor.isChecked(): if self.check_Taylor1.isChecked(): s2.plot(shrink(x, fac), shrink(taylor1_put, fac), 'orange', lw=1.0, label='Taylor 1st order') if self.check_Taylor2.isChecked(): s2.plot(shrink(x, fac), shrink(taylor2_put, fac), 'grey', lw=1.0, label='Taylor 2nd order') legend = s2.legend(loc='upper right', shadow=True, fontsize='medium') s3.clear() s3.get_shared_y_axes().join(s3, s4) s3.set_title(self.titles[graphtype + 'C'], fontsize=14, color='brown') s3.grid(True) s3.plot(x, greek_call, 'brown', lw=1.5, label='') s3.axvline(x=slope, color="g", alpha=1.0, linewidth=1) s3.axhline(y=0, color="black", alpha=1, linewidth=1) s4.clear() s4.set_title(self.titles[graphtype + 'P'], fontsize=14, color='brown') s4.grid(True) s4.plot(x, greek_put, 'brown', lw=1.5, label='') s4.axvline(x=slope, color="g", alpha=1.0, linewidth=1) s4.axhline(y=0, color="black", alpha=1, linewidth=1) mpl.fig.set_visible(True) mpl.draw() ## time-to-maturity Theta graph s5.clear() if self.check_Theta_T2M.isChecked() and self.greek == 'Θ': self.oMplCanvas_Theta_T2M.show() #print("Cool!") S0 = slope s5.set_title("Variation of Θ with time to maturity", fontsize=10, color='brown') s5.grid(True) s5.get_shared_y_axes().remove(s3) t = np.linspace(0, 0.99, 100) # time to maturity K_vec = [S0 - 10, S0, S0 + 10] Θ_vec = [None, None, None] Θ_vec[0] = bsm.theta(S0, K_vec[0], r, q, σ, T - t, category='call') Θ_vec[1] = bsm.theta(S0, K_vec[1], r, q, σ, T - t, category='call') Θ_vec[2] = bsm.theta(S0, K_vec[2], r, q, σ, T - t, category='call') s5.plot(t, Θ_vec[0], 'brown', lw=0.7, label=f'K={K_vec[0]}') s5.plot(t, Θ_vec[1], 'green', lw=0.7, label=f'K={K_vec[1]}') s5.plot(t, Θ_vec[2], 'grey', lw=0.7, label=f'K={K_vec[2]}') legend = s5.legend(loc='lower left', shadow=True, fontsize='small') mpl2.fig.set_visible(True) mpl2.draw()
def showGraph(self): mpl = self.oMplCanvas.canvas [s1, s2, s3, s4, s5, s6] = mpl.axes #print(f"showGraph::very:beginning:PL={self.PL}") S0 = self.S0 K_C1 = self.K_C1 K_C2 = self.K_C2 K_C3 = self.K_C3 K_P1 = self.K_P1 K_P2 = self.K_P2 K_P3 = self.K_P3 r = self.r q = self.q σ = self.σ T_C1 = self.T_C1 T_C2 = self.T_C2 T_C3 = self.T_C3 T_P1 = self.T_P1 T_P2 = self.T_P2 T_P3 = self.T_P3 k = self.simCurrentStep # this is used a lot below # Get the x, y units of Call and Put options, respectively # CALL α1 = self.spin_C1.value() α2 = self.spin_C2.value() α3 = self.spin_C3.value() # PUT β1 = self.spin_P1.value() β2 = self.spin_P2.value() β3 = self.spin_P3.value() #print(f"α={α}, β={β}") if self.radio_Call.isChecked(): (β1, β2, β3) = (0, 0, 0) elif self.radio_Put.isChecked(): (α1, α2, α3) = (0, 0, 0) # Set minimum and maximum x-axis values for s1 (main plot) # get the y-coordinates of self.circleCoords (options values) for t0, t1, ..., t5 circle_y_list = [ self.circleCoords[i][0] for i in range(len(self.circleCoords)) ] s1_x_max = max(140, max(circle_y_list) + 10) s1_x_min = min(60, min(circle_y_list) - 10) # x-axis points for s1 (main) plot x = np.linspace(s1_x_min, s1_x_max, 51) # y-axis points for s3 (1-unit call) plot y_call1 = bsm.bs_call_price(x, K_C1, r, q, σ, T_C1 * (1 - k / (self.simSteps))) y_call2 = bsm.bs_call_price(x, K_C2, r, q, σ, T_C2 * (1 - k / (self.simSteps))) y_call3 = bsm.bs_call_price(x, K_C3, r, q, σ, T_C3 * (1 - k / (self.simSteps))) # y-axis points for s2 (1-unit put) plot y_put1 = bsm.bs_put_price(x, K_P1, r, q, σ, T_P1 * (1 - k / (self.simSteps))) y_put2 = bsm.bs_put_price(x, K_P2, r, q, σ, T_P2 * (1 - k / (self.simSteps))) y_put3 = bsm.bs_put_price(x, K_P3, r, q, σ, T_P3 * (1 - k / (self.simSteps))) # y-axis points for s1 (combined options) y = α1 * y_call1 + α2 * y_call2 + α3 * y_call3 + \ β1 * y_put1 + β2 * y_put2 + β3 * y_put3 # payoff for 1-unit call z_call1 = bsm.payoff_call(x, K_C1) z_call2 = bsm.payoff_call(x, K_C2) z_call3 = bsm.payoff_call(x, K_C3) # payoff for 1-unit put z_put1 = bsm.payoff_put(x, K_P1) z_put2 = bsm.payoff_put(x, K_P2) z_put3 = bsm.payoff_put(x, K_P3) # payoff for combined z = α1 * z_call1 + α2 * z_call2 + α3 * z_call3 + \ β1 * z_put1 + β2 * z_put2 + β3 * z_put3 ############################################### # s2: 1-unit Put/Call options ############################################### s2.clear() if self.radio_Call.isChecked(): if α1: # non-zero title = f'$C_{1}$' s2.plot(x, y_call1, 'r', lw=0.6, label='value') s2.plot(x, z_call1, 'b-.', lw=1, label='payoff') s2.set_title(title, fontsize=12, color='brown') elif self.radio_Put.isChecked(): if β1: # non-zero title = f'$P_{1}$' s2.plot(x, y_put1, 'r', lw=0.6, label='value') s2.plot(x, z_put1, 'b-.', lw=1, label='payoff') s2.set_title(title, fontsize=12, color='brown') s2.grid(True) # plot circle on s2 call_put_circle_x = self.circleCoords[k][0] if self.radio_Call.isChecked(): call_put_circle_y = self.OUP[k]['C1'] elif self.radio_Put.isChecked(): call_put_circle_y = self.OUP[k]['P1'] s2.plot(call_put_circle_x, call_put_circle_y, 'black', marker="o") #self.text_PutValue1Unit.setPlainText(f"{put_circle_y:.2f}") ############################################### # s3: 1-unit Put/Call options ############################################### s3.clear() if self.radio_Call.isChecked(): if α2: # non-zero title = f'$C_{2}$' s3.plot(x, y_call2, 'r', lw=0.6, label='value') s3.plot(x, z_call2, 'b-.', lw=1, label='payoff') s3.set_title(title, fontsize=12, color='brown') elif self.radio_Put.isChecked(): if β2: # non-zero title = f'$P_{2}$' s3.plot(x, y_put2, 'r', lw=0.6, label='value') s3.plot(x, z_put2, 'b-.', lw=1, label='payoff') s3.set_title(title, fontsize=12, color='brown') s3.grid(True) # plot circle on s3 call_put_circle_x = self.circleCoords[k][0] if self.radio_Call.isChecked(): call_put_circle_y = self.OUP[k]['C2'] elif self.radio_Put.isChecked(): call_put_circle_y = self.OUP[k]['P2'] s3.plot(call_put_circle_x, call_put_circle_y, 'black', marker="o") #self.text_CallValue1Unit.setPlainText(f"{call_circle_y:.2f}") ############################################### # s6: 1-unit Put/Call options ############################################### s6.clear() s6.grid(True) if self.radio_Call.isChecked(): if α3: # non-zero title = f'$C_{3}$' s6.plot(x, y_call3, 'r', lw=0.6, label='value') s6.plot(x, z_call3, 'b-.', lw=1, label='payoff') s6.set_title(title, fontsize=12, color='brown') s6.grid(True) elif self.radio_Put.isChecked(): if β3: # non-zero title = f'$P_{3}$' s6.plot(x, y_put3, 'r', lw=0.6, label='value') s6.plot(x, z_put3, 'b-.', lw=1, label='payoff') s6.set_title(title, fontsize=12, color='brown') s6.grid(True) # plot circle on s2 call_put_circle_x = self.circleCoords[k][0] if α3: if self.radio_Call.isChecked(): call_put_circle_y = self.OUP[k]['C3'] elif self.radio_Put.isChecked(): call_put_circle_y = self.OUP[k]['P3'] s6.plot(call_put_circle_x, call_put_circle_y, 'black', marker="o") if β3: # both non-zero if self.radio_Call.isChecked(): call_put_circle_y = self.OUP[k]['C3'] elif self.radio_Put.isChecked(): call_put_circle_y = self.OUP[k]['P3'] s6.plot(call_put_circle_x, call_put_circle_y, 'black', marker="o") ############################################### # Plot all (discretized continuous) simulated share prices ############################################### s4.clear() s4.set_title(f'Simulated share prices', fontsize=12, color='brown') s4.yaxis.set_tick_params(labelright=False, labelleft=True) s4.grid(True) #print(f"size of X = {len(self.X)}") # set the upper limit of index for which the simulated share prices will be shown on s4 upperLimit = int((len(self.X) - 1) * k / self.simSteps) #print(f"upperLimit = {upperLimit}") s4.plot(self.X[:upperLimit], self.simY[:upperLimit], 'g', lw=0.75, label='$S_T$') s4.set_xlim(right=self.T_C1, left=0.0) s4.set_ylim(top=self.simY.max() + 10, bottom=self.simY.min() - 10) # plot simulated prices at discrete time points (t0, t1, ..., t5) s4.plot(self.Xdiscrete[:k + 1], self.Ydiscrete[:k + 1], 'black', lw=1.25, label='price') #legend = s4.legend(loc='upper left', shadow=False, fontsize='medium') #print(f"Ydiscrete = {self.Ydiscrete}") ############################################### # Plot main graph (s1: top row, middle) ############################################### s1.clear() #if int(α) - float(α) == 0.0: # α is an integer main_title = '' # was f'${α1}C + {β1}P$' weights = [α1, α2, α3, β1, β2, β3] for j, w in enumerate(weights[:3]): # α if w > 0: main_title += f"$+{w} C_{j+1}$ " if w < 0: main_title += f"${w} C_{j+1}$ " for j, w in enumerate(weights[3:]): # β if w > 0: main_title += f"$+{w} P_{j+1}$ " if w < 0: main_title += f"${w} P_{j+1}$ " s1.set_title(main_title, fontsize=12, color='brown') #s1.set_aspect(aspect=1.0) s1.yaxis.set_tick_params(labelright=False, labelleft=True) s1.grid(True) s1.plot(x, z, 'b-.', lw=1.5) # payoff s1.set_xlim(right=s1_x_max, left=s1_x_min) #s1.set_ylim(top=20, bottom=-20) # plot a number of option value curves (from 0 to 5) (y_bottom, y_top) = s1.get_ylim() y_inc = (y_top - y_bottom) * 0.15 s1.set_ylim(top=y_top + y_inc, bottom=y_bottom - y_inc) for i in range(0, k + 1): y_call1 = bsm.bs_call_price(x, K_C1, r, q, σ, T_C1 * (1 - i / (self.simSteps))) y_call2 = bsm.bs_call_price(x, K_C2, r, q, σ, T_C2 * (1 - i / (self.simSteps))) y_call3 = bsm.bs_call_price(x, K_C3, r, q, σ, T_C3 * (1 - i / (self.simSteps))) # y-axis points for s2 (1-unit put) plot y_put1 = bsm.bs_put_price(x, K_P1, r, q, σ, T_P1 * (1 - i / (self.simSteps))) y_put2 = bsm.bs_put_price(x, K_P2, r, q, σ, T_P2 * (1 - i / (self.simSteps))) y_put3 = bsm.bs_put_price(x, K_P3, r, q, σ, T_P3 * (1 - i / (self.simSteps))) # y-axis points for s1 (combined options) y = α1 * y_call1 + α2 * y_call2 + α3 * y_call3 + \ β1 * y_put1 + β2 * y_put2 + β3 * y_put3 #y_call = bsm.bs_call_price(x, K_C1, r, q, σ, T_C1*(1-(i)/(self.simSteps))) #y_put = bsm.bs_put_price(x, K_P1, r, q, σ, T_P1*(1-(i)/(self.simSteps))) #y = α1 * y_call + β1 * y_put # plot option value curve #s1.plot(x, y, 'red', alpha=0.6, lw=0.4+0.05*i, label=f'value = {put_circle_y + call_circle_y}') #s1.plot(x, y, 'red', alpha=0.6, lw=0.4+0.05*i) s1.plot(x, y, 'red', alpha=0.6, lw=0.4 + 0.05 * i) #s1.legend(loc='upper left', shadow=False, fontsize='medium') # Now plot the circles #self.recomputeCircle() for i, point in enumerate(self.circleCoords): if i == 0: s1.plot(point[0], point[1], 'black', marker="o") elif i > 0 and i <= k: # skip step 0, i.e. when there's only one curve #print(f"i={i}, {self.circleCoords}") p_x, p_y = self.circleCoords[ i - 1] # previous circle's coordinates c_x, c_y = self.circleCoords[i] # current circle's coordinates #print(f"p_x = {p_x:.2f}, p_y = {p_y:.2f}, c_x = {c_x:.2f}, c_y = {c_y:.2f}") s1.plot(point[0], point[1], 'black', marker="o") s1.arrow(p_x, p_y, c_x - p_x, c_y - p_y, color='purple', width=0.00025, head_width=0.25, length_includes_head=True) ########################################## # Plot P&L graph ########################################## s5.clear() s5.set_title(f'Profit/Loss', fontsize=12, color='brown') s5.yaxis.set_tick_params(labelright=False, labelleft=True) s5.grid(True) if self.radio_Call.isChecked(): # C1 value self.PL[k][0] = self.OUP[k]['C1'] # C2 vlaue self.PL[k][1] = self.OUP[k]['C2'] # C3 alue self.PL[k][2] = self.OUP[k]['C3'] # ΣC value self.PL[k][3] = α1 * self.OUP[k]['C1'] + α2 * self.OUP[k][ 'C2'] + α3 * self.OUP[k]['C3'] elif self.radio_Put.isChecked(): # P1 value self.PL[k][0] = self.OUP[k]['P1'] # P2 vlaue self.PL[k][1] = self.OUP[k]['P2'] # P3 alue self.PL[k][2] = self.OUP[k]['P3'] # ΣP value self.PL[k][3] = β1 * self.OUP[k]['P1'] + β2 * self.OUP[k][ 'P2'] + β3 * self.OUP[k]['P3'] # P/L #print(f"k={k}") self.PL[k][4] = self.PL[k][3] - self.PL[0][3] self.UpdatePL_TVOM() # copy from self.PL_TVOM to self.tablePL self.DisplayPL_Table() #item.setTextAlignment(Qt.AlignVCenter) # Select a row self.tablePL.setRangeSelected(QTableWidgetSelectionRange(k, 0, k, 4), True) for row in range(self.simSteps + 1): self.tablePL.setRowHeight(row, 20) # Finally, plot the P/L line # find min and max of option values all_options_values = [ self.circleCoords[i][1] for i in range(len(self.circleCoords)) ] s5_x_max = max(all_options_values) + 10 s5_x_min = min(all_options_values) - 10 xPL = self.Xdiscrete option_val_t0 = self.PL_TVOM[0][3] # option value at t0 yPL = [self.PL_TVOM[row][3] for row in range(k + 1)] #s5.set_ylim(top=s5_x_max, bottom=s5_x_min) s5.plot(xPL[:k + 1], yPL, 'r-.', lw=1.5, label='P&L') # plot horizontal line indicating the option value at t0 s5.axhline(y=option_val_t0, color="black", alpha=1, linewidth=1) # annotate plot with P/L values for row in range(0, k + 1): s5.annotate(f"{self.PL_TVOM[row][4]:+.2f}", xy=[ self.Xdiscrete[row] - 0.1, self.PL_TVOM[row][4] + option_val_t0 + 0.5 ]) for row in range(k + 1): s5.plot(self.Xdiscrete[row], self.PL_TVOM[row][4] + option_val_t0, marker='o', color='black') #self.tablePL.setStyleSheet("QTableView::item:selected { color:red; background:yellow; font-weight: bold; } " + "QTableView::vertical:header {font-size: 9}") # Display entire canvas! mpl.fig.set_visible(True) mpl.draw()
def showGraph(self): mpl = self.oMplCanvas.canvas [s1, s2, s3, s4, s5] = mpl.axes #print(f"showGraph::very:beginning:PL={self.PL}") S0 = self.S0 K_C1 = self.K_C1 K_P1 = self.K_P1 r = self.r q = self.q σ = self.σ T_C1 = self.T_C1 T_P1 = self.T_P1 k = self.simCurrentStep # this is used a lot below # Get the x, y units of Call and Put options, respectively # CALL α1 = self.spin_C1.value() # PUT β1 = self.spin_P1.value() #print(f"α={α}, β={β}") # SHARE Share = self.spin_Share.value() # Set minimum and maximum x-axis values for s1 (main plot) # get the y-coordinates of self.circleCoords (options values) for t0, t1, ..., t5 circle_y_list = [ self.circleCoords[i][0] for i in range(len(self.circleCoords)) ] s1_x_max = max(140, max(circle_y_list) + 10) s1_x_min = min(60, min(circle_y_list) - 10) # x-axis points for s1 (main) plot x = np.linspace(s1_x_min, s1_x_max, 51) self.x = x s = x # stock value per share # y-axis points for s3 (1-unit call) plot y_call1 = bsm.bs_call_price(x, K_C1, r, q, σ, T_C1 * (1 - k / (self.simSteps))) # y-axis points for s2 (1-unit put) plot y_put1 = bsm.bs_put_price(x, K_P1, r, q, σ, T_P1 * (1 - k / (self.simSteps))) # y-axis points for s1 (combined options) y = α1 * y_call1 + β1 * y_put1 + Share * s # payoff for 1-unit call z_call1 = bsm.payoff_call(x, K_C1) # payoff for 1-unit put z_put1 = bsm.payoff_put(x, K_P1) # payoff for combined z = α1 * z_call1 + β1 * z_put1 + Share * s profit_option = 0 if α1: # profit = payoff + call premium (short call) profit_option = α1 * z_call1 + (-α1) * bsm.bs_call_price( S0, K_C1, r, q, σ, T_C1) if β1: # profit = payoff - put premium (long put) profit_option = β1 * z_put1 + (-β1) * bsm.bs_put_price( S0, K_P1, r, q, σ, T_P1) profit_stock = Share * (x - S0) profit_combined = profit_stock + profit_option # s2: 1-unit Put/Call options s2.clear() if α1: # non-zero #title = f'$C_{1}$' title = f'{α1}$C$' s2.plot(x, α1 * y_call1, 'r', lw=0.6, label='value') s2.plot(x, α1 * z_call1, 'b-.', lw=1, label='payoff') s2.set_title(title, fontsize=12, color='brown') # plot circle on s2 put_circle_x = self.circleCoords[k][0] put_circle_y = α1 * bsm.bs_put_price( put_circle_x, K_C1, r, q, σ, T_C1 * (1 - k / (self.simSteps))) #s2.plot(put_circle_x, put_circle_y, 'black', marker="o") #self.text_PutValue1Unit.setPlainText(f"{put_circle_y:.2f}") s2.grid(True) # s3: 1-unit Put/Call options s3.clear() if β1: # non-zero title = f'{β1}$P_{1}$' s3.plot(x, β1 * y_put1, 'r', lw=0.6, label='value') s3.plot(x, β1 * z_put1, 'b-.', lw=1, label='payoff') s3.set_title(title, fontsize=12, color='brown') put_circle_x = self.circleCoords[k][0] put_circle_y = β1 * bsm.bs_put_price( put_circle_x, K_P1, r, q, σ, T_P1 * (1 - k / (self.simSteps))) s3.plot(put_circle_x, put_circle_y, 'black', marker="o") s3.grid(True) # plot circle on s3 call_circle_x = self.circleCoords[k][0] call_circle_y = bsm.bs_call_price(call_circle_x, K_C1, r, q, σ, T_C1 * (1 - k / (self.simSteps))) #s3.plot(call_circle_x, call_circle_y, 'black', marker="o") #self.text_CallValue1Unit.setPlainText(f"{call_circle_y:.2f}") # Plot all (discretized continuous) simulated share prices s4.clear() s4.set_title(f'Simulated share prices', fontsize=12, color='brown') s4.yaxis.set_tick_params(labelright=False, labelleft=True) s4.grid(True) #print(f"size of X = {len(self.X)}") # set the upper limit of index for which the simulated share prices will be shown on s4 upperLimit = int((len(self.X) - 1) * k / self.simSteps) #print(f"upperLimit = {upperLimit}") s4.plot(self.X[:upperLimit], self.simY[:upperLimit], 'g', lw=0.75, label='$S_T$') s4.set_xlim(right=self.T_C1, left=0.0) s4.set_ylim(top=self.simY.max() + 10, bottom=self.simY.min() - 10) # plot simulated prices at discrete time points (t0, t1, ..., t5) s4.plot(self.Xdiscrete[:k + 1], self.Ydiscrete[:k + 1], 'black', lw=1.25, label='price') #legend = s4.legend(loc='upper left', shadow=False, fontsize='medium') #print(f"Ydiscrete = {self.Ydiscrete}") # Plot main graph (s1: top row, middle) s1.clear() #if int(α) - float(α) == 0.0: # α is an integer main_title = '' # was f'${α1}C + {β1}P$' if Share > 0: main_title = f"${Share}S$" elif Share < 0: main_title = f"$-{Share}S$" weights = [α1, β1] for j, w in enumerate(weights[:1]): # α if w > 0: #main_title += f"$+{w} C_{j+1}$ " main_title += f"$+{w} C$ " if w < 0: #main_title += f"${w} C_{j+1}$ " main_title += f"${w} C$ " for j, w in enumerate(weights[1:]): # β if w > 0: #main_title += f"$+{w} P_{j+1}$ " main_title += f"$+{w} P$ " if w < 0: #main_title += f"${w} P_{j+1}$ " main_title += f"${w} P$ " s1.set_title(main_title, fontsize=12, color='brown') s1.set_aspect(aspect='equal') s1.yaxis.set_tick_params(labelright=False, labelleft=True) s1.grid(True) # Do we want to display Profit or Payoff? payoff_selected = True if self.radio_Payoff.isChecked() else False profit_selected = True if self.radio_Profit.isChecked() else False if payoff_selected: # payoff if α1: s1.plot(x, z, 'r', lw=1.5, label='Covered Call') if β1: s1.plot(x, z, 'r', lw=1.5, label='Protective Put') s1.set_xlim(right=s1_x_max, left=s1_x_min) # long stock line if α1: #s1.plot(x, Share * (x - self.S0), 'g--', lw=1.5, label='Long Stock') s1.plot(x, Share * (x - 0), 'g--', lw=1.5, label='Long Stock') if β1: #s1.plot(x, Share * (x - self.S0), 'g--', lw=1.5, label='Long Stock') s1.plot(x, Share * (x - 0), 'g--', lw=1.5, label='Long Stock') # call/put if α1: #s1.plot(x, α1 * (z_call1), 'b-.', lw=1, label='Short Call') s1.plot(x, α1 * z_call1 + β1 * z_put1 + S0, 'b-.', lw=1, label='Short Call') if β1: #s1.plot(x, β1 * (z_put1), 'b-.', lw=1, label='Long Put') s1.plot(x, α1 * z_call1 + β1 * z_put1 + S0, 'b-.', lw=1, label='Long Put') s1.legend(loc='upper left', shadow=True, fontsize='large') if profit_selected: # payoff if α1: s1.plot(x, profit_combined, 'r', lw=1.5, label='Covered Call') if β1: s1.plot(x, profit_combined, 'r', lw=1.5, label='Protective Put') s1.set_xlim(right=s1_x_max, left=s1_x_min) # long stock line if α1: s1.plot(x, profit_stock, 'g--', lw=1.5, label='Long Stock') if β1: s1.plot(x, profit_stock, 'g--', lw=1.5, label='Long Stock') # call/put if α1: s1.plot(x, profit_option, 'b-.', lw=1, label='Short Call') if β1: s1.plot(x, profit_option, 'b-.', lw=1, label='Long Put') s1.legend(loc='upper left', shadow=True, fontsize='large') # option premium (1 unit) if profit_selected: premium_call = bsm.bs_call_price(S0, K_C1, r, q, σ, T_C1) premium_put = bsm.bs_put_price(S0, K_P1, r, q, σ, T_P1) if payoff_selected: premium_call = 0 premium_put = 0 premium_offset = 0 if payoff_selected else (-α1) * premium_call + ( -β1) * premium_put # plot a number of option value curves (from 0 to 5) for i in range(0, k + 1): y_call1 = 0.0 y_put1 = 0.0 if α1: y_call1 = bsm.bs_call_price(x, K_C1, r, q, σ, T_C1 * (1 - i / (self.simSteps))) # y-axis points for s2 (1-unit put) plot if β1: y_put1 = bsm.bs_put_price(x, K_P1, r, q, σ, T_P1 * (1 - i / (self.simSteps))) # y-axis points for s1 (combined options) if payoff_selected: y = α1 * y_call1 + β1 * y_put1 + Share * (x - 0) elif profit_selected: y = α1 * y_call1 + β1 * y_put1 + Share * (x - self.S0) #y = α1 * y_call + β1 * y_put # plot option value curve if α1: s1.plot(x, y + (-α1) * premium_call, \ 'red', alpha=0.6, lw=0.4+0.05*i, label=f'value = {put_circle_y + call_circle_y}') if β1: s1.plot(x, y + (-β1) * premium_put, \ 'red', alpha=0.6, lw=0.4+0.05*i, label=f'value = {put_circle_y + call_circle_y}') #s1.legend(loc='upper left', shadow=False, fontsize='medium') # Now plot the circles #self.recomputeCircle() for i, point in enumerate(self.circleCoords): if i == 0: if payoff_selected: s1.plot(point[0], point[1] + premium_offset + S0, 'black', marker="o") elif profit_selected: s1.plot(point[0], point[1] + premium_offset, 'black', marker="o") elif i > 0 and i <= k: # skip step 0, i.e. when there's only one curve #print(f"i={i}, {self.circleCoords}") p_x, p_y = self.circleCoords[ i - 1] # previous circle's coordinates c_x, c_y = self.circleCoords[i] # current circle's coordinates #print(f"p_x = {p_x:.2f}, p_y = {p_y:.2f}, c_x = {c_x:.2f}, c_y = {c_y:.2f}") if payoff_selected: s1.plot(point[0], point[1] + premium_offset + S0, 'black', marker="o") s1.arrow(p_x, p_y + premium_offset + S0, c_x - p_x, c_y - p_y, \ color='purple', width=0.00025, head_width=1.0, length_includes_head=True) elif profit_selected: s1.plot(point[0], point[1] + premium_offset, 'black', marker="o") s1.arrow(p_x, p_y + premium_offset, c_x - p_x, c_y - p_y, \ color='purple', width=0.00025, head_width=1.0, length_includes_head=True) # Plot P&L graph s5.clear() s5.set_title(f'Profit/Loss', fontsize=12, color='brown') s5.yaxis.set_tick_params(labelright=False, labelleft=True) s5.grid(True) # default horizontal header labels hori_labels = ['1P\nProfit', '1C\nProfit', 'ΣC+ΣP\nProfit', 'P/L'] number_basis = 'Profit' if profit_selected else 'Value' # 1C vlaue stepSize = int((1 / self.Δt) / self.simSteps) if α1: #self.PL[k][0] = put_circle_y self.PL[k][0] = (-α1) * bsm.bs_call_price( self.simY[k * stepSize][0], K_C1, r, q, σ, T_C1 * (1 - k / (self.simSteps))) hori_labels[0] = f"{α1}C\n{number_basis}" # 1P value if β1: self.PL[k][0] = call_circle_y self.PL[k][0] = (-β1) * bsm.bs_put_price( self.simY[k * stepSize][0], K_P1, r, q, σ, T_P1 * (1 - k / (self.simSteps))) hori_labels[0] = f"{β1}P\n{number_basis}" # zS value self.PL[k][1] = self.simY[ k * stepSize][0] - S0 if profit_selected else self.simY[k * stepSize][0] hori_labels[1] = f"{Share}S\n{number_basis}" # xC|yP + zS self.PL[k][2] = ( -α1) * self.PL[k][0] + β1 * self.PL[k][0] + Share * self.PL[k][1] #hori_labels[2] = f"{hori_labels[0]} + {hori_labels[1]}" hori_labels[2] = f"O+S\n{number_basis}" hori_labels[3] = "P/L" if profit_selected else "Value" # P/L #print(f"k={k}") self.PL[k][3] = self.PL[k][2] - self.PL[0][2] self.UpdatePL_TVOM() # copy from self.PL_TVOM to self.tablePL self.DisplayPL_Table(hori_labels) #item.setTextAlignment(Qt.AlignVCenter) # Select a row self.tablePL.setRangeSelected(QTableWidgetSelectionRange(k, 0, k, 3), True) for row in range(self.simSteps + 1): self.tablePL.setRowHeight(row, 20) # Finally, plot the P/L line # find min and max of option values all_options_values = [ self.circleCoords[i][1] for i in range(len(self.circleCoords)) ] #s5_x_max = max(all_options_values)+10 #s5_x_min = min(all_options_values)-10 xPL = self.Xdiscrete option_val_t0 = self.PL_TVOM[0][2] # option value at t0 yPL = [self.PL_TVOM[row][2] for row in range(k + 1)] #s5.set_ylim(top=s5_x_max, bottom=s5_x_min) s5.plot(xPL[:k + 1], yPL, 'r-.', lw=1.5, label='P&L') # plot horizontal line indicating the option value at t0 s5.axhline(y=option_val_t0, color="black", alpha=1, linewidth=1) # annotate plot with P/L values for row in range(0, k + 1): s5.annotate(f"{self.PL_TVOM[row][3]:+.2f}", xy=[ self.Xdiscrete[row] - 0.1, self.PL_TVOM[row][3] + option_val_t0 + 2 ]) for row in range(k + 1): s5.plot(self.Xdiscrete[row], self.PL_TVOM[row][3] + option_val_t0, marker='o', color='black') #self.tablePL.setStyleSheet("QTableView::item:selected { color:red; background:yellow; font-weight: bold; } " + "QTableView::vertical:header {font-size: 9}") # Display entire canvas! mpl.fig.set_visible(True) mpl.draw()
initialCon.append(-0.01 / 300.0 * x) # Ensuring boundary conditions #initialCon[0] = 0 #initialCon[-1] = 0 yPrev = initialCon yCurrent = initialCon sample = [] for n in range(0,10): for i in range(0,len(x)): if i !=0 and i != 649: yNew = ((2 - 2*r**2 - 6 * eps * r**2 * N**2)*yCurrent[i] - yPrev[i] + r**2*(1 + 4*eps*N**2)*(yCurrent[i+1] + yCurrent[i-1]) - eps*r**2*N**2 *(yCurrent[i+2] + yCurrent[i-2])) yPrev = copy(yCurrent) yCurrent = copy(yNew) plt.scatter(yNew) plt.draw() plt.pause() plt.clf()
def showGraph(self): #self.oMplCanvas.close() mpl = self.oMplCanvas.canvas mainplot = mpl.axes[0][0] mainplot.clear() mainplot.autoscale(enable=True) #mainplot.set_adjustable(adjustable='box') #mainplot.set_xlim(auto=True) mainplot.set_ylim(auto=True) P = self.randomwalk_params['P'] T = self.randomwalk_params['T'] #TimeStepShown = min(T, ?) if self.radioGRW.isChecked(): self.S = self.Y self.plot_title = f"Geometric Random Walk" elif self.radioRW.isChecked(): self.S = self.X self.plot_title = f"Additive Random Walk" mainplot.plot(self.S[:T + 1, :P]) mainplot.grid(True) mainplot.set_xlabel('time step', fontsize=8, color='brown') mainplot.set_ylabel('price', fontsize=8, color='brown') mainplot.tick_params(axis='both', which='major', labelsize=6) divider = make_axes_locatable(mainplot) ##### #axHist = divider.append_axes("right", 1.25, pad=0.1, sharey=mainplot) axHist = mpl.axes[0][1] axHist.clear() axHist.set_xlim(auto=True) axHist.set_ylim(auto=True) # Turn off tick labels #axHist.set_yticklabels([]) #axHist.set_xticklabels([]) #axHist.hist(S[-1, :N], bins=51, density=True, orientation='horizontal', rwidth=2) N = self.randomwalk_params['N'] axHist.hist(self.S[-1, :N], density=True, bins=101, orientation='horizontal', rwidth=2) axHist.yaxis.set_ticks_position("right") axHist.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) axHist.grid(True) axHist.tick_params(axis='both', which='major', labelsize=6) p = self.oSlider_prob.value() / 100 SimSize = int(self.comboBox_SimSize.currentText()) mainplot.set_title(self.plot_title + f" $p$ = {p:.2f}", fontsize=12, color='brown') #mainplot.set_title(r'$z = \sqrt{x^2+y^2}$', fontsize=14, color='r') axHist.set_xlabel('prob', fontsize=8, color='brown') ##### t1 = self.slider_t1.value() t2 = self.slider_t2.value() mainplot.axvline(x=t1) mainplot.axvline(x=t2, color="blue") ax3 = mpl.axes[1][0] ax3.clear() ax3.set_xlabel('price', fontsize=8, color='brown') ax3.tick_params(axis='both', which='major', labelsize=6) ax3.yaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) MaxStep = self.S.shape[0] - 1 ax3.hist(self.S[min(t1 + 1, MaxStep), :], density=True, bins=101, orientation='vertical', rwidth=2, color='red', alpha=0.5) ax3.hist(self.S[min(t2 + 1, MaxStep), :], density=True, bins=101, orientation='vertical', rwidth=2, color='blue', alpha=0.5) ##### ## populate tableWidget with descriptive statistics table = self.tableWidget table.setColumnCount(1) #Set three columns table.setRowCount(6) table.setHorizontalHeaderLabels(["Value"]) descr_stats_labels = [ 'E(X)', 'Var(X)', 'Skew(X)', 'Kurt(X)', 'E[(X - K)+]', 'E[(K - X)+]' ] table.setVerticalHeaderLabels(descr_stats_labels) #for i in range(0, table.rowCount()): # table.setItem(i, 0, QTableWidgetItem(descr_stats_labels[i])) samp_mean = self.S[-1, :].mean() table.setItem(0, 0, QTableWidgetItem(f"{samp_mean:.2f}")) samp_var = self.S[-1, :].var() table.setItem(1, 0, QTableWidgetItem(f"{samp_var:.2f}")) samp_skew = skew(self.S[-1, :]) table.setItem(2, 0, QTableWidgetItem(f"{samp_skew:.2f}")) samp_kurt = kurtosis(self.S[-1, :]) table.setItem(3, 0, QTableWidgetItem(f"{samp_kurt:.2f}")) #table.setVerticalHeaderLabels(None) #table.set_visible(False) ## Compute E[(X_n - K)^+] T = self.randomwalk_params['T'] K = self.randomwalk_params['K'] N = self.randomwalk_params['N'] X = self.S[T, :] - K mean1 = X[X > 0].sum() / N X = self.S[T, :] mean1a = (np.maximum(X, K) - K).mean() ## (a - b)+ = max(a, b) - b ## Compute E[(K - X_n)^+] X = K - self.S[T, :] mean2 = X[X > 0].sum() / N X = self.S[T, :] mean2a = (np.maximum(K, X) - X).mean() del (X) table.setItem(4, 0, QTableWidgetItem(f"{mean1:.2f}")) table.setItem(5, 0, QTableWidgetItem(f"{mean2:.2f}")) table.resizeColumnsToContents() ##### self.OutputStats['T'] = [ samp_mean, samp_var, samp_skew, samp_kurt, mean1a, mean2a ] ##### ## deal with descriptive statistics of main plot mpltext = self.oMplCanvas2.canvas FigureCanvas.updateGeometry(mpltext) simulated_statistics = [ 'STATISTICS', ' ', '$Simulated$:', r'$\mathrm{E}(X_n) = ' + f'{samp_mean:.2f}$', r'$\mathrm{Var}(X_n) = ' + f'{samp_var:.2f}$', r'$\mathrm{Skew}(X_n) = ' + f'{samp_skew:.2f}$', r'$\mathrm{Kurt}(X_n) = ' + f'{samp_kurt:.2f}$', r'$\mathrm{E}[(X_n - K)^+] = ' + f'{mean1a:.2f}$', r'$\mathrm{E}[(K - X_n)^+] = ' + f'{mean2a:.2f}$', ] #simulated_statistics.extend([r'line 8', r'line 9', r'line 10', r'line 11', r'line 12', r'line 13']) ### Get theoretical values y0 = self.randomwalk_params['S0'] n = self.randomwalk_params['T'] u = self.randomwalk_params['u'] / 100.0 p = self.randomwalk_params['p'] / 100.0 print(f"y0={y0}, n={n}, u={u}, p={p}") theo_mean = (y0 / u**n) * A(2, u, n, p)**n theo_var = (y0 / u**n)**2 * (A(4, u, n, p)**n - A(2, u, n, p)**(2 * n)) theo_skew = ( (y0 / u**n)**3 * (A(6, u, n, p)**n - 3 * A(4, u, n, p)**n * A(2, u, n, p)**n + 2 * A(2, u, n, p)**(3 * n))) / theo_var**(3 / 2) theo_kurt = (y0 / u**n)**4 * ( A(8, u, n, p)**n - 4 * A(6, u, n, p)**n * A(2, u, n, p)**n + 6 * A(4, u, n, p)**n * A(2, u, n, p)**(2 * n) - 3 * A(2, u, n, p)**(4 * n)) / theo_var**2 theo_mean1a = 0 theo_mean2a = 0 analytical_statistics = [ ' ', '$Analytical$:', r'$\mathrm{E}(X_n) = ' + f'{theo_mean:.2f}$', r'$\mathrm{Var}(X_n) = ' + f'{theo_var:.2f}$', r'$\mathrm{Skew}(X_n) = ' + f'{theo_skew:.2f}$', r'$\mathrm{Kurt}(X_n) = ' + f'{theo_kurt:.2f}$', r'$\mathrm{E}[(X_n - K)^+] = ' + f'{theo_mean1a:.2f}$', r'$\mathrm{E}[(K - X_n)^+] = ' + f'{theo_mean2a:.2f}$', ] #statistics = list(simulated_statistics.append([r'-----'])) statistics = list(simulated_statistics) statistics.extend(analytical_statistics) #print('stats: ', statistics) #mpltext.fig = plt.figure() plt.style.use('seaborn-white') ax = mpltext.axes[0][0] ax.clear() #ax.plot([0, 0], 'r') #ax.set_title('Test') ax.axis([0, 3, -len(statistics), 0]) ax.set_yticks(-np.arange(len(statistics))) for i, s in enumerate(statistics): ax.text(0.1, -(i + 1) * 1.5, s, fontsize=14) plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=()) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') mpltext.fig.set_visible(True) mpltext.draw() #mpl2.close() #mpl2.fig.show(False) ##### mpl.fig.set_visible(True) mpl.draw()
def showGraph(self): #self.oMplCanvas.close() mpl = self.oMplCanvas.canvas mainplot = mpl.axes[0][0] mainplot.clear() #mainplot.autoscale(enable=True) #mainplot.autoscale(enable=False) #mainplot.set_adjustable(adjustable='box') #mainplot.set_xlim(auto=True) #mainplot.set_ylim(auto=True) P = self.randomwalk_params['P'] T = self.randomwalk_params['T'] Δt = self.randomwalk_params['Δt'] xvals = np.linspace(0.0, 1.0, int(1 / Δt) + 1) #TimeStepShown = min(T, ?) if self.radioGRW.isChecked(): self.S = self.Y self.plot_title = "Geometric Brownian Motion" elif self.radioRW.isChecked(): self.S = self.X self.plot_title = "Brownian Motion" #mainplot.plot(self.S[:T+1, :P]) mainplot.plot(xvals, self.S[:, :P], linewidth=0.5) mainplot.grid(True) mainplot.set_xlabel('time step', fontsize=8, color='brown') mainplot.set_ylabel('price', fontsize=8, color='brown') mainplot.tick_params(axis='both', which='major', labelsize=6) #mainplot.draw() #divider = make_axes_locatable(mainplot) ##### #axHist = divider.append_axes("right", 1.25, pad=0.1, sharey=mainplot) axHist = mpl.axes[0][1] axHist.clear() axHist.set_xlim(auto=True) axHist.set_ylim(auto=True) # Turn off tick labels #axHist.set_yticklabels([]) #axHist.set_xticklabels([]) #axHist.hist(S[-1, :N], bins=51, density=True, orientation='horizontal', rwidth=2) N = self.randomwalk_params['N'] axHist.hist(self.S[-1, :N], density=True, bins=101, orientation='horizontal', alpha=0.40, color='green') axHist.yaxis.set_ticks_position("right") axHist.xaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) axHist.grid(True) axHist.tick_params(axis='both', which='major', labelsize=6) #μ = self.oSlider_mu.value()/100 SimSize = int(self.comboBox_SimSize.currentText()) #mainplot.set_title(self.plot_title + f" $p$ = {p:.2f}", fontsize=12, color='brown') mainplot.set_title(self.plot_title, fontsize=12, color='brown') #mainplot.set_title(r'$z = \sqrt{x^2+y^2}$', fontsize=14, color='r') axHist.set_xlabel('probability', fontsize=8, color='brown') ##### # Now take care of sliders t1 and t2 self.reset_t1t2() #self.slider_t1.setEnabled(False) #self.slider_t1.setValue(0) #self.slider_t1.setEnabled(True) t1 = self.slider_t1.value() t2 = self.slider_t2.value() mainplot.axvline(x=t1 / self.t1t2_max, color="red", alpha=0.5, linewidth=1) mainplot.axvline(x=t2 / self.t1t2_max, color="blue", alpha=0.5, linewidth=1) ax3 = mpl.axes[1][0] ax3.clear() ax3.set_xlabel('price', fontsize=8, color='brown') ax3.tick_params(axis='both', which='major', labelsize=6) ax3.grid(True) ax3.yaxis.set_major_formatter(FuncFormatter('{0:.1%}'.format)) MaxStep = self.S.shape[0] - 1 ax3.hist(self.S[min(t1 + 0, MaxStep), :], density=True, bins=101, orientation='vertical', rwidth=2, color='red', alpha=0.5) ax3.hist(self.S[min(t2 + 0, MaxStep), :], density=True, bins=101, orientation='vertical', rwidth=2, color='blue', alpha=0.5) ##### ## populate tableWidget with descriptive statistics table = self.tableWidget table.setColumnCount(1) #Set three columns table.setRowCount(6) table.setHorizontalHeaderLabels(["Value"]) descr_stats_labels = [ 'E(X)', 'Var(X)', 'Skew(X)', 'Kurt(X)', 'E[(X - K)+]', 'E[(K - X)+]' ] table.setVerticalHeaderLabels(descr_stats_labels) #for i in range(0, table.rowCount()): # table.setItem(i, 0, QTableWidgetItem(descr_stats_labels[i])) samp_mean = self.S[-1, :].mean() table.setItem(0, 0, QTableWidgetItem(f"{samp_mean:.2f}")) samp_var = self.S[-1, :].var() table.setItem(1, 0, QTableWidgetItem(f"{samp_var:.2f}")) samp_skew = skew(self.S[-1, :]) table.setItem(2, 0, QTableWidgetItem(f"{samp_skew:.2f}")) samp_kurt = kurtosis(self.S[-1, :], fisher=False) # 3.0 is subtracted if fisher=True table.setItem(3, 0, QTableWidgetItem(f"{samp_kurt:.2f}")) #table.setVerticalHeaderLabels(None) #table.set_visible(False) ## Compute E[(X_n - K)^+] T = self.randomwalk_params['T'] K = self.randomwalk_params['K'] if self.radioRW.isChecked(): K = log(K) N = self.randomwalk_params['N'] X = self.S[-1, :] - K mean1 = X[X > 0].sum() / N X = self.S[-1, :] mean1a = (np.maximum(X, K) - K).mean() ## (a - b)+ = max(a, b) - b ## Compute E[(K - X_n)^+] X = K - self.S[-1, :] mean2 = X[X > 0].sum() / N X = self.S[-1, :] mean2a = (np.maximum(K, X) - X).mean() del (X) table.setItem(4, 0, QTableWidgetItem(f"{mean1:.2f}")) table.setItem(5, 0, QTableWidgetItem(f"{mean2:.2f}")) table.resizeColumnsToContents() ##### self.OutputStats['T'] = [ samp_mean, samp_var, samp_skew, samp_kurt, mean1a, mean2a ] ##### ## deal with descriptive statistics of main plot mpltext = self.oMplCanvas2.canvas FigureCanvas.updateGeometry(mpltext) simulated_statistics = [ 'STATISTICS', ' ', '$Simulated$:', r'$\mathrm{E}(X_T) = ' + f'{samp_mean:.2f}$', r'$\mathrm{Var}(X_T) = ' + f'{samp_var:.2f}$', r'$\mathrm{Skew}(X_T) = ' + f'{samp_skew:.2f}$', r'$\mathrm{Kurt}(X_T) = ' + f'{samp_kurt:.2f}$', r'$\mathrm{E}[(X_T - K)^+] = ' + f'{mean1a:.2f}$', r'$\mathrm{E}[(K - X_T)^+] = ' + f'{mean2a:.2f}$', ] #simulated_statistics.extend([r'line 8', r'line 9', r'line 10', r'line 11', r'line 12', r'line 13']) ### Get theoretical values y0 = self.randomwalk_params['S0'] n = self.randomwalk_params['T'] K = self.randomwalk_params['K'] μ = self.randomwalk_params['μ'] σ = self.randomwalk_params['σ'] Δt = self.randomwalk_params['Δt'] K = self.randomwalk_params['K'] print(self.randomwalk_params) if self.radioGRW.isChecked(): #(theo_mean, theo_var, theo_skew, theo_kurt, theo_mean1a, theo_mean2a) = theoretical_statistics_GRW(y0, u, n, p, K) (theo_mean, theo_var, theo_skew, theo_kurt, theo_mean1a, theo_mean2a) = theoretical_statistics_GBM(y0, μ, σ, T, K) elif self.radioRW.isChecked(): #(theo_mean, theo_var, theo_skew, theo_kurt, theo_mean1a, theo_mean2a) = theoretical_statistics_RW(y0, u, n, p, K) (theo_mean, theo_var, theo_skew, theo_kurt, theo_mean1a, theo_mean2a) = theoretical_statistics_BM(y0, μ, σ, T, K) else: theo_mean, theo_var, theo_skew, theo_kurt, theo_mean1a, theo_mean2a = ( 0, 0, 0, 0, 0, 0) analytical_statistics = [ ' ', '$Analytical$:', r'$\mathrm{E}(X_T) = ' + f'{theo_mean:.2f}$', r'$\mathrm{Var}(X_T) = ' + f'{theo_var:.2f}$', r'$\mathrm{Skew}(X_T) = ' + f'{theo_skew:.2f}$', r'$\mathrm{Kurt}(X_T) = ' + f'{theo_kurt:.2f}$', r'$\mathrm{E}[(X_T - K)^+] = ' + f'{theo_mean1a:.2f}$', r'$\mathrm{E}[(K - X_T)^+] = ' + f'{theo_mean2a:.2f}$', ] #statistics = list(simulated_statistics.append([r'-----'])) statistics = list(simulated_statistics) statistics.extend(analytical_statistics) #print('stats: ', statistics) #mpltext.fig = plt.figure() plt.style.use('seaborn-white') ax = mpltext.axes[0][0] ax.clear() #ax.plot([0, 0], 'r') #ax.set_title('Test') ax.axis([0, 3, -len(statistics), 0]) ax.set_yticks(-np.arange(len(statistics))) for i, s in enumerate(statistics): ax.text(0.1, -(i + 1) * 1.5, s, fontsize=14) plt.setp(plt.gca(), frame_on=False, xticks=(), yticks=()) ax.xaxis.set_ticks_position('none') ax.yaxis.set_ticks_position('none') mpltext.fig.set_visible(True) mpltext.draw() #mpl2.close() #mpl2.fig.show(False) ##### mpl.fig.set_visible(True) if self.checkBox_yLim.isChecked(): new_yLim = int(self.txt_yLim.toPlainText()) mainplot.set_ylim(top=new_yLim) mpl.draw()