Esempio n. 1
0
def get_wavelet_var(wavelet, H=0.3, samp_size=1024, plot_sil=1):
    f = FBM(n=samp_size, hurst=H, length=0.5, method='daviesharte')
    fbm_sample = f.fbm()
    t_values = f.times()
    cA, cD = pywt.dwt(fbm_sample, wavelet)

    M = len(cD)
    R = np.zeros(M + 1)

    for k in range(M + 1):
        cD_shift = shift(cD, k, cval=0)
        R[k] = np.sum(cD * np.conjugate(cD_shift))

    print(M + 1)
    print(np.argmin(R))
    plt.plot(R)
    plt.show()
    AutoCorr_mat = toeplitz(R[0:M], R[0:M]) + 2.5
    #pdb.set_trace()

    mean_corr = (np.sum(AutoCorr_mat) - M * AutoCorr_mat[0][0]) / (M**2 - M)
    #print(mean_corr)
    max_corr = np.max(R[1:])
    #pdb.set_trace()
    U, S, V = svd(AutoCorr_mat)
    if (plot_sil != 1):
        plt.plot(np.log10(np.arange(M) + 1), np.log10(S))

    return S[0], 1 + (M - 1) * mean_corr
Esempio n. 2
0
def test_FBM_fgn_adjust_rnd(n_good, hurst_good, length_good,
                              fbm_method_good, adjust_rnd_good):
    f = FBM(n_good, hurst_good, length_good, fbm_method_good)
    fgn_sample = f.fgn()
    fgn_sample = f.fgn(adjust_rnd_good)
    assert isinstance(fgn_sample, np.ndarray)
    assert len(fgn_sample) == n_good
Esempio n. 3
0
 def daviesharte_to_hosking_fallback_test(self):
     # Low n, high hurst
     f = FBM(5, 0.99, 1, method='daviesharte')
     # This only works on py3
     # with self.assertWarns(Warning):
     #     s = f.fbm()
     with warnings.catch_warnings(record=True) as w:
         s = f.fbm()
         self.assertEqual(len(w), 1)
         self.assertIn('invalid for Davies-Harte', str(w[-1].message))
     self.assertEqual('hosking', f.method)
Esempio n. 4
0
def generate_labeled_data(n_samples_each, sample_length, H_1, H_2):
    """ Generates sample fBm paths using the fbm module."""
    data_1 = np.array([FBM(n=sample_length, hurst=H_1, length=1,
                         method='daviesharte').fbm() for j in range(n_samples)])
    permutation_1 = np.random.permutation(data_1.shape[0])
    data_1 = data_1[permutation_1]
    
    data_2 = np.array([FBM(n=sample_length, hurst=H_2, length=1,
                         method='daviesharte').fbm() for j in range(n_samples)])
    permutation_2 = np.random.permutation(data_2.shape[0])
    data_2 = data_2[permutation_2]
    
    data_1 = np.pad(data_1, ((0,0), (0,1)), mode='constant', constant_values=H_1)
    data_2 = np.pad(data_1, ((0,0), (0,1)), mode='constant', constant_values=H_2)
    return data_1, data_2
Esempio n. 5
0
def getPriceTrajectory(N_prices, current, iterations, dt, prob, m0, N_mo,
                       return_book):
    bid = np.zeros(N_prices)
    ask = np.zeros(N_prices)
    ############################metaorders_initialization + fractional brownian noise
    fbm = FBM(n=iterations,
              hurst=0.75,
              length=iterations * dt,
              method="daviesharte").fgn()
    # fbm = m0*np.random.normal(0,dt,iterations)
    #rates = np.ones(N_mo)*m0*dt
    #rates = np.floor(rates).astype(int) + np.random.binomial(1,rates-np.floor(rates).astype(int))
    noise = m0 * fbm
    noise = np.floor(noise).astype(int)
    noise += np.random.binomial(1, m0 * fbm - noise)
    D = prob / (2 * dt)
    ll = (current / D)  #Latent Liquidity
    index = int((N_prices / 2) + 1)
    ask[index:] = ll * np.arange(index - N_prices / 2, N_prices / 2, 1)
    ask = ask.astype(int) + np.random.binomial(1, ask - ask.astype(int))
    bid[:index - 1] = ll * np.arange(N_prices / 2, 1, -1)
    bid = bid.astype(int) + np.random.binomial(1, bid - bid.astype(int))
    #orders taken from a poisson distribution of parameter J*dt
    orders = np.reshape(np.random.poisson(current * dt, size=2 * iterations),
                        (iterations, 2))

    return rd_w_metaorders(ask, bid, iterations, orders, noise, prob,
                           return_book)
