def compute_expectation_mc(qgy, num_sim, n_per_year): n = qgy.n sigma2 = [] sigma2_prime = [] dt = 1 / n_per_year for i in range(1, n): for j in range(n_per_year): t = qgy.Tk[i - 1] + dt * (j + 1) sigma2.append(qgy.inf_vol(t)) sigma2_prime.append(qgy.inf_vol_prime(t)) sigma2_prime = None sigma_n = np.repeat(1, n_per_year * (n - 1)) sigma_n_prime = None #np.repeat(0, n_per_year * (n - 1)) phi_Tk = gen_phi_vec_list(qgy) psi_Tk = gen_psi_matx_list(qgy) #quasi monte carlo permut_matrix = qgy.generate_permutation_matrix(num_sim, (n - 1) * n_per_year) sob_seq = qgy.generate_sobol_squence(num_sim, 3) ###################### np.random.seed(seed=12345) ans = np.zeros(n) for i in range(num_sim): # use pesudo random number [x_n, x_y1] = qgy.generate_two_correlated_gauss( sigma_n, sigma2, qgy.rho_n_y1, (n - 1) * n_per_year, 1 / n_per_year, sigma_n_prime, sigma2_prime) x_y2 = qgy.generate_one_gauss(sigma2, (n - 1) * n_per_year, 1 / n_per_year, sigma2_prime) # use quasi random number #[x_n, x_y1] = qgy.generate_two_correlated_quasi_gauss(sigma_n, sigma2, qgy.rho_n_y1, dt, i, permut_matrix, sob_seq, [1, 2]) #x_y2 = qgy.generate_one_quasi_gauss(sigma2, dt, i, permut_matrix, sob_seq, 0) x_Tk_y1 = np.concatenate([[0], x_y1[n_per_year - 1::n_per_year]]) x_Tk_y2 = np.concatenate([[0], x_y2[n_per_year - 1::n_per_year]]) x_n_Tk = np.concatenate([[0], x_n[n_per_year - 1::n_per_year]]) one_path = np.zeros(n) for j in range(len(x_Tk_y1)): x_Tk = np.matrix([x_n_Tk[j], x_Tk_y1[j], x_Tk_y2[j]]).T X_Tk = qgy.Xt(x_Tk, phi_Tk[j], psi_Tk[j]) one_path[j] = X_Tk #plt.plot(qgy.Tk, one_path, 'g.') ans += one_path ans /= num_sim ans[0] = 1 return ans
from Model.QgyModel import * test = [10, 20, 40, 80, 160, 320] num_sim = 10000 for num_per_year in test: dt = 1 / num_per_year qgy = QgyModel() qgy.n_per_year = num_per_year N = num_per_year * (qgy.n - 1) sigma = np.repeat(1, N) res = [] for i in range(num_sim): one_path = qgy.generate_one_gauss(sigma, N, dt) res.append(one_path[-1]) #plt.plot(one_path, 'g-') #plt.show() var = np.var(res) mean = np.mean(res) print("num_per_year = ", num_per_year, "mean = ", mean, ", var = ", var)
dt = 1 / qgy.n_per_year for i in range(1, len(qgy.R_Tk_y)): for j in range(qgy.n_per_year): t = qgy.Tk[i - 1] + dt * (j + 1) sigma2.append(qgy.inf_vol(t)) sigma2_prime.append(qgy.inf_vol_prime(t)) sigma_n = np.repeat(1, N) sigma_n_prime = np.repeat(0, N) t = np.linspace(1, qgy.Tk[-1], qgy.n_per_year * (qgy.n - 1)) dist = [] N = 100 for i in range(0, N): [x_n, x_y1] = qgy.generate_two_correlated_gauss(sigma_n, sigma2, qgy.rho_n_y1, (qgy.n - 1) * qgy.n_per_year, 1 / qgy.n_per_year, sigma_n_prime, sigma2_prime) x_y2 = qgy.generate_one_gauss(sigma2, (qgy.n - 1) * qgy.n_per_year, 1 / qgy.n_per_year, sigma2_prime) x_Tk_y1 = x_y1[::qgy.n_per_year] x_Tk_y2 = x_y2[::qgy.n_per_year] plt.subplot(1, 3, 1) plt.plot(t, x_n, 'r') plt.subplot(1, 3, 2) plt.plot(t, x_y1, 'b') plt.subplot(1, 3, 3) plt.plot(t, x_y2, 'g') plt.show()