예제 #1
0
def main():
    import sys, os

    pdbfile = sys.argv[1]
    name = pdbfile[0:pdbfile.index('.')]

    atoms, x, y, z = utils.get_coordinates_from_pdb(pdbfile, name)
    atoms, x, y, z = utils.filter_by_name(
        atoms, x, y, z, 'CA')  # filter to just get the alpha carbons

    utils.write_xyz_file(
        atoms, x, y, z, name, sys.argv[2]
    )  # write coordinates to an XYZ file which can be converted to PDB

    iters = int(input("Enter amount of Monte Carlo iterations: "))
    k = int(input("Enter spring constant (how rigid is the polymer?): "))
    kBt = int(
        input(
            "Enter kbT value (Boltzmann constant times temperature of system): "
        ))
    rad = int(input("Enter how far to move atoms radially: "))

    utils.graph_protein(x, y, z, 'Initial Protein')  # graph initial protein
    monte_carlo.monte_carlo(iters, k, kBt, rad, x, y, z)

    utils.write_xyz_file(
        atoms, x, y, z, name,
        sys.argv[3])  # write XYZ file of new structure's coordinates
    utils.graph_protein(x, y, z, 'Final Protein')  # graph final protein
예제 #2
0
def monte_carlo_asian(T, S0, K, r, sigma, steps, period=False, reps=100):
    '''
    :param T: time in years
    :param S0: stock price at time = 0
    :param K: sttrike price
    :param r: risk free rate
    :param sigma: volatility
    :param steps: amount of intervals in time
    :param period: time window of asian average pricing in number of steps
    :param reps: amount of repetitions of the monte carlo progress
    :return: option price and list of payoffs
    '''

    # Initialize the monte carlo class
    mc = monte_carlo(steps, T, S0, sigma, r, K)
    payoffs = np.zeros(reps)

    for rep in range(reps):
        # Create wiener process
        mc.wiener_method()

        # Take chucks of periods, or all prices
        if period:
            prices = mc.wiener_price_path[::period]
        else:
            prices = mc.wiener_price_path

        # take the mean of the periods
        mean_price = (sum(prices) / len(prices))
        payoffs[rep] = max(mean_price - mc.K, 0)

    # calculate the price by finding the mean of the payoffs
    option_price = np.mean(payoffs)
    return option_price, payoffs
예제 #3
0
def plot_wiener_process(T, K, S0, r, sigma, steps, save_plot=False):
    """
    :param T:  Period
    :param S0: Stock price at spot time
    :param K:  Strike price
    :param r:  interest rate
    :param sigma: volatility
    :param steps: number of steps
    :param save_plot:  to save the plot
    :return:  returns a plot of a simulated stock movement
    """

    mc = monte_carlo(steps, T, S0, sigma, r, K)

    mc.wiener_method()

    plt.figure(figsize=(10, 7))
    np.linspace(
        1, mc.T * 365,
        mc.steps)  #to ensure the x-axis is in respective to the total time T
    plt.plot(np.linspace(1, mc.T * 365, mc.steps), mc.wiener_price_path)
    plt.xlabel("Days", fontsize=18, fontweight='bold')
    plt.ylabel("Stock price", fontsize=18, fontweight='bold')
    plt.tick_params(labelsize='18')
    #plt.title("Stock price simulated based on the Wiener process",fontsize=17,fontweight='bold')
    if save_plot:
        plt.savefig("figures/" + "wiener_process", dpi=300)
    plt.show()
    plt.close()