Esempio n. 6
0
class FBM2D:
    def __init__(self, H, N, L):
        """
        init of FBM2D
        
        parameters:
        H : Hurst index with 0 < H < 1
        N : number of observations along both dimensions, constructed field will contain (N x N) points
        L : number of one dimensional fbm used in construction of 2D Fields
        """
        if H <= 0 or H >= 1:
            raise ValueError("Hurst parameter must be in interval (0, 1).")
        self.H = H
        self.N = N
        self.L = L
        self.fbb_gen = FBM(
            n=int(1.5 * self.N), hurst=self.H,
            length=1.5)  #init generator for fractional Brownian motion

    def fbs(self):
        """
        returnes fractional Brownian surface (scalar fractional Brownian motion) in 2D
        """
        #generate self.L bands with equidistant angles theta between band and x-axis
        theta_i = np.linspace(0, np.pi, self.L + 1)[:-1]  #angles
        oneDfbm = np.zeros((self.L, int(1.5 * self.N) + 1))
        for i in range(self.L):
            fGn = self.fbb_gen.fgn()
            oneDfbm[i, 1:] = np.sqrt(
                np.sqrt(np.pi) * math.gamma(1 + self.H) /
                math.gamma(1 / 2 + self.H)) * np.cumsum(fGn)

        # perform turbing band algortihm in fortran
        return f.turningband2d(oneDfbm, theta_i, self.N)
Esempio n. 7
0
class FractionalBrownianMotion(BlackScholes):
    def __init__(self,
                 drift,
                 volatility,
                 hurst,
                 nb_paths,
                 nb_stocks,
                 nb_dates,
                 spot,
                 maturity,
                 dividend=0,
                 **keywords):
        super(FractionalBrownianMotion,
              self).__init__(drift, volatility, nb_paths, nb_stocks, nb_dates,
                             spot, maturity, dividend, **keywords)
        self.hurst = hurst
        self.fBM = FBM(n=nb_dates,
                       hurst=hurst,
                       length=maturity,
                       method='cholesky')
        self._nb_stocks = self.nb_stocks

    def _generate_one_path(self):
        """Returns a nparray (nb_stocks * nb_dates) with prices."""
        path = np.empty((self._nb_stocks, self.nb_dates + 1))
        for stock in range(self._nb_stocks):
            path[stock, :] = self.fBM.fbm() + self.spot
        # print("path",path)
        return path

    def generate_one_path(self):
        return self._generate_one_path()
Esempio n. 8
0
def generate_data(n_samples, sample_length, H):
    """ Generates sample fBm paths using the fbm module."""
    data = np.array([FBM(n=sample_length, hurst=H, length=1,
                         method='daviesharte').fbm() for j in range(n_samples)])
    permutation = np.random.permutation(data.shape[0])
    shuffled_data = data[permutation]
    
    return shuffled_data
Esempio n. 9
0
 def __init__(self, H, N, L):
     """
     init of FBM2D
     
     parameters:
     H : Hurst index with 0 < H < 1
     N : number of observations along both dimensions, constructed field will contain (N x N) points
     L : number of one dimensional fbm used in construction of 2D Fields
     """
     if H <= 0 or H >= 1:
         raise ValueError("Hurst parameter must be in interval (0, 1).")
     self.H = H
     self.N = N
     self.L = L
     self.fbb_gen = FBM(
         n=int(1.5 * self.N), hurst=self.H,
         length=1.5)  #init generator for fractional Brownian motion
