-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathtest.py
148 lines (126 loc) · 4.07 KB
/
test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# "High-frequency trading in a limit order book"
# by Marco Avellaneda and Sasha Stoikov"
# https://math.nyu.edu/faculty/avellane/HighFrequencyTrading.pdf
# https://quant.stackexchange.com/questions/36400/avellaneda-stoikov-market-making-model
import math
import numpy as np
import matplotlib.pyplot as plt
import random
import time
while True:
# Parameters for mid price simulation:
S0 = 100. # initial price
T = 1.0 # time
sigma = 2 # volatility
M = 20000 # number of time steps
dt = T/M # time step
Sim = 1000 # number of simulations
gamma = 0.1 # risk aversion
k = 1.5 #
A = 140 # order probability
I = 1 # stocks
M_float = float(M)
sqrt_dt = math.sqrt(dt)
# Results:
AverageSpread = []
Profit = []
Std = []
for i in range(1, Sim+1):
# reservation price:
# r(s,t) = s - q * gamma * sigma**2 * (T-t)
S = np.zeros((M+1, I))
Bid = np.zeros((M+1, I))
Ask = np.zeros((M+1, I))
ReservPrice = np.zeros((M+1, I))
spread = np.zeros((M+1, I))
deltaB = np.zeros((M+1, I))
deltaA = np.zeros((M+1, I))
q = np.zeros((M+1, I))
w = np.zeros((M+1, I))
equity = np.zeros((M+1, I))
S[0] = S0
ReservPrice[0] = S0
Bid[0] = S0
Ask[0] = S0
spread[0] = 0
deltaB[0] = 0
deltaA[0] = 0
q[0] = 0 # position
w[0] = 0 # wealth
equity[0] = 0
for t in range(1, M+1):
z = np.random.standard_normal(I) # dW
S[t] = S[t-1] + sigma * sqrt_dt * z # new S value
ReservPrice[t] = S[t] - q[t-1] * gamma * (sigma ** 2) * (T - t/M_float) # Mid Price estimation
spread[t] = gamma * (sigma ** 2) * (T - t/M_float) + (2/gamma) * math.log(1 + (gamma/k)) # Spread estimation
Bid[t] = ReservPrice[t] - spread[t]/2. # bid
Ask[t] = ReservPrice[t] + spread[t]/2. # ask
deltaB[t] = S[t] - Bid[t] # difference to price
deltaA[t] = Ask[t] - S[t] # difference to price
lambdaA = A * np.exp(-k * deltaA[t])
ProbA = 1 - np.exp(-lambdaA * dt)
fa = random.random()
lambdaB = A * np.exp(-k * deltaB[t])
ProbB = 1 - np.exp(-lambdaB * dt)
fb = random.random()
if ProbB > fb and ProbA < fa: # buy market order filling our limit order
q[t] = q[t-1] + 1 # position
w[t] = w[t-1] - Bid[t] # wealth
if ProbB < fb and ProbA > fa: # sell market order filling our limit order
q[t] = q[t-1] - 1 # position
w[t] = w[t-1] + Ask[t] # wealth
if ProbB < fb and ProbA < fa: # no order
q[t] = q[t-1] # position
w[t] = w[t-1] # wealth
if ProbB > fb and ProbA > fa: # both sides order
q[t] = q[t-1] # position
w[t] = w[t-1] - Bid[t] # wealth
w[t] = w[t] + Ask[t]
equity[t] = w[t] + q[t] * S[t]
AverageSpread.append(spread.mean())
Profit.append(equity[-1])
Std.append(np.std(equity))
print(" Results ")
print("----------------------------------------")
print("%14s %21s" % ('statistic', 'value'))
print(40 * "-")
print("%14s %20.5f" % ("Average spread :", np.array(AverageSpread).mean()))
print("%16s %20.5f" % ("Profit :", np.array(Profit).mean()))
print("%16s %20.5f" % ("Std(Profit) :", np.array(Std).mean()))
# Plots:
x = np.linspace(0., T, num=(M+1))
fig = plt.figure(figsize=(10, 8))
plt.subplot(2, 2, 1) # number of rows, number of columns, number of the subplot
plt.plot(x, S[:], lw=1., label='S')
plt.plot(x, Ask[:], lw=1., label='Ask')
plt.plot(x, Bid[:], lw=1., label='Bid')
plt.grid(True)
plt.legend(loc=0)
plt.ylabel('P')
plt.title('Prices')
plt.subplot(2, 2, 2)
plt.plot(x, q[:], 'g', lw=1., label='q') # plot 2 lines
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Time')
plt.ylabel('Position')
#plt.show()
plt.subplot(2, 2, 4)
plt.plot(x, equity[:], 'b', lw=1., label='equity')
plt.grid(True)
plt.legend(loc=0)
plt.axis('tight')
plt.xlabel('Time')
plt.ylabel('Position')
# Histogram of profit:
#plt.figure(figsize=(7, 5))
plt.subplot(2, 2, 3)
plt.hist(np.array(Profit), label=['Inventory strategy'], bins=100)
plt.legend(loc=0)
plt.grid(True)
plt.xlabel('pnl')
plt.ylabel('number of values')
plt.title('Histogram')
plt.show()
time.sleep(1)