예제 #4
0
def milstein_process(T, S0, K, r, sigma, steps, save_plot=False):
    """
    :param T:  Period
    :param S0: Stock price at spot time
    :param K:  Strike price
    :param r:  interest rate
    :param sigma: volatility
    :param steps: number of steps
    :param save_plot:  to save the plot
    :return:  returns a plot of a simulated stock movement
    """

    mc = monte_carlo(steps, T, S0, sigma, r, K)

    price_path = mc.milstein_method()

    plt.figure()
    np.linspace(
        1, mc.T * 365,
        mc.steps)  # to ensure the x-axis is in respective to the total time T
    plt.plot(np.linspace(1, mc.T * 365, mc.steps), mc.milstein_price_path)
    plt.xlabel("Days", fontsize=12, fontweight='bold')
    plt.ylabel("Stock price", fontsize=12, fontweight='bold')
    plt.xticks(fontweight='bold')
    plt.yticks(fontweight='bold')
    plt.title("Milestein method", fontsize=17, fontweight='bold')
    if save_plot:
        plt.savefig("figures/" + "milestein method", dpi=300)
    plt.show()
    plt.close()
예제 #5
0
def test_multi_brownian_motion_metrics():
    """Validate multi_generate_brownian_motion sanity"""
    returns = monte_carlo.monte_carlo(multi_brownian_motion_test, tries=100000)
    spy_returns, stock_returns = zip(*returns)

    spy_mean = np.log(np.mean(spy_returns))
    assert_approx(spy_mean, SPY_MEAN)

    stock_mean = np.log(np.mean(stock_returns))
    assert_approx(stock_mean, SPY_MEAN)  # same returns

    spy_log_returns = finance_helpers.log_returns(spy_returns)
    stock_log_returns = finance_helpers.log_returns(stock_returns)

    spy_stdev = np.std(spy_log_returns)
    assert_approx(spy_stdev, SPY_STDEV)

    stock_stdev = np.std(stock_log_returns)
    assert_approx(stock_stdev, STOCK_STDEV)

    # correlate the returns together
    corr = np.corrcoef(spy_log_returns, stock_log_returns)
    assert corr.shape == (2, 2)
    correlation = corr[0][1]
    assert_approx(correlation, corr[1][0])

    # tolerance assertion
    assert_approx(correlation, STOCK_SPY_CORREL)
예제 #6
0
def control_variance_asian(T=1,
                           S0=100,
                           K=99,
                           r=0.06,
                           sigma=0.2,
                           steps=100,
                           reps=10000):
    '''
    Control variance on the Asian option price, taking geometric averaging as control since we have the
    Black-Scholes price of it. We pridict using a monte-carlo method.
    :param T: time in years
    :param S0: stock price at time = 0
    :param K: sttrike price
    :param r: risk free rate
    :param sigma: volatility
    :param steps: amount of intervals in time
    :param reps: amount of repetitions of the monte carlo progress
    :return: option price and list of payoffs
    '''
    # Initialize classes
    mc = monte_carlo(steps, T, S0, sigma, r, K)
    bs = BlackScholes(T, S0, K, r, sigma, steps)

    # Estimate Rho and get analytical option price
    N = steps
    rho = 0.99
    C_B = bs.asian_call_price()

    # Calculate B from different sigmas
    sigma_mean = sigma / np.sqrt(3)
    sigma_gmean = sigma * np.sqrt(((N + 1) * (2 * N + 1)) / (6 * N**2))

    Beta = (sigma_mean / sigma_gmean) * rho
    payoffs = np.zeros(reps)

    # Repeat monte carlo for #reps times
    for rep in range(reps):
        # Create wiener process
        mc.wiener_method()

        # Get price path
        prices = mc.wiener_price_path

        # Calculate both geometric mean and normal mean from same price path (Seed)
        mean_price = (sum(prices) / len(prices))
        gmean_price = stats.gmean(prices)

        # Calculate payoff of individual methods
        C_a = max(mean_price - mc.K, 0)
        C_b = max(gmean_price - mc.K, 0)

        # Apply control variance with analytical option price
        payoffs[rep] = C_a - Beta * (C_b - C_B)

    # Option price is equal to the mean of the payoffs
    option_price = np.mean(payoffs)

    return option_price, payoffs