Esempio n. 10
0
 def setUp(self):
     # For seed = 42, n = 5, H = 0.7, L = 1
     self.realizations = {
         'fbm': {
             'daviesharte':
             np.array([
                 0., 0.29326393, 0.57918201, 0.69236348, 1.17425979,
                 1.33485224
             ]),
             'cholesky':
             np.array([
                 0., 0.16100061, 0.16997488, 0.38610856, 0.92328558,
                 1.02602397
             ]),
             'hosking':
             np.array([
                 0., 0.16100061, 0.16997488, 0.38610856, 0.92328558,
                 1.02602397
             ]),
         },
         'fgn': {
             'daviesharte':
             np.array([
                 0.29326393, 0.28591808, 0.11318147, 0.48189631, 0.16059245
             ]),
             'cholesky':
             np.array([
                 0.16100061, 0.00897426, 0.21613369, 0.53717702, 0.10273839
             ]),
             'hosking':
             np.array([
                 0.16100061, 0.00897426, 0.21613369, 0.53717702, 0.10273839
             ]),
         }
     }
     self.seed = 42
     self.n = 5
     self.H = 0.7
     self.L = 1
     self.t = np.linspace(0, self.L, self.n + 1)
     self.cls_objects = {
         'daviesharte': FBM(self.n, self.H, self.L, method='daviesharte'),
         'cholesky': FBM(self.n, self.H, self.L, method='cholesky'),
         'hosking': FBM(self.n, self.H, self.L, method='hosking'),
     }
Esempio n. 11
0
def d_h_test(H=None,f=None):
    if not H:
        H = [x / 100 for x in range(1, 100)]
    fractal_d = []
    for h in H:
        if not f:
            f = FBM(n=2000, hurst=h, length=1, method='daviesharte')
        series = f.fbm()
        G = VG(series)
        #Y = nx.degree_histogram(G)
        #print(Y)
        X, Y = GC(G)
        LogXI, LogYI = [], []
        for x in X:
            LogXI.append(math.log(x))
        for y in Y:
            LogYI.append(math.log(y))
        fractal_d.append(-1 * np.polyfit(LogXI, LogYI, 1)[0])
        #print(Y)
    return fractal_d
Esempio n. 12
0
 def __init__(self,
              drift,
              volatility,
              hurst,
              nb_paths,
              nb_stocks,
              nb_dates,
              spot,
              maturity,
              dividend=0,
              **keywords):
     super(FractionalBlackScholes,
           self).__init__(drift, volatility, nb_paths, nb_stocks, nb_dates,
                          spot, maturity, dividend, **keywords)
     self.drift = drift
     self.hurst = hurst
     self.fBM = FBM(n=nb_dates,
                    hurst=self.hurst,
                    length=maturity,
                    method='hosking')
Esempio n. 13
0
 def __init__(self,
              drift,
              volatility,
              hurst,
              nb_paths,
              nb_stocks,
              nb_dates,
              spot,
              maturity,
              dividend=0,
              **keywords):
     super(FractionalBrownianMotion,
           self).__init__(drift, volatility, nb_paths, nb_stocks, nb_dates,
                          spot, maturity, dividend, **keywords)
     self.hurst = hurst
     self.fBM = FBM(n=nb_dates,
                    hurst=hurst,
                    length=maturity,
                    method='cholesky')
     self._nb_stocks = self.nb_stocks
def fOU_generator(a,n=0.3,h=0.2,length=300):
    
    fbm_increments = np.diff(FBM(length, h).fbm())
    # X(t+1) = X(t) - a(X(t)-m) + n(W(t+1)-W(t))
    x0 = np.random.normal(1,0.1)
    x0 = 0.5
    m = x0
    price = [x0]
    for i in range(length):
        p = price[i] - a*(price[i]-m) + n*fbm_increments[i]
        price.append(p)
    return np.array(price)
