import numpy as np
import pandas as pd
ber=[-1,1] # either -1 or 1
n=20 # number of simulation, <=> number of experiment
t=10 # number of coin toss each in experiment
Increments=np.random.choice(ber,size=(n,t))
Increments
array([[ 1, 1, 1, 1, 1, 1, 1, -1, -1, 1], [ 1, 1, 1, -1, 1, -1, 1, 1, -1, 1], [ 1, 1, -1, -1, 1, -1, 1, 1, -1, 1], [ 1, -1, 1, 1, -1, -1, 1, 1, -1, -1], [-1, -1, -1, -1, 1, -1, 1, -1, 1, 1], [-1, -1, 1, -1, 1, 1, -1, -1, 1, 1], [ 1, -1, 1, -1, 1, 1, -1, -1, -1, -1], [ 1, -1, -1, 1, -1, 1, 1, 1, 1, 1], [ 1, -1, -1, -1, 1, -1, 1, 1, 1, 1], [ 1, 1, 1, 1, -1, 1, 1, 1, -1, -1], [ 1, -1, 1, -1, -1, -1, -1, 1, -1, 1], [ 1, 1, 1, -1, -1, 1, 1, 1, 1, 1], [ 1, -1, -1, -1, -1, -1, -1, 1, 1, -1], [ 1, -1, -1, 1, -1, 1, 1, 1, 1, -1], [-1, -1, -1, 1, -1, 1, -1, -1, 1, 1], [-1, 1, 1, -1, 1, -1, 1, 1, -1, 1], [-1, 1, -1, -1, -1, 1, -1, 1, 1, 1], [-1, 1, -1, 1, -1, 1, 1, 1, -1, 1], [ 1, -1, 1, -1, 1, 1, 1, -1, -1, -1], [-1, 1, -1, -1, -1, -1, -1, 1, -1, 1]])
Price_S=Increments.cumsum(axis=1)
Price_S
array([[ 1, 2, 3, 4, 5, 6, 7, 6, 5, 6], [ 1, 2, 3, 2, 3, 2, 3, 4, 3, 4], [ 1, 2, 1, 0, 1, 0, 1, 2, 1, 2], [ 1, 0, 1, 2, 1, 0, 1, 2, 1, 0], [-1, -2, -3, -4, -3, -4, -3, -4, -3, -2], [-1, -2, -1, -2, -1, 0, -1, -2, -1, 0], [ 1, 0, 1, 0, 1, 2, 1, 0, -1, -2], [ 1, 0, -1, 0, -1, 0, 1, 2, 3, 4], [ 1, 0, -1, -2, -1, -2, -1, 0, 1, 2], [ 1, 2, 3, 4, 3, 4, 5, 6, 5, 4], [ 1, 0, 1, 0, -1, -2, -3, -2, -3, -2], [ 1, 2, 3, 2, 1, 2, 3, 4, 5, 6], [ 1, 0, -1, -2, -3, -4, -5, -4, -3, -4], [ 1, 0, -1, 0, -1, 0, 1, 2, 3, 2], [-1, -2, -3, -2, -3, -2, -3, -4, -3, -2], [-1, 0, 1, 0, 1, 0, 1, 2, 1, 2], [-1, 0, -1, -2, -3, -2, -3, -2, -1, 0], [-1, 0, -1, 0, -1, 0, 1, 2, 1, 2], [ 1, 0, 1, 0, 1, 2, 3, 2, 1, 0], [-1, 0, -1, -2, -3, -4, -5, -4, -5, -4]])
Price_S_0=np.concatenate( [np.zeros([n,1]),Price_S] , axis=1) # add a 0 columnm, make the figure starting from 0
pd.DataFrame(Price_S_0.T).plot() # plot treat each vector as a set of values, so tranpose the whole matrix. 20 collumn means 20 simulations
<AxesSubplot:>
np.square(Increments).sum(axis=1) # see results below, each experiment has value = t (=10)
array([10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
np.mean(Increments,axis=1) # approx = 0
array([ 0.6, 0.4, 0.2, 0. , -0.2, 0. , -0.2, 0.4, 0.2, 0.4, -0.2, 0.6, -0.4, 0.2, -0.2, 0.2, 0. , 0.2, 0. , -0.4])
np.var(Increments,axis=1) # approx = 1
array([0.64, 0.84, 0.96, 1. , 0.96, 1. , 0.96, 0.84, 0.96, 0.84, 0.96, 0.64, 0.84, 0.96, 0.96, 0.96, 1. , 0.96, 1. , 0.84])
by Fanyu Zhao