예제 #7
0
def test_brownian_motion_metrics():
    """validate distribution generated conforms to expectations"""
    returns = monte_carlo.monte_carlo(brownian_motion_test, tries=100000)

    # Validate expectation/variance per GBM
    mean = finance_helpers.average_log_return(returns)
    assert_approx(mean, SPY_MEAN)

    # now we look at all the log returns and compute variance on them
    volatility = finance_helpers.volatility_of_returns(returns)
    assert_approx(volatility, SPY_STDEV)
예제 #8
0
def display():
    if request.method == "POST":
        ticker1 = request.form['ticker']
        sim_days1 = request.form['sim_days']
        sim_num1 = request.form['sim_num']

        sim = mc.monte_carlo(ticker1)
        sim.plot_historical_data()
        a1, b1 = sim.brownian_motion(int(sim_days1, 10), int(sim_num1, 10))

        return render_template('display.html', a=a1, b=b1)
        #return ticker
    else:
        return 'lol'
예제 #9
0
 def find_best(key=None):
     best = monte_carlo.monte_carlo(gameplay)
     if best:
         popup = Toplevel()
         popup.title("Recommendation")
         msg = Message(popup, text='Computed Best Strategy: '+best).pack()
         # popup.bind(sequence='<KeyPress-Return>', func=popup.destroy)
         button = Button(popup, text="Got It!", command=popup.destroy)
         button.pack()
     else:
         popup = Toplevel()
         popup.title("Lose")
         msg = Message(popup, text='You\'ve lost!').pack()
         button = Button(popup, text="OK", command=popup.destroy)
         button.pack()
예제 #10
0
 def find_best(key=None):
     best = monte_carlo.monte_carlo(gameplay)
     if best:
         popup = Toplevel()
         popup.title("Recommendation")
         msg = Message(popup, text='Computed Best Strategy: ' + best).pack()
         # popup.bind(sequence='<KeyPress-Return>', func=popup.destroy)
         button = Button(popup, text="Got It!", command=popup.destroy)
         button.pack()
     else:
         popup = Toplevel()
         popup.title("Lose")
         msg = Message(popup, text='You\'ve lost!').pack()
         button = Button(popup, text="OK", command=popup.destroy)
         button.pack()
예제 #11
0
def antithetic_monte_carlo_process(T, S0, K, r, sigma, steps, save_plot=False):

    mc = monte_carlo(steps, T, S0, sigma, r, K)

    path_list = mc.antithetic_wiener_method()

    plt.figure()
    plt.plot(path_list[0])
    plt.plot(path_list[1])
    plt.xlabel("Days", fontsize=12, fontweight='bold')
    plt.ylabel("Stock price", fontsize=12, fontweight='bold')
    plt.title("Antithetic Monte Carlo", fontsize=17, fontweight='bold')
    plt.xticks(fontweight='bold')
    plt.yticks(fontweight='bold')
    plt.show()
    plt.close()
예제 #12
0
def test_monte_carlo():

    repeat = 100
    center = np.array([0, -100, 0])
    radius = 100

    #model
    triangle = np.array([[0, -1, 0], [-50, 10, -10], [50, 10, -10],
                         [50, 10, 10]])
    model = np.array([triangle])

    des_per_cycle = 25
    cycles = 25

    hits, shots, t_nums = monte_carlo(repeat, center, radius, model,
                                      des_per_cycle)

    print("repeats = ", repeat)
    print("hits = ", hits, "/", shots, " = ", hits / shots)
예제 #13
0
def display():
    if request.method == "POST" :
            ticker1 = request.form['ticker']
            sim_days1 = request.form['sim_days']
            sim_num1 = request.form['sim_num']

            sim = mc.monte_carlo(ticker1)
            name1,name2 = sim.plot_historical_data()
            a1,b1,name3,name4 = sim.brownian_motion(int(sim_days1,10),int(sim_num1,10))


            if name1 != -1:
                return render_template('display.html', a=a1,b=b1,n1=name1,n2=name2,n3=name3,n4=name4,company_name= sim.company_name,se_name=sim.se_name)
            else:
                return render_template('display_error.html')

            
    else :
    	return redirect(url_for('index'))