Esempio n. 15
0
def generate(M,
             N,
             h_x=0.8,
             h_y=0.8,
             scale=1.,
             signature=False,
             BM=False,
             dim_BM=2):

    if BM:
        X = brownian(M - 1, dim_BM, time=1.)
        Y = brownian(N - 1, dim_BM, time=1.)

    else:
        fbm_generator_X = FBM(M - 1, h_x)
        fbm_generator_Y = FBM(N - 1, h_y)

        x = scale * fbm_generator_X.fbm()
        y = scale * fbm_generator_Y.fbm()

        X = AddTime().fit_transform([x])[0]
        Y = AddTime().fit_transform([y])[0]

    if signature:
        X = iisignature.sig(X, 5, 2)
        Y = iisignature.sig(Y, 5, 2)

        X0 = np.zeros_like(X[0, :].reshape(1, -1))
        X0[0, 0] = 1.
        X = np.concatenate([X0, X])
        Y = np.concatenate([X0, Y])

    return X, Y
Esempio n. 16
0
class FractionalBlackScholes(BlackScholes):
    def __init__(self,
                 drift,
                 volatility,
                 hurst,
                 nb_paths,
                 nb_stocks,
                 nb_dates,
                 spot,
                 maturity,
                 dividend=0,
                 **keywords):
        super(FractionalBlackScholes,
              self).__init__(drift, volatility, nb_paths, nb_stocks, nb_dates,
                             spot, maturity, dividend, **keywords)
        self.drift = drift
        self.hurst = hurst
        self.fBM = FBM(n=nb_dates,
                       hurst=self.hurst,
                       length=maturity,
                       method='hosking')

    def generate_one_path(self):
        """Returns a nparray (nb_stocks * nb_dates) with prices."""
        path = np.empty((self.nb_stocks, self.nb_dates + 1))
        fracBM_noise = np.empty((self.nb_stocks, self.nb_dates))
        path[:, 0] = self.spot
        for stock in range(self.nb_stocks):
            fracBM_noise[stock, :] = self.fBM.fgn()
        for k in range(1, self.nb_dates + 1):
            previous_spots = path[:, k - 1]
            diffusion = self.diffusion_fct(previous_spots, (k) * self.dt)
            path[:, k] = (previous_spots +
                          self.drift_fct(previous_spots,
                                         (k) * self.dt) * self.dt +
                          np.multiply(diffusion, fracBM_noise[:, k - 1]))
        print("path", path)
        return path
def getPriceTrajectory(N_prices,current,iterations,dt,prob,m0,return_book,sigma):
    bid = np.zeros(N_prices)
    ask = np.zeros(N_prices)  
    ############################metaorders_initialization + fractional brownian noise 
    fbm = FBM(iterations, 0.75, iterations * dt,method="daviesharte").fgn()
    rates = np.ones(iterations)*m0*dt
    rates = np.floor(rates).astype(int) + np.random.binomial(1,rates-np.floor(rates).astype(int))
    noise = sigma*fbm 
    noise = np.floor(noise).astype(int)
    noise += np.random.binomial(1,sigma*fbm - noise)
    D = prob /(2* dt)
    ll = (current/D)  #Latent Liquidity 
    index = int((N_prices/2)+1)
    ask[index:] = ll * np.arange(index- N_prices/2, N_prices/2,1)
    ask = ask.astype(int) + np.random.binomial(1, ask - ask.astype(int))
    bid[:index-1] = ll * np.arange(N_prices/2, 1, -1)
    bid = bid.astype(int) + np.random.binomial(1, bid - bid.astype(int))
    #orders taken from a poisson distribution of parameter J*dt 
    orders = np.reshape(np.random.poisson(current*dt, size = 2 * iterations), (iterations, 2))
    ######################################computation of participation ratio of m0 wrt all the traded volume in T)
    [pt,v] = rd_w_metaorders(ask,bid,iterations,orders,noise,rates,prob,return_book)
    phi = 1./float(1+float(v/(1+sum(rates)))+float(sigma/(dt*m0))*np.mean(abs(fbm)))
    return [pt,phi]
Esempio n. 18
0
    elif mf_process == 2:
        # multifractal random walk (c_1=0.75, c_2=-0.05, N=32768)
        data_file = 'example_data/mrw07005n32768.mat'

    # Complete path to file
    current_dir = os.path.dirname(os.path.abspath(__file__))
    data_file = os.path.join(current_dir, data_file)

    #-------------------------------------------------------------------------------
    # Load data
    #-------------------------------------------------------------------------------
    data = get_data_from_mat_file(data_file)

