forked from alialaradi/DeepGalerkinMethod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MertonProblem.py
422 lines (307 loc) · 14.1 KB
/
MertonProblem.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# SCRIPT FOR SOLVING THE MERTON PROBLEM
#%% import needed packages
import DGM
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#%% Parameters
# Merton problem parameters
r = 0.05 # risk-free rate
mu = 0.2 # asset drift
sigma = 0.25 # asset volatility
gamma = 1 # exponential utility preference parameter
T = 1 # terminal time (investment horizon)
# Solution parameters (domain on which to solve PDE)
t_low = 0 + 1e-10 # time lower bound
X_low = 0.0 + 1e-10 # wealth lower bound
X_high = 1 # wealth upper bound
# neural network parameters
num_layers = 3
nodes_per_layer = 50
starting_learning_rate = 0.001
# Training parameters
sampling_stages = 500 # number of times to resample new time-space domain points
steps_per_sample = 10 # number of SGD steps to take before re-sampling
# Sampling parameters
nSim_interior = 1000
nSim_terminal = 100
# multipliers for oversampling i.e. draw X from [X_low - X_oversample, X_high + X_oversample]
X_oversample = 0.5
t_oversample = 0.5
# Plot options
n_plot = 41 # Points on plot grid for each dimension
# Save options
saveOutput = False
saveName = 'MertonProblem'
saveFigure = False
figureName = 'MertonProblem'
#%% Analytical Solution
# market price of risk
theta = (mu - r)/sigma
def exponential_utility(x):
''' Compute exponential utility for given level of wealth
Args:
x: wealth
'''
return -tf.exp(-gamma*x)
def value_function_analytical_solution(t,x):
''' Compute the value function for the Merton problem
Args:
t: time points
x: space (wealth) points
'''
return -np.exp(-x*gamma*np.exp(r*(T - t)) - (T - t)*0.5*theta**2)
def optimal_control_analytical_solution(t,x):
''' Compute the optimal control for the Merton problem
Args:
t: time points
x: space (wealth) points
'''
return theta/(gamma*sigma) * np.exp(-r*(T - t))
#%% Sampling function - randomly sample time-space pairs
def sampler(nSim_interior, nSim_terminal):
''' Sample time-space points from the function's domain; points are sampled
uniformly on the interior of the domain, at the initial/terminal time points
and along the spatial boundary at different time points.
Args:
nSim_interior: number of space points in the interior of the function's domain to sample
nSim_terminal: number of space points at terminal time to sample (terminal condition)
'''
# Sampler #1: domain interior
t_interior = np.random.uniform(low=t_low - 0.5*(T-t_low), high=T, size=[nSim_interior, 1])
# t_interior = np.random.uniform(low=t_low - t_oversample, high=T, size=[nSim_interior, 1])
X_interior = np.random.uniform(low=X_low - 0.5*(X_high-X_low), high=X_high + 0.5*(X_high-X_low), size=[nSim_interior, 1])
# X_interior = np.random.uniform(low=X_low - X_oversample, high=X_high + X_oversample, size=[nSim_interior, 1])
# X_interior = np.random.uniform(low=X_low * X_multiplier_low, high=X_high * X_multiplier_high, size=[nSim_interior, 1])
# Sampler #2: spatial boundary
# no spatial boundary condition for this problem
# Sampler #3: initial/terminal condition
t_terminal = T * np.ones((nSim_terminal, 1))
# X_terminal = np.random.uniform(low=X_low - X_oversample, high=X_high + X_oversample, size = [nSim_terminal, 1])
X_terminal = np.random.uniform(low=X_low - 0.5*(X_high-X_low), high=X_high + 0.5*(X_high-X_low), size = [nSim_terminal, 1])
# X_terminal = np.random.uniform(low=X_low * X_multiplier_low, high=X_high * X_multiplier_high, size = [nSim_terminal, 1])
return t_interior, X_interior, t_terminal, X_terminal
#%% Loss function for Merton Problem PDE
def loss(model, t_interior, X_interior, t_terminal, X_terminal):
''' Compute total loss for training.
Args:
model: DGM model object
t_interior: sampled time points in the interior of the function's domain
X_interior: sampled space points in the interior of the function's domain
t_terminal: sampled time points at terminal point (vector of terminal times)
X_terminal: sampled space points at terminal time
'''
# Loss term #1: PDE
# compute function value and derivatives at current sampled points
V = model(t_interior, X_interior)
V_t = tf.gradients(V, t_interior)[0]
V_x = tf.gradients(V, X_interior)[0]
V_xx = tf.gradients(V_x, X_interior)[0]
diff_V = -0.5 * theta**2 * V_x**2 + (V_t + r*X_interior*V_x)*V_xx
# compute average L2-norm of differential operator
L1 = tf.reduce_mean(tf.square(diff_V))
# Loss term #2: boundary condition
# no boundary condition for this problem
# Loss term #3: initial/terminal condition
target_terminal = exponential_utility(X_terminal)
fitted_terminal = model(t_terminal, X_terminal)
L3 = tf.reduce_mean( tf.square(fitted_terminal - target_terminal) )
return L1, L3
#%% Set up network
# initialize DGM model (last input: space dimension = 1)
model = DGM.DGMNet(nodes_per_layer, num_layers, 1)
# tensor placeholders (_tnsr suffix indicates tensors)
# inputs (time, space domain interior, space domain at initial time)
t_interior_tnsr = tf.placeholder(tf.float32, [None,1])
X_interior_tnsr = tf.placeholder(tf.float32, [None,1])
t_terminal_tnsr = tf.placeholder(tf.float32, [None,1])
X_terminal_tnsr = tf.placeholder(tf.float32, [None,1])
# loss
L1_tnsr, L3_tnsr = loss(model, t_interior_tnsr, X_interior_tnsr, t_terminal_tnsr, X_terminal_tnsr)
loss_tnsr = L1_tnsr + L3_tnsr
# value function
V = model(t_interior_tnsr, X_interior_tnsr)
# optimal control computed numerically from fitted value function
def compute_fitted_optimal_control(V):
V_x = tf.gradients(V, X_interior_tnsr)[0]
V_xx = tf.gradients(V_x, X_interior_tnsr)[0]
return -(theta/(gamma*sigma))*V_x/(V_xx)
numerical_optimal_control = compute_fitted_optimal_control(V)
# set optimizer - NOTE THIS IS DIFFERENT FROM OTHER APPLICATIONS!
global_step = tf.Variable(0, trainable=False)
learning_rate = tf.train.exponential_decay(starting_learning_rate, global_step,100000, 0.96, staircase=True)
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss_tnsr)
# initialize variables
init_op = tf.global_variables_initializer()
# open session
sess = tf.Session()
sess.run(init_op)
#%% Train network
# initialize loss per training
loss_list = []
# for each sampling stage
for i in range(sampling_stages):
# sample uniformly from the required regions
t_interior, X_interior, t_terminal, X_terminal = sampler(nSim_interior, nSim_terminal)
# for a given sample, take the required number of SGD steps
for _ in range(steps_per_sample):
loss,L1,L3,_ = sess.run([loss_tnsr, L1_tnsr, L3_tnsr, optimizer],
feed_dict = {t_interior_tnsr:t_interior, X_interior_tnsr:X_interior, t_terminal_tnsr:t_terminal, X_terminal_tnsr:X_terminal})
loss_list.append(loss)
print(loss, L1, L3, i)
# save outout
if saveOutput:
saver = tf.train.Saver()
saver.save(sess, './SavedNets/' + saveName)
#%% Plot value function results
# LaTeX rendering for text in plots
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
# figure options
plt.figure()
plt.figure(figsize = (12,10))
# time values at which to examine density
valueTimes = [t_low, T/3, 2*T/3, T]
# vector of t and S values for plotting
X_plot = np.linspace(X_low, X_high, n_plot)
for i, curr_t in enumerate(valueTimes):
# specify subplot
plt.subplot(2,2,i+1)
# simulate process at current t
optionValue = value_function_analytical_solution(curr_t, X_plot)
# compute normalized density at all x values to plot and current t value
t_plot = curr_t * np.ones_like(X_plot.reshape(-1,1))
fitted_optionValue = sess.run([V], feed_dict= {t_interior_tnsr:t_plot, X_interior_tnsr:X_plot.reshape(-1,1)})
# plot histogram of simulated process values and overlay estimated density
plt.plot(X_plot, optionValue, color = 'b', label='Analytical Solution', linewidth = 3, linestyle=':')
plt.plot(X_plot, fitted_optionValue[0], color = 'r', label='DGM estimate')
# subplot options
plt.xlim(xmin=0.0, xmax=X_high)
plt.xlabel(r"Wealth", fontsize=15, labelpad=10)
plt.ylabel(r"Value Function", fontsize=15, labelpad=20)
plt.title(r"\boldmath{$t$}\textbf{ = %.2f}"%(curr_t), fontsize=18, y=1.03)
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
plt.grid(linestyle=':')
if i == 0:
plt.legend(loc='upper left', prop={'size': 16})
# adjust space between subplots
plt.subplots_adjust(wspace=0.3, hspace=0.4)
if saveFigure:
plt.savefig(figureName + '_valueFunction.png')
#%% Plot optimal control results
# figure options
plt.figure()
plt.figure(figsize = (12,10))
# time values at which to examine density
valueTimes = [t_low, T/3, 2*T/3, T]
# vector of t and S values for plotting
X_plot = np.linspace(X_low, X_high, n_plot)
for i, curr_t in enumerate(valueTimes):
# specify subplot
plt.subplot(2,2,i+1)
# simulate process at current t
optimal_control = optimal_control_analytical_solution(t_plot,X_plot)
# compute normalized density at all x values to plot and current t value
t_plot = curr_t * np.ones_like(X_plot.reshape(-1,1))
fitted_optimal_control = sess.run([numerical_optimal_control],feed_dict={t_interior_tnsr:t_plot, X_interior_tnsr:X_plot.reshape(-1,1)})
# plot histogram of simulated process values and overlay estimated density
plt.plot(X_plot, optimal_control, color = 'b', label='Analytical Solution', linewidth = 3, linestyle=':')
plt.plot(X_plot, fitted_optimal_control[0], color = 'r', label='DGM estimate')
# subplot options
plt.xlim(xmin=0.0, xmax=X_high)
plt.ylim(ymin=2.0, ymax=3.5)
plt.xlabel(r"Wealth", fontsize=15, labelpad=10)
plt.ylabel(r"Value Function", fontsize=15, labelpad=20)
plt.title(r"\boldmath{$t$}\textbf{ = %.2f}"%(curr_t), fontsize=18, y=1.03)
plt.xticks(fontsize=13)
plt.yticks(fontsize=13)
plt.grid(linestyle=':')
if i == 0:
plt.legend(loc='upper left', prop={'size': 16})
# adjust space between subplots
plt.subplots_adjust(wspace=0.3, hspace=0.4)
if saveFigure:
plt.savefig(figureName + '_optimalControl.png')
#%% Error heatmaps - value function
# vector of t and X values for plotting
X_plot = np.linspace(X_low, X_high, n_plot)
t_plot = np.linspace(t_low, T, n_plot)
# compute value function for each (t,X) pair
value_function_mesh = np.zeros([n_plot, n_plot])
for i in range(n_plot):
for j in range(n_plot):
value_function_mesh[j,i] = value_function_analytical_solution(t_plot[i], X_plot[j])
# compute model-implied value function for each (t,X) pair
t_mesh, X_mesh = np.meshgrid(t_plot, X_plot)
t_plot = np.reshape(t_mesh, [n_plot**2,1])
X_plot = np.reshape(X_mesh, [n_plot**2,1])
fitted_value_function = sess.run([V], feed_dict= {t_interior_tnsr:t_plot, X_interior_tnsr:X_plot})
fitted_value_function_mesh = np.reshape(fitted_value_function, [n_plot, n_plot])
# PLOT ABSOLUTE ERROR
plt.figure()
plt.figure(figsize = (8,6))
plt.pcolormesh(t_mesh, X_mesh, np.abs(value_function_mesh - fitted_value_function_mesh), cmap = "rainbow")
# plot options
plt.colorbar()
plt.title("Absolute Error", fontsize=20)
plt.ylabel("Wealth", fontsize=15, labelpad=10)
plt.xlabel("Time", fontsize=15, labelpad=20)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if saveFigure:
plt.savefig(figureName + '_valueFunction_absErr.png')
# PLOT RELATIVE ERROR
plt.figure()
plt.figure(figsize = (8,6))
plt.pcolormesh(t_mesh, X_mesh, np.abs(1 - np.divide(fitted_value_function_mesh, value_function_mesh)), cmap = "rainbow")
# plot options
plt.colorbar()
plt.title("Relative Error", fontsize=20)
plt.ylabel("Wealth", fontsize=15, labelpad=10)
plt.xlabel("Time", fontsize=15, labelpad=20)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if saveFigure:
plt.savefig(figureName + '_valueFunction_relErr.png')
#%% Error heatmaps - optimal control
# vector of t and X values for plotting
X_plot = np.linspace(X_low, X_high, n_plot)
t_plot = np.linspace(t_low, T, n_plot)
# compute optimal control for each (t,X) pair
optimal_control_mesh = np.zeros([n_plot, n_plot])
for i in range(n_plot):
for j in range(n_plot):
optimal_control_mesh[j,i] = optimal_control_analytical_solution(t_plot[i], X_plot[j])
# compute model-implied optimal control for each (t,X) pair
t_mesh, X_mesh = np.meshgrid(t_plot, X_plot)
t_plot = np.reshape(t_mesh, [n_plot**2,1])
X_plot = np.reshape(X_mesh, [n_plot**2,1])
fitted_optimal_control = sess.run([numerical_optimal_control], feed_dict= {t_interior_tnsr:t_plot, X_interior_tnsr:X_plot})
fitted_optimal_control_mesh = np.reshape(fitted_optimal_control, [n_plot, n_plot])
# PLOT ABSOLUTE ERROR
plt.figure()
plt.figure(figsize = (8,6))
plt.pcolormesh(t_mesh, X_mesh, np.abs(optimal_control_mesh - fitted_optimal_control_mesh), cmap = "rainbow")
# plot options
plt.colorbar()
plt.title("Absolute Error", fontsize=20)
plt.ylabel("Wealth", fontsize=15, labelpad=10)
plt.xlabel("Time", fontsize=15, labelpad=20)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if saveFigure:
plt.savefig(figureName + '_optimalControl_absErr.png')
# PLOT RELATIVE ERROR
plt.figure()
plt.figure(figsize = (8,6))
plt.pcolormesh(t_mesh, X_mesh, np.abs(1 - np.divide(fitted_optimal_control_mesh, optimal_control_mesh)), cmap = "rainbow")
# plot options
plt.colorbar()
plt.title("Relative Error", fontsize=20)
plt.ylabel("Wealth", fontsize=15, labelpad=10)
plt.xlabel("Time", fontsize=15, labelpad=20)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if saveFigure:
plt.savefig(figureName + '_optimalControl_relErr.png')