예제 #14
0
def main():
    N0 = 200
    e = 0.05
    alpha = 0.01
    gamma = 1
    max_episode = 50001
    mse_list = []
    mc_Q = monte_carlo(10**6, gamma, N0)
    for lbd in np.arange(0, 1.1, 0.1):
        theta, mse = linear_approx_sarsa(max_episode, alpha, e, gamma, lbd,
                                         mc_Q)
        mse_list.append(mse[-1])
        lfp_Q = cal_q_table(theta)
        Vm = np.amax(lfp_Q, axis=2)
        if lbd == 0.0 or lbd == 1.0:
            # plot MSE against episode number
            plt.figure()
            plt.plot(np.arange(0, max_episode, 1000), mse)
            plt.xlabel("episode")
            plt.ylabel("MSE")
            plt.title("lambda = {}".format(lbd))
            plt.draw()
            # plot value function
            x = np.arange(1, 11)
            y = np.arange(1, 22)
            xs, ys = np.meshgrid(x, y)
            fig = plt.figure()
            ax = Axes3D(fig)
            ax.plot_wireframe(xs, ys, Vm.T, rstride=1, cstride=1)
            plt.title("Value function when lambda = {}".format(lbd))
            plt.draw()

    # plot mse against lambda
    plt.figure()
    plt.plot(np.arange(0, 1.1, 0.1), mse_list)
    plt.xlabel(r"$\lambda$")
    plt.ylabel("MSE")
    plt.draw()

    plt.show()
예제 #15
0
'''
cd ~/Economics/Econometrics/Homework/HW2
Project is structured as
    uniformRV to generate the random vector x
    statsmodels for the regression
    collect the results here, by calling monte_carlo from monte_carlo.py
    Plotting/analysis from this script
'''
low, high, n = (0, 10, 100)
x = uniformRV(low, high, n)
x = sm.tools.tools.add_constant(x, prepend = True)
form = lambda x: np.random.normal(10 - x[:, 1], 5)

# b is an odd matrix. b[0] is (1000, 5) The order is b0, b1, variance for b0, variance for b1, cov(b0, b1).  b[1] is the list of 1000 sample means for the y. b[2] is the 1000 MSE's, one for each iteration.

regressionResults = monte_carlo(x, 1000, form)
ybar = regressionResults[1]

# mseModel = regressionResults[2] # I don't think we want these.  We want the MSE of the residuals.
mseResiduals = regressionResults[3]
beta0 = regressionResults[0][:, 0]
beta1 = regressionResults[0][:, 1]
varBeta0 = regressionResults[0][:, 2]
varBeta1 = regressionResults[0][:, 3]
covBeta = regressionResults[0][:, 4]

# Output
print 'The mean of x is %f' % np.mean(x[:, 1])
print 'The sample mean of the means of each y vector is %f' % np.mean(ybar)
print 'The sample mean of the intercept is %f' % np.mean(beta0)
print 'The sample mean of the slope is %f' % np.mean(beta1)
예제 #16
0
def test_low_energy():
    assert MC.monte_carlo(energy,[0, 100],1e-10,100) == [50,50]
예제 #17
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 17:02:04 2018