else:
    from fbm import FBM
    f = FBM(2**15, 0.75)
    fgn_sample = f.fgn()
    fbm_sample = f.fbm()
    if mf_process == 10:
        data = fbm_sample
    if mf_process == 11:
        data = fgn_sample

from fbm import FBM
f = FBM(2**15, 0.75)
data_1 = data  #f.fbm()
f = FBM(2**15, 0.6)
data_2 = f.fbm()
#-------------------------------------------------------------------------------
# Setup analysis
#-------------------------------------------------------------------------------
Esempio n. 19
0
def HVG(series):
    '''
    function HVG(series) convert time series to horizon visibility graph
    :return:networkx graph from time series
    '''
    N = len(series)
    G = nx.Graph()
    for ta in range(N):
        ya = series[ta]
        criterion = 0
        for tb in range(ta + 1, N):
            yb = series[tb]
            if yb >= criterion:
                if ya >= criterion:
                    criterion = yb
                    G.add_edge(ta,tb)
                else:
                    break
                    #edge_list.append([ta, tb])
    return G

if __name__ == '__main__':
    f = FBM(n=1000, hurst=0.5, length=1, method='daviesharte')
    #series = [x for x in range(50)]
    series = f.fbm()
    #series = [2,4,1,5,6,3,6]
    G = HVG(series)
    pro_draw.draw_graph(G)
    #print(G.number_of_edges())

def simulate_fbm_df(d_const, n_dim, n_steps, dt, loc_std=0, hurst=0.5):
    """Simulate and output a single trajectory of fractional brownian motion in a specified number of dimensions.

    :param d_const: diffusion constant in um2/s
    :param n_dim: number of spatial dimensions for simulation (1, 2, or 3)
    :param n_steps: trajectory length (number of steps)
    :param dt: timestep size (s)
    :param loc_std: standard deviation for Gaussian localization error (um)
    :param hurst: Hurst index in range (0,1), hurst=0.5 gives brownian motion
    :return: trajectory dataframe (position in n_dim dimensions, at each timepoint)
    """

    np.random.seed()

    # create fractional brownian motion trajectory generator
    # Package ref: https://github.com/crflynn/fbm
    f = FBM(n=n_steps, hurst=hurst, length=n_steps * dt, method='daviesharte')

    # get time list and trajectory where each timestep has and n-dimensional vector step size
    t_values = f.times()
    fbm_sim = []
    for dim in range(n_dim):
        fbm_sim.append(f.fbm() * np.sqrt(2 * d_const))

    df = pd.DataFrame()
    for i in range(n_steps):

        x_curr = [fbm_sim[dim][i] for dim in range(n_dim)]
        # for initial time point, start at origin and optionally add noise
        if i == 0:
            x_obs_curr = [
                x_curr[dim] + loc_std * np.random.randn()
                for dim in range(n_dim)
            ]
        # for latter timepoints, set "current" position to position determined by displacement out of the last timepoint
        else:
            x_obs_curr = x_obs_next

        # Get next n-dimensional position
        x_next = [fbm_sim[dim][i + 1] for dim in range(n_dim)]
        # Get noise to add to next position, to get the observed position
        noise_next = [loc_std * np.random.randn() for _dim in range(n_dim)]
        x_obs_next = [x_next[dim] + noise_next[dim] for dim in range(n_dim)]
        # break current and next position into vector and magnitdue displacements
        dx_obs = [x_obs_next[dim] - x_obs_curr[dim] for dim in range(n_dim)]
        dx = [x_next[dim] - x_curr[dim] for dim in range(n_dim)]
        dr_obs = np.linalg.norm(dx_obs)
        dr = np.linalg.norm(dx)
        t = t_values[i]

        # Add timestep data to dataframe
        data = {
            't_step': t,
            'x': x_curr,
            'x_obs': x_obs_curr,
            'dx': dx,
            'dx_obs': dx_obs,
            'dr': dr,
            'dr_obs': dr_obs
        }
        df = df.append(data, ignore_index=True)

    return df
