def main(): problem_name0 = 'AllenCahn' config = get_config(problem_name0) bsde = get_equation(problem_name0, config.dim, config.total_time, config.num_time_interval) # log_dir = './logs' # if not os.path.exists(log_dir): # os.mkdir(log_dir) # path_prefix = os.path.join(log_dir, problem_name0) # with open('{}_config.json'.format(path_prefix), 'w') as outfile: # json.dump(dict((name, getattr(config, name)) # for name in dir(config) if not name.startswith('__')), # outfile, indent=2) # logging.basicConfig(level=logging.INFO, # format='%(levelname)-6s %(message)s') for idx_run in range(1, 2): tf.reset_default_graph() with tf.Session() as sess: logging.info('Begin to solve %s with run %d' % (problem_name0, idx_run)) model = FeedForwardModel(config, bsde, sess) if bsde.y_init: logging.info('Y0_true: %.4e' % bsde.y_init) model.build() training_history = model.train() print(training_history)
def main(): problem_name = FLAGS.problem_name config = get_config(problem_name) bsde = get_equation(problem_name, config.dim, config.total_time, config.num_time_interval) if not os.path.exists(FLAGS.log_dir): os.mkdir(FLAGS.log_dir) path_prefix = os.path.join(FLAGS.log_dir, problem_name) with open('{}_config.json'.format(path_prefix), 'w') as outfile: json.dump(dict((name, getattr(config, name)) for name in dir(config) if not name.startswith('__')), outfile, indent=2) logging.basicConfig(level=logging.INFO, format='%(levelname)-6s %(message)s') for idx_run in range(1, FLAGS.num_run + 1): tf.reset_default_graph() with tf.Session() as sess: logging.info('Begin to solve %s with run %d' % (problem_name, idx_run)) model = FeedForwardModel(config, bsde, sess) if bsde.y_init: logging.info('Y0_true: %.4e' % bsde.y_init) model.build() training_history = model.train() if bsde.y_init: logging.info('relative error of Y0: %s', '{:.2%}'.format( abs(bsde.y_init - training_history[-1, 2]) / bsde.y_init)) # save training history np.savetxt('{}_training_history_{}.csv'.format(path_prefix, idx_run), training_history, fmt=['%d', '%.5e', '%.5e', '%d'], delimiter=",", header="step,loss_function,target_value,elapsed_time", comments='')
def main(): problem_name0 = 'AllenCahn' config = get_config(problem_name0) bsde = get_equation(problem_name0, config.dim, config.total_time, config.num_time_interval) log_dir = './logs' if not os.path.exists(log_dir): os.mkdir(log_dir) path_prefix = os.path.join(log_dir, problem_name0) # with open('{}_config.json'.format(path_prefix), 'w') as outfile: # json.dump(dict((name, getattr(config, name)) # for name in dir(config) if not name.startswith('__')), # outfile, indent=2) # logging.basicConfig(level=logging.INFO, b # format='%(levelname)-6s %(message)s') for idx_run in range(1, 2): tf.reset_default_graph() with tf.Session() as sess: # sess = tf_debug.LocalCLIDebugWrapperSession(sess) # logging.info('Begin to solve %s with run %d' % (problem_name0, idx_run)) model = FeedForwardModel(config, bsde, sess) # if bsde.y_init: # logging.info('Y0_true: %.4e' % bsde.y_init) model.build() training_history = model.train() # training_history.reshape(1,-1) print(training_history) np.savetxt('{}_training_history_{}.csv'.format( path_prefix, idx_run), training_history, fmt=['%.5e', '%d'], delimiter=",", header="loss_function,elapsed_time", comments='') writer = tf.summary.FileWriter('./graph/qgraph', sess.graph)
def main(): problem_name = FLAGS.problem_name # get probelm name config = get_config(problem_name) if not os.path.exists(FLAGS.log_dir1): # check to see if this log directory already exists os.mkdir(FLAGS.log_dir1) path_prefix = os.path.join(FLAGS.log_dir1, problem_name) # create the name of the path file total_Time = config.total_time num_time_interval = config.num_time_interval dt = total_Time / num_time_interval print("----- BEFORE ITERS ----- ") print("total_Time: ", total_Time) print("num_time_interval: ", num_time_interval) print("dt: ", dt) ### CALCULATING PORTFOLIOS bsde = get_equation(problem_name, config.dim, total_Time, num_time_interval) wealth = bsde.wealth() gamma = bsde.gamma() mu = bsde.mu() r = bsde.interest_Rate() alpha_revert = bsde.alpha_Revert() delta_revert = bsde.delta_Revert() rho_1 = bsde.rho1() rho_2 = bsde.rho2() rho_12 = bsde.rho12() nu_f = bsde.nu_f() nu_s = bsde.nu_s() mf = bsde.muF() ms = bsde.muS() print("wealth: ", wealth) print("gamma: ", gamma) print("mu: ", mu) print("r: ", r) print("alpha_revert: ", alpha_revert) print("delta_revert: ", delta_revert) print("rho1: ", rho_1) print("rho2: ", rho_2) print("rho12: ", rho_12) print("nu_f: ", nu_f) print("nu_s: ", nu_s) print("mf: ", mf) print("ms: ", ms) num_Samples = 2 dw_Factors, process_Factors, stockPrice = simStockMultiscale(num_Samples, mu, r, alpha_revert, delta_revert, rho_1, rho_2, rho_12, nu_f, nu_s, dt, num_time_interval, mf, ms) print("all dw_Factors: ", dw_Factors) print("all process_Factors: ", process_Factors) print("all stockPrices: ", stockPrice) merton_Sample_Payoffs = np.array([]) merton_Portfolio_Value_Over_Time = np.array([]) merton_Strats_Over_Time = np.array([]) NN_Sample_Payoffs = np.array([]) NN_Portfolio_Value_Over_Time = np.array([]) NN_Strats_Over_Time = np.array([]) print("------------------ PORTFOLIO STAGE ----------------------") nn_Position_In_Stock = 0 # gives number of stocks purchased nn_Wealth_In_Bonds = 0 # gives amount of money in risk free nn_Portfolio_Value = wealth merton_Position_In_Stock = 0 # gives number of stocks purchased merton_Wealth_In_Bonds = 0 merton_Portfolio_Value = wealth # fix the first sampel sample dw_Factor_Sample = dw_Factors[0, :, :] process_Factors_Sample = process_Factors[0, :, :] print("dw_Factor_Sample: ", dw_Factor_Sample) print("process_Factors_Sample: ", process_Factors_Sample) print("\n") for time_Index in range(num_time_interval): tf.reset_default_graph() print("------------------ Time_Index: ", time_Index, " ------------------------- \n") with tf.Session() as sess: remaining_Time = total_Time - time_Index * dt remaining_Intervals = num_time_interval - time_Index print("remaining Time: ", remaining_Time) print("remaining Intervals: ", remaining_Intervals) #logging.info('Begin to solve %s with run %d' % (problem_name, idx_run)) #config.setTotalTime(remaining_Time) print("config.total_time before change: ", config.total_time) print("config.num_time_interval before change: ", config.num_time_interval) config.total_time = remaining_Time config.num_time_interval = remaining_Intervals print("config.total_time after change: ", config.total_time) print("config.num_time_interval after change: ", config.num_time_interval) #config.setNumTimeIntervals(remaining_Intervals) ### change the factors to update to current time curr_Factors = process_Factors[0, :, time_Index] # get x (y, z if exists) at first time step curr_Y_Factor = process_Factors[0, 0, time_Index] curr_Z_Factor = process_Factors[0, 1, time_Index] curr_Stock_Price = stockPrice[0, 0, time_Index] print("curr_Factors: ", curr_Factors) print("curr_Stock_Price: ", curr_Stock_Price) print("curr_Y_Factor: ", curr_Y_Factor) print("curr_Z_Factor: ", curr_Z_Factor) bsde = get_equation(problem_name, config.dim, remaining_Time, remaining_Intervals) bsde.setY(curr_Y_Factor) bsde.setZ(curr_Z_Factor) print("bsde Y Factor: ", bsde.getY()) print("bsde Z Factor: ", bsde.getZ()) ###### IMPORTANT ###### model = FeedForwardModel(config, bsde, sess, problem_name) # create the feed forward model #if bsde.y_init: # logging.info('Y0_true: %.4e' % bsde.y_init) model.build() # bulid the model training_history = model.train() # trin the model #if bsde.y_init: # logging.info('relative error of Y0: %s', # '{:.2%}'.format( # abs(bsde.y_init - training_history[-1, 2])/bsde.y_init)) # save training history #training_history = np.append(training_history, bsde._total_time) np.savetxt('{}_training_history_{}.csv'.format(path_prefix, time_Index), training_history, fmt=['%d', '%.5e', '%.5e', '%d'], delimiter=",", header="step,loss_function,target_value,elapsed_time", comments='') print("dw_Factor_Sampe[:, time_Index:]: ", dw_Factor_Sample[:, time_Index:]) print("process_Factors_Sample[:, time_Index]: ", process_Factors_Sample[:, time_Index:]) init_Out, output_Z_Vals = model.simPortfolio() current_Sample = output_Z_Vals[:, 0, :] print("init_Out: ", init_Out) print("output_Z_Vals: ", output_Z_Vals) print("current_Sample: ", current_Sample) print("current_Sample[0, :]: ", current_Sample[0, :]) mat_Sqrt = model.calculate_Diffusion_Mat(curr_Factors) grads = np.linalg.solve(np.transpose(mat_Sqrt), current_Sample[0, :]) print("mat_Sqrt: ", mat_Sqrt) print("grads: ", grads) g_y = grads[0] g_z = grads[1] V_x = wealth**(gamma - 1) * math.exp(-init_Out) V_xx = (gamma - 1) * wealth**(gamma - 2) * math.exp(-init_Out) V_xy = -g_y * wealth**(gamma - 1) * math.exp(-init_Out) V_xz = -g_z * wealth**(gamma - 1) * math.exp(-init_Out) nn_pi_Strategy = -((mu - r) * V_x + math.sqrt(2 * alpha_revert) * nu_f * rho_1 * math.exp(curr_Y_Factor + curr_Z_Factor) * V_xy + math.sqrt(2 * delta_revert) * nu_s * rho_2 * math.exp(curr_Y_Factor + curr_Z_Factor) * V_xz) / (math.exp(2 * (curr_Y_Factor + curr_Z_Factor)) * wealth * V_xx) merton_Strategy = (mu - r) / (math.exp(2 * (curr_Y_Factor + curr_Z_Factor)) * (1 - gamma)) print("nn_pi_Strategy: ", nn_pi_Strategy) print("merton_Strategy: ", merton_Strategy) # if initial time create the portfolios if time_Index == 0: nn_Position_In_Stock = (nn_pi_Strategy * wealth) / curr_Stock_Price # gives number of stocks purchased nn_Wealth_In_Bonds = wealth - nn_Position_In_Stock * curr_Stock_Price # gives amount of money in risk free nn_Portfolio_Value = wealth merton_Position_In_Stock = (merton_Strategy * wealth) / curr_Stock_Price # gives number of stocks purchased merton_Wealth_In_Bonds = wealth - merton_Position_In_Stock * curr_Stock_Price merton_Portfolio_Value = wealth else: # rebalance # update NN Portfolio value nn_Portfolio_Value = nn_Wealth_In_Bonds * math.exp(r * dt) + curr_Stock_Price * nn_Position_In_Stock print("nn portfolio after change: ", nn_Portfolio_Value) # update merton Portfolio value merton_Portfolio_Value = merton_Wealth_In_Bonds * math.exp(r * dt) + curr_Stock_Price * merton_Position_In_Stock print("merton portfolio after change: ", merton_Portfolio_Value) # rebalance portfolios nn_Position_In_Stock = (nn_pi_Strategy * nn_Portfolio_Value) / curr_Stock_Price # gives number of stocks purchased nn_Wealth_In_Bonds = nn_Portfolio_Value - nn_Position_In_Stock * curr_Stock_Price # gives amount of money in risk free merton_Position_In_Stock = (merton_Strategy * merton_Portfolio_Value) / curr_Stock_Price # gives number of stocks purchased merton_Wealth_In_Bonds = merton_Portfolio_Value - merton_Position_In_Stock * curr_Stock_Price merton_Portfolio_Value_Over_Time = np.append(merton_Portfolio_Value_Over_Time, merton_Portfolio_Value) NN_Portfolio_Value_Over_Time = np.append(NN_Portfolio_Value_Over_Time, nn_Portfolio_Value) merton_Strats_Over_Time = np.append(merton_Strats_Over_Time, merton_Position_In_Stock) NN_Strats_Over_Time = np.append(NN_Strats_Over_Time, nn_Position_In_Stock) print("nn_Position_In_Stock: ", nn_Position_In_Stock) print("nn_Wealth_In_Bonds: ", nn_Wealth_In_Bonds) print("merton_Position_In_Stock: ", merton_Position_In_Stock) print("merton_Wealth_In_Bonds: ", merton_Wealth_In_Bonds) print("\n\n") print("\n ----------- FINAL REBALANCE ------------------ \n") curr_Stock_Price = stockPrice[0, 0, -1] nn_Portfolio_Value = nn_Wealth_In_Bonds * math.exp(r * dt) + curr_Stock_Price * nn_Position_In_Stock print("nn portfolio after change: ", nn_Portfolio_Value) # update merton Portfolio value merton_Portfolio_Value = merton_Wealth_In_Bonds * math.exp(r * dt) + curr_Stock_Price * merton_Position_In_Stock print("merton portfolio after change: ", merton_Portfolio_Value) # add final rebalance merton_Portfolio_Value_Over_Time = np.append(merton_Portfolio_Value_Over_Time, merton_Portfolio_Value) NN_Portfolio_Value_Over_Time = np.append(NN_Portfolio_Value_Over_Time, nn_Portfolio_Value) merton_Strats_Over_Time = np.append(merton_Strats_Over_Time, merton_Position_In_Stock) NN_Strats_Over_Time = np.append(NN_Strats_Over_Time, nn_Position_In_Stock) nn_Payoff = (nn_Portfolio_Value)**gamma / gamma merton_Payoff = (merton_Portfolio_Value)**gamma / gamma print("nn_Payoff: ", nn_Payoff) print("merton_Payoff: ", merton_Payoff) NN_Sample_Payoffs = np.append(NN_Sample_Payoffs, nn_Payoff) merton_Sample_Payoffs = np.append(merton_Sample_Payoffs, merton_Payoff) np.savetxt('{}_NNPandL.csv'.format(path_prefix), NN_Sample_Payoffs, fmt=['%.5e'], delimiter=",", header="Samples", comments='') np.savetxt('{}_MertonPandL.csv'.format(path_prefix), merton_Sample_Payoffs, fmt=['%.5e'], delimiter=",", header="Samples", comments='') np.savetxt('{}_NNValueOverTime.csv'.format(path_prefix), NN_Portfolio_Value_Over_Time, fmt=['%.5e'], delimiter=",", header="Data", comments='') np.savetxt('{}_MertonValueOverTime.csv'.format(path_prefix), merton_Portfolio_Value_Over_Time, fmt=['%.5e'], delimiter=",", header="Data", comments='') np.savetxt('{}_MertonStratsOverTime.csv'.format(path_prefix), merton_Strats_Over_Time, fmt=['%.5e'], delimiter=",", header="Data", comments='') np.savetxt('{}_NNStratsOverTime.csv'.format(path_prefix), NN_Strats_Over_Time, fmt=['%.5e'], delimiter=",", header="Data", comments='')
price = opttype * (F * norm.cdf(opttype * d1) - K * norm.cdf(opttype * d2)) * np.exp(-r * T) return price #params dim, total_time, num_time_interval = 1, 1, 10 sigma, r, K = 0.2, 0.02, 100 ob_range = (60, 140) #fit eurOption = EuropeanCall(dim, total_time, num_time_interval, sigma, r, K, ob_range) tf.reset_default_graph() with tf.Session() as sess: model = FeedForwardModel(sess, eurOption, EuropeanCallConfig()) model.build() f_graphs, z_graphs = model.train() #plot fig, ax = plt.subplots() l, u = ob_range num = EuropeanCallConfig().ob_num ax.plot(np.linspace(l, u, num), f_graphs.flatten()) ax.plot( np.linspace(l, u, num), blackscholes_price(K, total_time, np.linspace(l, u, num), sigma, r, 0, 'call'), 'g') plt.grid(linewidth=1) for i in range(len(z_graphs)):
def main(): problem_name = FLAGS.problem_name # get probelm name config = get_config(problem_name) bsde = get_equation(problem_name, config.dim, config.total_time, config.num_time_interval) if not os.path.exists( FLAGS.log_dir1 ): # check to see if this log directory already exists os.mkdir(FLAGS.log_dir1) path_prefix = os.path.join( FLAGS.log_dir1, problem_name) # create the name of the path file with open('{}_config.json'.format(path_prefix), 'w') as outfile: json.dump(dict((name, getattr(config, name)) for name in dir(config) if not name.startswith('__')), outfile, indent=2) logging.basicConfig(level=logging.INFO, format='%(levelname)-6s %(message)s') ## Order of calls # 1) Repeat the experiment the number of times you indicate # 2) Create the feed forward network # 3) Build the Model # 4) Train the model # normal pricing """ for idx_run in range(1, 2): tf.reset_default_graph() with tf.Session() as sess: #logging.info('Begin to solve %s with run %d' % (problem_name, idx_run)) ###### IMPORTANT ###### model = FeedForwardModel(config, bsde, sess, problem_name) # create the feed forward model if bsde.y_init: logging.info('Y0_true: %.4e' % bsde.y_init) model.build() # bulid the model training_history = model.train() # trin the model #if bsde.y_init: #logging.info('relative error of Y0: %s', # '{:.2%}'.format( # abs(bsde.y_init - training_history[-1, 2])/bsde.y_init)) # save training history np.savetxt('{}_training_history_{}.csv'.format(path_prefix, idx_run), training_history, fmt=['%d', '%.5e', '%.5e', '%d'], delimiter=",", header="step,loss_function,target_value,elapsed_time", comments='') """ # for just IV Pricing """ vals = np.array([]) for idx_run in range(1, 3): tf.reset_default_graph() with tf.Session() as sess: #logging.info('Begin to solve %s with run %d' % (problem_name, idx_run)) ###### IMPORTANT ###### model = FeedForwardModel(config, bsde, sess, problem_name) # create the feed forward model if bsde.y_init: logging.info('Y0_true: %.4e' % bsde.y_init) model.build() # bulid the model training_history = model.train() # trin the model #if bsde.y_init: # logging.info('relative error of Y0: %s', # '{:.2%}'.format( # abs(bsde.y_init - training_history[-1, 2])/bsde.y_init)) # save training history vals = np.append(vals, training_history[len(training_history) - 1, 2]) vals = np.append(vals, bsde._total_time) num_Iter = 1 while os.path.exists('{}_training_history_{}_{}.csv'.format(path_prefix, idx_run, num_Iter)): num_Iter += 1 np.savetxt('{}_training_history_{}_{}.csv'.format(path_prefix, idx_run, num_Iter), vals, fmt=['%.5e'], delimiter=",", header="target_value", comments='') """ ### FOR JUST DELTA HEDGING / CALCULATING PORTFOLIOS for idx_run in range(1, 2): tf.reset_default_graph() with tf.Session() as sess: #logging.info('Begin to solve %s with run %d' % (problem_name, idx_run)) ###### IMPORTANT ###### model = FeedForwardModel( config, bsde, sess, problem_name) # create the feed forward model #if bsde.y_init: # logging.info('Y0_true: %.4e' % bsde.y_init) model.build() # bulid the model training_history = model.train() # trin the model #if bsde.y_init: # logging.info('relative error of Y0: %s', # '{:.2%}'.format( # abs(bsde.y_init - training_history[-1, 2])/bsde.y_init)) # save training history num_Iter = 1 while os.path.exists('{}_training_history_{}_{}.csv'.format( path_prefix, idx_run, num_Iter)): num_Iter += 1 #training_history = np.append(training_history, bsde._total_time) np.savetxt('{}_training_history_{}_{}.csv'.format( path_prefix, idx_run, num_Iter), training_history, fmt=['%d', '%.5e', '%.5e', '%d'], delimiter=",", header="step,loss_function,target_value,elapsed_time", comments='') output = model.calcPortfolioStrategyMS() num_Iter = 1 while os.path.exists('{}_Strat_{}.csv'.format( path_prefix, num_Iter)): num_Iter += 1 output = np.append(output, bsde._num_time_interval) np.savetxt('{}_Strat_{}.csv'.format(path_prefix, num_Iter), output, fmt=['%f'], delimiter=",", header="Delta", comments='')