@author: omarmgad
"""

from monte_carlo import monte_carlo
from ranking_plot import ranking_plot
from conf_int_old import conf_int_old

'''Calculates confidence intervals given 'n' sites and pandas dataframe which includes mean and standard deviation for each sample. Monte Carlo simulation can be changed by modifying 'x' to increase number of iterations (results in average of ECF_means across all simulations). Also plots the result as a forest plot.'''

n = 50 # number of sites
x = 10 # number of iterations for Monte Carlo simulation

df = monte_carlo(n, x)

df_rank = df.rank()
df = df.set_index(df_rank.iloc[:,0])
#indexes by rank intead of site number, there's still a column for site number for record keeping

#ranking_plot(df, n)
conf_int_old(df, n)
예제 #18
0
def fitness(mana_costs, land_pool):
    return sum([
        monte_carlo(1000, lambda: experiment(x, land_pool)) for x in mana_costs
    ])
예제 #19
0
def play(sess, model, number_epochs, train = True):

    win_cnt = 0
    lose_cnt = 0
    draw_cnt = 0
    win_hist = []
    cheeses = []
    steps = 0.
    last_W = 0
    last_D = 0
    last_L = 0
    
    for epoch in tqdm(range(number_epochs)):
        # We generate a new environment 
        env.reset()
        game_over = False
        input_t = env.observe()
        
        if not train :
            exp_replay.decay = 1
        if epoch < 2000 :
            # We try to find an optimized path using Monte Carlo
            mc_path = monte_carlo(env.width, env.height, env.player, env.enemy , env.piecesOfCheese)
            
        if epoch < 2000 and mc_path != [] :
            # If a path is found, we follow it in order to choose the actions
            mc_path.pop(0)
            mc_path = [ (target[0], target[1]) for target in mc_path]
            while mc_path != [] :
                input_tm1 = input_t
                current_target = mc_path[0]
                if distance(current_target, env.player) <= 1 : 
                    mc_path.pop(0)
                if current_target[0] > env.player[0] :
                    action = 1
                elif current_target[0] < env.player[0] :
                    action = 0
                elif current_target[1] > env.player[1]:
                    action = 2
                elif current_target[1] < env.player[1]: 
                    action = 3
                
                # We apply the action on the state and get the reward and the new state
                input_t, reward, game_over = env.act(action)
                exp_replay.remember([input_tm1, action, reward, input_t], game_over)
                
                    
        else :  
            # The agent is going now to be trained using random actions in order to adjust the Q-values
            while not game_over :
                input_tm1 = input_t
                if random() < exp_replay.eps :
                    action = randint(0, model._num_actions - 1)
                else:           
                    q = model.predict_one(sess, input_tm1)
                    action = np.argmax(q[0])
                exp_replay.eps = exp_replay.min_eps + (exp_replay.max_eps - exp_replay.min_eps) \
                                      * np.exp(-exp_replay.decay * epoch)
                                      
                 # We apply the action on the state and get the reward and the new state
                input_t, reward, game_over = env.act(action)
                exp_replay.remember([input_tm1, action, reward, input_t], game_over)
                
        # Statistics
        steps += env.round
        if env.score > env.enemy_score: 
            win_cnt += 1 
        elif env.score == env.enemy_score: 
            draw_cnt += 1 
        else:
            lose_cnt += 1 
        cheese = env.score 
            
        win_hist.append(win_cnt) 
        cheeses.append(cheese) 
        
        # Training the agent
        if train :
            for _ in range(number_of_batches):                
                inputs, targets = exp_replay.get_batch(model, batch_size=32)
                model.train_batch(sess, inputs.reshape((32,-1)), targets.reshape((32,-1)))
                
        # Show statistics every 100 epochs
        if (epoch + 1) % 100 == 0 : 
            cheese_np = np.array(cheeses)
            string = "Epoch {:03d}/{:03d} | Cheese count {} | Last 100 Cheese {}| W/D/L {}/{}/{} | 100 W/D/L {}/{}/{} | 100 Steps {}".format(
                        epoch, number_epochs, cheese_np.sum(), 
                        cheese_np[-100:].sum(), win_cnt, draw_cnt, lose_cnt, 
                        win_cnt-last_W, draw_cnt-last_D, lose_cnt-last_L, steps/100)
            print(string)
            winrate_pereps.append((win_cnt-last_W)/100)
            drawrate_pereps.append((draw_cnt-last_D)/100)
            steps = 0.
            last_W = win_cnt
            last_D = draw_cnt
            last_L = lose_cnt                
예제 #20
0
def LR_method(T,
              S0,
              K,
              r,
              sigma,
              steps,
              set_seed="random",
              reps=[100],
              contract="call",
              seed_nr=10,
              option_type="digital",
              show_plot=False,
              save_plot=False,
              save_output=False):
    """
    ONLY FOR DIGITAL OPTION.
    """

    # Initialize variables
    diff_reps = len(reps)
    deltas = np.zeros(diff_reps)
    std_deltas = np.zeros(diff_reps)
    discount = math.exp(-r * T)
    mc = monte_carlo(steps, T, S0, sigma, r, K)

    seeds = []
    if set_seed == "fixed":
        seeds = [seed_nr for _ in range(diff_reps)]

    # Start likelihood ratio method for a different amount of repititions
    for i, rep in enumerate(reps):

        # If given, fix seed
        if seeds:
            np.random.seed(set_seed[i])

        # Generate random normally distrivuted numbers for given repitition
        # determine stock prices and payoffs and calculate (average) deltas
        numbers = np.random.normal(size=rep)
        scores = numbers / (S0 * sigma * math.sqrt(T))
        S = mc.euler_method_vectorized(numbers)
        payoffs = np.where(S - K > 0, 1, 0)
        d = discount * payoffs * scores
        deltas[i] = d.mean()
        std_deltas[i] = payoffs.std() / math.sqrt(rep)

    # Theoretical delta
    bs_deltas = np.ones(diff_reps)
    d2 = (np.log(S0 / K) + (r - 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
    num = discount * stats.norm.pdf(d2, 0.0, 1.0)
    den = sigma * S0 * math.sqrt(T)
    bs_deltas = bs_deltas * num / den

    # Determine relative errors
    errors = np.abs(1 - (deltas / bs_deltas))

    if show_plot or save_plot:
        plot_LR(reps, errors, std_deltas, option_type, contract, set_seed,
                show_plot, save_plot)

    # Save output, if required
    if save_output:
        name = os.path.join("Data",
                            f"{option_type}-{contract}_LR_{set_seed}seed_")
        save_output_ex2(name, K, sigma, deltas, bs_deltas, errors, std_deltas)

    return deltas, bs_deltas, errors, std_deltas
예제 #21
0
import monte_carlo as mc

sim = mc.monte_carlo('AAPL')

sim.plot_historical_data()

sim.brownian_motion(200, 1000)
import matplotlib.pyplot as plt
import sys
sys.path.append('coin_flipping_src')
from monte_carlo import monte_carlo
from probability import probability
plt.style.use('bmh')
x_coords = range(10)
probablility_results = [probability(x, 10) for x in x_coords]
plt.plot(x_coords, probablility_results, linewidth=2.5)
# plt.plot([0,1,2,3,4],[0.1, 0.3, 0.5, 0.1, 0.1],linewidth=2.5)
for _ in range(5):
    plt.plot(x_coords, [monte_carlo(x, 10, 100) for x in x_coords],
             linewidth=0.75)
# plt.plot([0,1,2,3,4],[0.3, 0.1, 0.4, 0.2, 0.1],linewidth=0.75)
# plt.plot([0,1,2,3,4],[0.2, 0.2, 0.3, 0.3, 0.2],linewidth=0.75)
plt.legend(['True', 'MC 1', 'MC 2', 'MC 3', 'MC 4', 'MC 5'])
plt.xlabel('Number of Heads')
plt.ylabel('Probability')
plt.title('True Distribution vs Monte Carlo Simulations for 10 Coin Flips')
plt.savefig('plot.png')
plt.show()
def fitness(mana_costs, land_pool):
	return sum([monte_carlo(1000, lambda: experiment(x, land_pool)) for x in mana_costs])
예제 #24
0
def bump_revalue_vectorized(T,
                            S0,
                            K,
                            r,
                            sigma,
                            steps,
                            epsilons=[0.5],
                            seeds=[],
                            reps=100,
                            full_output=False,
                            option_type="regular",
                            contract="put"):
    """
    Applies bump and revalue method to determine the delta at spot time
    """

    # Init amount of bumps (epsilons) and storage (Black Scholes) deltas
    diff_eps = len(epsilons)
    deltas = np.zeros(diff_eps)
    bs_deltas = np.zeros(diff_eps)
    std_deltas = np.zeros(diff_eps)
    discount = math.exp(-r * T)

    # Start MC simulation for each bump
    for i, eps in enumerate(epsilons):

        # Determine "bumped" price
        S0_eps = S0 + eps

        # Create bump and revalue Monte Carlo (MC) objects
        mc_revalue = monte_carlo(steps, T, S0, sigma, r, K)
        mc_bump = monte_carlo(steps, T, S0_eps, sigma, r, K)

        # Determine stock prices at maturity
        S_rev, S_bump = stock_prices_bump_revalue(seeds, reps, mc_revalue,
                                                  mc_bump, i)

        # Determine prices and delta hedging depending at spot time
        results = payoff_and_hedge_options(option_type, contract, S_rev,
                                           S_bump, S0_eps, K, r, sigma, T,
                                           bs_deltas, discount, i)
        prices_revalue, prices_bump, bs_deltas = results

        # Mean and variance option prices bump and revalue
        mean_revalue = prices_revalue.mean()
        mean_bump = prices_bump.mean()
        var_bump = prices_bump.var()
        var_revalue = prices_revalue.var()

        # Determine MC delta and its variance
        deltas[i] = (discount * (mean_bump - mean_revalue)) / eps
        var_delta = 0
        if not seeds:
            cov_br = np.cov(prices_bump, prices_revalue)[0, 1]
            var_delta = (1 / (eps * eps)) * (
                (var_bump + var_revalue - 2 * cov_br) / reps)

        # print("Var BUMP:", round(var_bump, 3))
        # print("Var REVALUE", round(var_revalue, 3))
        # print("COVARIANCE:", round(cov_br, 3))
        # print("Var DELTA:", round(var_delta, 3))
        # print("========================================================")

        std_deltas[i] = math.sqrt(var_delta)

    # Determine relative (percent) errors
    errors = np.abs(1 - (deltas / bs_deltas))

    # Checks if full output is required
    if full_output:
        return deltas, bs_deltas, errors, std_deltas, prices_revalue, prices_bump

    return deltas, bs_deltas, errors, std_deltas
예제 #25
0
    # Read CsTSI sequence
    cstsi_seq = list(parse_fasta(get_data(CSTSI_PROTEIN)))[0][1]

    # Analyze CsGSI sequence
    print("Analyzing %s..." % CSGSI_PROTEIN)

    csgsi_seq = list(parse_fasta(get_data(CSGSI_PROTEIN)))[0][1]
    alignment_result = align_sequences(csgsi_seq, cstsi_seq, nucleotides=False)

    for clusters in CLUSTER_COUNTS:
        print(
            f"Variance between clusters ({clusters} clusters): {str(alignment_result.clustered_mismatch_variance(cluster_count=clusters))}"
        )

        # Simulate random sequences
        simulation_result = monte_carlo(
            get_clustering_simulation_fn(cstsi_seq, csgsi_seq),
            get_effect_size_fn(cluster_count=clusters),
            observed_effect_size=alignment_result.clustered_mismatch_variance(
                cluster_count=clusters),
            n_trials=n_trials,
        )

        make_output_dir()
        with open(get_output(f"monte_carlo_{clusters}.{simulation_id}.json"),
                  "w+") as f:
            f.write(simulation_result.to_json())

        simulation_result.examine()
예제 #26
0
def diff_monte_carlo_process(T,
                             S0,
                             K,
                             r,
                             sigma,
                             steps,
                             samples,
                             save_plot=False):
    """
    :param T:  Period
    :param S0: Stock price at spot time
    :param K:  Strike price
    :param r:  interest rate
    :param sigma: volatility
    :param steps: number of steps
    :param save_plot:  to save the plot
    :return:  returns a plot of a simulated stock movement
    """

    different_mc_rep = samples
    increments = len(samples)

    # mc_pricing will be a dict a list containing  tuples of (pricing and standard error)
    mc_pricing = defaultdict(list)

    for repetition in tqdm.tqdm(different_mc_rep):

        mc_list = [
            monte_carlo(steps, T, S0, sigma, r, K) for i in range(repetition)
        ]
        num_core = 3
        pool = multiprocessing.Pool(num_core)
        pay_off_list = pool.map(worker_pay_off_euler_direct,
                                ((mc) for mc in mc_list))
        pool.close()
        pool.join()

        mean_pay_off = np.mean([pay_off for pay_off in pay_off_list])
        std_pay_off = np.std([pay_off for pay_off in pay_off_list
                              ]) / np.sqrt(repetition)
        mc_pricing['euler_integration'].append(
            (np.exp(-r * T) * mean_pay_off, std_pay_off))

    bs = BlackScholes(T, S0, K, r, sigma)
    bs_solution = np.ones(increments) * bs.put_price()
    print(bs.put_price())

    for i in range(len(different_mc_rep)):
        print("Number of samples: ", different_mc_rep[i], " Mean :",
              mc_pricing['euler_integration'][i][0], " Variance :",
              mc_pricing['euler_integration'][i][1])

    fig, axs = plt.subplots(2, figsize=(10, 7))
    axs[0].plot(different_mc_rep,
                [i[0] for i in mc_pricing['euler_integration']],
                color='gray',
                label='Monte Carlo')
    axs[0].plot(different_mc_rep, bs_solution, 'r', label='Black Scholes')
    axs[0].legend()
    axs[0].set_ylabel("Option Price", fontsize=17)
    axs[0].tick_params(labelsize='18')

    axs[1].plot(different_mc_rep,
                [i[1] for i in mc_pricing['euler_integration']],
                label='Standard error')
    axs[1].set_xlabel("Monte Carlo repetition", fontsize=17)
    axs[1].legend()
    axs[1].set_ylabel("Standard error", fontsize=17)
    axs[1].tick_params(labelsize='18')
    axs[1].ticklabel_format(axis="y", style="sci", scilimits=(0, 0))

    if save_plot:
        plt.savefig("figures/" + "mc_euler_integration_diff_MC", dpi=300)
    plt.show()
    plt.close()
예제 #27
0
import math
from monte_carlo import monte_carlo
from probability import probability


def kl_divergence(p, q):
    divergence = 0
    for i in range(len(p)):
        divergence += p[i] * (math.log(p[i] / q[i]))
    return divergence


def fix_zeroes(arr):
    for i in range(len(arr)):
        if arr[i] == 0:
            arr[i] = 0.0001
    return arr


probability_results = [probability(x, 10) for x in range(10)]
monte_carlo_100 = fix_zeroes([monte_carlo(x, 10, 100) for x in range(10)])
monte_carlo_1000 = fix_zeroes([monte_carlo(x, 10, 1000) for x in range(10)])
monte_carlo_10000 = [monte_carlo(x, 10, 10000) for x in range(10)]
print("\nDivergence with 100 trials: ")
print("\n   " + str(kl_divergence(probability_results, monte_carlo_100)))
print("\nDivergence with 1000 trials: ")
print("\n   " + str(kl_divergence(probability_results, monte_carlo_1000)))
print("\nDivergence with 1000 trials: ")
print("\n   " + str(kl_divergence(probability_results, monte_carlo_10000)))

# As the number of samples increases, the KL divergence gets closer to 0 because as the number of trials increases the monte_carlo estimation gets closer and closer the the actual probability.
예제 #28
0
import random
from config import config
from monte_carlo import monte_carlo, get_M
from vizualization import *

L = 5
N = 10
N_max = 5

if __name__ == "__main__":
    matrix = config(L)
    Ms = list()
    for _ in range(N_max):
        monte_carlo(matrix, N, L)
        Ms.append(get_M(matrix))
    visualize_matrix(matrix)
from probability import probability
from monte_carlo import monte_carlo

print("Monte Carlo Results:")
for _ in range(3):
    print("\n   " + str(monte_carlo(5, 8, 1000)))

print("\nProbability:")
print("\n   " + str(probability(5, 8)))