Esempio n. 21
0
nlength = 14
inclength = 40
#Load model
model = keras.models.load_model(".\\good_DLFNNmodels\\model3densediff_n" +
                                str(nlength - 1) + ".h5")
multipath = []
multiexp = []
estmultiexp = []
esttime = []

#stitch together multifractional fbm
for i in range(0, 10):
    Hsim = random.uniform(0, 1)
    randinclength = random.randrange(20) + inclength
    f = FBM(n=randinclength, hurst=Hsim, length=1, method='hosking')
    x = f.fbm()
    if i == 0:
        for p in x:
            multipath.append(p)
            multiexp.append(Hsim)
    else:
        checkpoint = multipath[-1]
        for p in x[1:]:
            multipath.append(checkpoint + p)
            multiexp.append(Hsim)

#symmetric window analysis
eitherside = int(np.floor(float(nlength) / 2.))
for i in range(eitherside, len(multipath) - eitherside):
    #for differencing
Esempio n. 22
0
 def fbm(self, n, hurst, length=1, method="daviesharte"):
     """One off sample of fBm."""
     f = FBM(n, hurst, length, method)
     return f.fbm()
Esempio n. 23
0
import matplotlib.pyplot as plt
import datetime

def calc_msd_correct(right, left):
    return (right - left) ** 2

iterations = 100

size = 5000
size1 = 20                              # how much particles we have
myarray = np.zeros((size1, size))
myarray2 = np.zeros((size1, size))
myWmsd = np.zeros((size1, size-1))
myWmsd2 = np.zeros((size1, size-1))
coeff = 0.5
f = FBM(size-1, 0.75)
f2 = FBM(size-1, 0.5)

for i in range(myarray.shape[0]):
    myarray[i] = f.fbm()
    myarray2[i] = f2.fbm()


plt.figure()
plt.plot(np.linspace(0, 1, size), myarray[0])
plt.plot(np.linspace(0, 1, size), myarray2[0])
plt.title('fBM particles')
plt.show()

print('save trajectories')
#np.savetxt()
    N_train = int(round((N_data * Test_set_proportion), 0))
    N_test = int(round((N_data * Train_step_proportion), 0))
    # Generate Unaltered Test Data
    data_x_test = np.sort(
        np.random.uniform(low=-(1 + Extrapolation_size),
                          high=(1 + Extrapolation_size),
                          size=N_test))

    data_y_test = unknown_f(data_x_test)

    # Generate Unaltered Training Data
    data_x = np.sort(np.random.uniform(low=-1, high=1, size=N_train))
    data_y = unknown_f(data_x)
else:
    # Generate Fractional Data
    FBM_Generator = FBM(n=N_data, hurst=0.75, length=1, method='daviesharte')
    data_y_outputs_full = FBM_Generator.fbm()
    data_x_outputs_full = FBM_Generator.times()
    # Partition Data
    data_x, data_x_test, data_y, data_y_test = train_test_split(
        data_x_outputs_full,
        data_y_outputs_full,
        test_size=Test_set_proportion,
        random_state=2020,
        shuffle=True)

    # Reorder Train Set
    indices_train = np.argsort(data_x)
    data_x = data_x[indices_train]
    data_y = data_y[indices_train]
from fbm import FBM
import matplotlib.pyplot as plt

f = FBM(n=100, hurst=0.9, length=1, method='daviesharte')

# Generate a fBm realization
fbm_sample = f.fbm()

# Generate a fGn realization
fgn_sample = f.fgn()

# Get the times associated with the fBm
t_values = f.times()
plt.plot(t_values, fbm_sample)
plt.show()
Esempio n. 26
0
print(tf.__version__)
from tensorflow import keras
from fbm import FBM, MBM
import numpy as np
import random

nlength = 14
#Load model
model = keras.models.load_model(".\\good_DLFNNmodels\\model3densediff_n" +
                                str(nlength - 1) + ".h5")
#generate fbm example
simulatedH = []
testH = []
for samples in range(0, 1000):
    Hsim = random.uniform(0, 1)
    f = FBM(n=nlength - 1, hurst=Hsim, length=1, method='hosking')
    x = np.transpose(pd.DataFrame(f.fbm()).values)
    xdiff = np.transpose(pd.DataFrame(f.fbm()).values[1:])
    for j in range(1, len(x)):
        xdiff[0, j - 1] = x[j] - x[j - 1]
        # /(np.amax(x)-np.amin(x))
    # print(x)
    # print(xdiff)
    exp_est = model.predict(xdiff)
    simulatedH.append(Hsim)
    testH.append(exp_est[0][0])
    print('simulated: ', Hsim, 'predicted: ', exp_est)

plt.figure()
plt.plot(simulatedH, testH, 'b.')
plt.plot([0, 1], [0, 1], 'r-')
Esempio n. 27
0
from math import exp
sigma = 0.55
phi = norm.cdf(u * T**(-H) + c2 * T**(1 - H))
phi = norm.cdf((u + c2 * T) / (sigma * T**H))
print("u=%.4f  H=%.4f" % (u, H))
print("theoretical upper bound = %.3f" %
      (1 - phi + exp(-2 * u * c2 * T**(1 - 2 * H) / sigma**2) * phi))

## =================================================================
##  分形布朗运动模拟
## =================================================================

from fbm import FBM
from tqdm import trange

f = FBM(n=1000, hurst=H, length=T, method='daviesharte')
for i in trange(实验次数, ncols=80):
    fbm_ts = f.times()
    fbm_asset = f.fbm()
    fbm_asset = [
        u + c2 * fbm_ts[i] - amp**H * fbm_asset[i]
        for i in range(len(fbm_asset))
    ]

    for i in range(len(fbm_asset)):
        if fbm_asset[i] < 0:
            fbm_ts = fbm_ts[:i + 1]
            fbm_asset = fbm_asset[:i + 1]
            break

    if fbm_asset[-1:][0] < 0:
Esempio n. 28
0
# flake8: noqa
from fbm import FBM
import matplotlib.pyplot as plt
import time
import math
import numpy as np


def h(s):
    # return 0.499*math.sin(t) + 0.5
    # return 0.6 * t + 0.3
    return 0.5 * np.exp(-8.0 * s**2)


fbm_generator = FBM(2**8, 0.85)
t = fbm_generator.times()
fbm_realization = fbm_generator.fbm()
fgn_realization = fbm_generator.fgn()
h_t = np.array(h(fbm_realization))
plt.plot(t, fbm_realization)
plt.plot(t, h_t)
# plt.plot(t[0:-1], fgn_realization)
plt.show()
Esempio n. 29
0
def generate_data(n_samples, sample_length, H):

    return np.array([
        FBM(n=sample_length, hurst=H, length=1, method='daviesharte').fbm()
        for j in range(n_samples)
    ])
Esempio n. 30
0
hurst = [0.60, 0.70, 0.80]  #[0.08, 0.10, 0.14, 0.20, 0.30, 0.40, 0.50]
hurstSimu = np.zeros(len(hurst))
v = 0.3
m = -10.0
X0 = -10.0
P0 = 100.0
alpha = 5e-4
Ndays = 2000
delta = 1.0 / 2000

output = open('simulation1.txt', 'w')
n = int(np.floor(Ndays / delta))

for i, H in enumerate(hurst):
    f = FBM(n=n, hurst=H, length=int(Ndays), method='daviesharte')
    fgn_sample = f.fgn()

    startTime = 8
    endTime = 16
    sampleFreInMinuts = 5

    #X = rfsv.simXEuler(X0, fgn_sample, v, alpha, m, delta, Ndays)
    X = rfsv.simX(X0, fgn_sample, v, alpha, m, delta, Ndays)
    sigma = np.exp(X)
    P = rfsv.simPrice(P0, sigma, delta, Ndays)
    #P = rfsv.simPriceEuler(P0, sigma, delta, Ndays)

    logP = np.log(P)
    realizedVariance = rfsv.realizedVariance(logP, delta, Ndays,
                                             sampleFreInMinuts, startTime,