forked from asavine/Scripting
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscriptingModel.h
More file actions
555 lines (468 loc) · 15.9 KB
/
scriptingModel.h
File metadata and controls
555 lines (468 loc) · 15.9 KB
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/*
Written by Antoine Savine in 2018
This code is the strict IP of Antoine Savine
License to use and alter this code for personal and commercial applications
is freely granted to any person or company who purchased a copy of the book
Modern Computational Finance: Scripting for Derivatives and XVA
Jesper Andreasen & Antoine Savine
Wiley, 2018
As long as this comment is preserved at the top of the file
*/
#pragma once
#include "scriptingProduct.h"
#include "scriptingScenarios.h"
#include "cpp11basicRanGen.h"
#include <algorithm>
#include <numeric>
// Base model for Monte-Carlo simulations
template <class T>
struct Model
{
// Clone
virtual unique_ptr<Model> clone() const = 0;
// Initialize simulation dates
virtual void initSimDates(const vector<Date>& simDates) = 0;
// Number of Gaussian numbers required for one path
virtual size_t dim() const = 0;
// Apply the model SDE
virtual void applySDE(
const vector<double>& G, // Gaussian numbers, dimension dim()
vector<T>& spots, // Populate spots for each event date
vector<T>& numeraires) // Populate numeraire for each event date
const = 0;
};
template <class T>
class SimpleBlackScholes : public Model<T>
{
Date myToday;
T mySpot;
T myRate;
T myVol;
T myDrift;
bool myTime0; // If today is among simul dates
vector<double> myTimes;
vector<double> myDt;
vector<double> mySqrtDt;
private:
// Calculate all deterministic discount factors
void calcDf( vector<T>& dfs) const
{
for (size_t i = 0; i<myTimes.size(); ++i)
dfs[i] = exp(myRate * myTimes[i]);
}
public:
// Construct with T0, S0, vol and rate
SimpleBlackScholes( const Date& today, const double spot, const double vol, const double rate)
: myToday( today), mySpot( spot), myVol( vol), myRate( rate),
myDrift(-rate+0.5*vol*vol)
{}
// Clone
virtual unique_ptr<Model<T>> clone() const override
{
return unique_ptr<Model<T>>(new SimpleBlackScholes(*this));
}
// Parameter accessors, read only
const T& spot() { return mySpot; }
const T& rate() { return myRate; }
const T& vol() { return myVol; }
// Initialize simulation dates
void initSimDates(const vector<Date>& simDates) override
{
myTime0 = simDates[0] == myToday;
// Fill array of times
for( auto dateIt = simDates.begin(); dateIt != simDates.end(); ++dateIt)
{
myTimes.push_back( double( *dateIt - myToday) / 365);
}
myDt.resize( myTimes.size());
myDt[0] = myTimes[0];
for( size_t i=1; i<myTimes.size(); ++i)
{
myDt[i] = myTimes[i] - myTimes[i-1];
}
mySqrtDt.resize( myTimes.size());
for(size_t i=0; i<myTimes.size(); ++i)
{
mySqrtDt[i] = sqrt( myDt[i]);
}
}
size_t dim() const override { return myTimes.size() - myTime0; }
// Simulate one path
// Apply the model SDE
void applySDE(
const vector<double>& G, // Gaussian numbers, dimension dim()
vector<T>& spots, // Populate spots for each event date
vector<T>& numeraires) // Populate numeraire for each event date
const override
{
// Compute discount factors
calcDf( numeraires);
// Note the ineffiency: in this case, numeraires could be computed only once
// Then apply the SDE
size_t step = 0;
// First step
spots[0] = myTime0? mySpot:
mySpot*exp(-myDrift*myDt[0]+myVol*mySqrtDt[0]*G[step++]);
// All steps
for(size_t i=1; i<myTimes.size(); ++i)
{
spots[i] = spots[i-1]
*exp(-myDrift*myDt[i]+myVol*mySqrtDt[i]*G[step++]);
}
}
};
template <class T>
class SimpleBachelier : public Model<T>
{
Date myToday;
T mySpot;
T myRate;
T myVol;
bool myTime0; // If today is among simul dates
vector<double> myTimes;
vector<double> myDt;
vector<double> mySqrtDt;
private:
// Calculate all deterministic discount factors
void calcDf(vector<T>& dfs) const
{
for (size_t i = 0; i<myTimes.size(); ++i)
dfs[i] = exp(myRate * myTimes[i]);
}
public:
// Construct with T0, S0, vol and rate
SimpleBachelier(const Date& today, const double spot, const double vol, const double rate)
: myToday(today), mySpot(spot), myVol(vol), myRate(rate)
{}
// Clone
virtual unique_ptr<Model<T>> clone() const override
{
return unique_ptr<Model<T>>(new SimpleBachelier(*this));
}
// Parameter accessors, read only
const T& spot() { return mySpot; }
const T& rate() { return myRate; }
const T& vol() { return myVol; }
// Initialize simulation dates
void initSimDates(const vector<Date>& simDates) override
{
myTime0 = simDates[0] == myToday;
// Fill array of times
for (auto dateIt = simDates.begin(); dateIt != simDates.end(); ++dateIt)
{
myTimes.push_back(double(*dateIt - myToday) / 365);
}
myDt.resize(myTimes.size());
myDt[0] = myTimes[0];
for (size_t i = 1; i<myTimes.size(); ++i)
{
myDt[i] = myTimes[i] - myTimes[i - 1];
}
mySqrtDt.resize(myTimes.size());
for (size_t i = 0; i<myTimes.size(); ++i)
{
mySqrtDt[i] = sqrt(myDt[i]);
}
}
size_t dim() const override { return myTimes.size() - myTime0; }
// Simulate one path
// Apply the model SDE
void applySDE(
const vector<double>& G, // Gaussian numbers, dimension dim()
vector<T>& spots, // Populate spots for each event date
vector<T>& numeraires) // Populate numeraire for each event date
const override
{
// Compute discount factors
calcDf(numeraires);
// Note the ineffiency: in this case, numeraires could be computed only once
// Then apply the SDE
size_t step = 0;
// If rate ~0 the dynamics is simpler and can be simulated more efficiently
if (fabs(myRate) < 0.0001)
{
// First step
spots[0] = myTime0 ? mySpot :
mySpot + myVol * mySqrtDt[0] * G[step++];
// All steps
for (size_t i = 1; i<myTimes.size(); ++i)
{
spots[i] = spots[i - 1] + myVol * mySqrtDt[i] * G[step++];
}
}
// General dynamics with non-zero rates
else
{
// First step
spots[0] = myTime0 ? mySpot :
mySpot * exp(myRate * myDt[0]) + myVol * sqrt ((exp (2 * myRate * myDt[0]) - 1) / (2 * myRate)) * G[step++];
// All steps
for (size_t i = 1; i<myTimes.size(); ++i)
{
spots[i] = spots[i - 1] * exp(myRate * myDt[i]) + myVol * sqrt((exp(2 * myRate * myDt[i]) - 1) / (2 * myRate)) * G[step++];
}
}
}
};
template <class T>
class MonteCarloSimulator
{
RandomGen& myRandomGen;
Model<T>& myModel;
public:
MonteCarloSimulator( Model<T>& model, RandomGen& ranGen) : myRandomGen( ranGen), myModel( model) {}
void init( const vector<Date>& simDates)
{
myModel.initSimDates( simDates);
myRandomGen.init( myModel.dim());
}
void simulateOnePath( vector<T>& spots, vector<T>& numeraires)
{
myRandomGen.genNextNormVec();
myModel.applySDE(myRandomGen.getNorm(), spots, numeraires);
}
};
// Model interface for communication with script
template <class T>
struct ScriptModelApi
{
virtual void initForScripting(const vector<Date>& eventDates) = 0;
virtual void nextScenario(Scenario<T>& s) = 0;
};
template <class T>
class ScriptSimulator : public MonteCarloSimulator<T>, public ScriptModelApi<T>
{
vector<T> myTempSpots;
vector<T> myTempNumeraires;
public:
ScriptSimulator( Model<T>& model, RandomGen& ranGen) : MonteCarloSimulator<T>( model, ranGen) {}
void initForScripting( const vector<Date>& eventDates) override
{
MonteCarloSimulator<T>::init( eventDates);
myTempSpots.resize( eventDates.size());
myTempNumeraires.resize(eventDates.size());
}
void nextScenario( Scenario<T>& s) override
{
MonteCarloSimulator<T>::simulateOnePath( myTempSpots, myTempNumeraires);
// Note the inefficiency
for(size_t i=0; i<s.size(); ++i)
{
s[i].spot = myTempSpots[i];
s[i].numeraire = myTempNumeraires[i];
}
}
};
inline void simpleBsScriptVal(
const Date& today,
const double spot,
const double vol,
const double rate,
const bool normal, // true = normal, false = lognormal
const map<Date,string>& events,
const unsigned numSim,
const unsigned seed, // 0 = default
// Fuzzy
const bool fuzzy, // Use sharp (false) or fuzzy (true) eval
const double defEps, // Default epsilon, may be redefined by node
const bool skipDoms, // Skip domains (unless fuzzy)
// Compile?
const bool compile,
// Results
vector<string>& varNames,
vector<double>& varVals)
{
if( events.begin()->first < today)
throw runtime_error("Events in the past are disallowed");
// Initialize product
Product prd;
prd.parseEvents( events.begin(), events.end());
size_t maxNestedIfs = prd.preProcess( fuzzy, skipDoms);
// Build scenarios
unique_ptr<Scenario<double>> scen = prd.buildScenario<double>();
// Initialize model and random generator
BasicRanGen random(seed);
unique_ptr<Model<double>> model;
if (normal) model.reset(new SimpleBachelier<double>(today, spot, vol, rate));
else model.reset(new SimpleBlackScholes<double>(today, spot, vol, rate));
// Initialize simulator
ScriptSimulator<double> simulator(*model, random);
simulator.initForScripting(prd.eventDates());
// Initialize results
varNames = prd.varNames();
varVals.resize(varNames.size(), 0.0);
// Compiled - not implemented (yet) for fuzzy
if (compile)
{
EvalState<double> state(prd.varNames().size());
prd.compile();
// Loop over simulations
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.nextScenario(*scen);
// Evaluate product
prd.evaluateCompiled(*scen, state);
// Update results
const size_t n = varVals.size();
for (size_t v = 0; v<n; ++v)
{
varVals[v] += state.variables[v];
}
}
}
// Fuzzy
else if (fuzzy)
{
FuzzyEvaluator<double> eval = prd.buildFuzzyEvaluator<double>(maxNestedIfs, defEps);
// Loop over simulations
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.nextScenario(*scen);
// Evaluate product
prd.evaluate(*scen, eval);
// Update results
const size_t n = varVals.size();
for (size_t v = 0; v<n; ++v)
{
varVals[v] += eval.varVals()[v];
}
}
}
// Evaluator
else
{
Evaluator<double> eval = prd.buildEvaluator<double>();
// Loop over simulations
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.nextScenario(*scen);
// Evaluate product
prd.evaluate(*scen, eval);
// Update results
const size_t n = varVals.size();
for (size_t v = 0; v<n; ++v)
{
varVals[v] += eval.varVals()[v];
}
}
}
for (auto& v : varVals) v /= numSim;
}
// Hard coded barrier
inline void simpleBsBarVal(
const Date& today,
const double spot,
const double vol,
const double rate,
const bool normal, // true = normal, false = lognormal
const Date mat,
const vector<Date>& barDates,
const double strike,
const double bar,
const unsigned numSim,
const unsigned seed, // 0 = default
double& val)
{
// Initialize model and random generator
BasicRanGen random(seed);
unique_ptr<Model<double>> model;
if (normal) model.reset(new SimpleBachelier<double>(today, spot, vol, rate));
else model.reset(new SimpleBlackScholes<double>(today, spot, vol, rate));
// Initialize simulator
MonteCarloSimulator<double> simulator(*model, random);
vector<Date> eventDates = barDates;
size_t lastBar = eventDates.size();
if (mat > barDates.back()) eventDates.push_back(mat);
vector<double> spots(eventDates.size()), numeraires(eventDates.size());
simulator.init(eventDates);
// Loop over simulations
double res = 0.0;
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.simulateOnePath(spots, numeraires);
// Evaluate barrier
bool breached = false;
for (size_t i = 0; i < lastBar; ++i)
{
if (spots[i] > bar)
{
breached = true;
break;
}
}
if (!breached && spots.back() > strike) res += (spots.back() - strike) / numeraires.back();
}
val = res / numSim;
}
// Hard coded asian
inline void simpleBsAsianVal(
const Date& today,
const double spot,
const double vol,
const double rate,
const bool normal, // true = normal, false = lognormal
const vector<Date>& asDates,
const unsigned numSim,
const unsigned seed, // 0 = default
double& val)
{
// Initialize model and random generator
BasicRanGen random(seed);
unique_ptr<Model<double>> model;
if (normal) model.reset(new SimpleBachelier<double>(today, spot, vol, rate));
else model.reset(new SimpleBlackScholes<double>(today, spot, vol, rate));
// Initialize simulator
MonteCarloSimulator<double> simulator(*model, random);
vector<double> spots(asDates.size()), numeraires(asDates.size());
simulator.init(asDates);
// Loop over simulations
double res = 0.0;
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.simulateOnePath(spots, numeraires);
// Evaluate asian
const double ave = accumulate(spots.begin(), spots.end(), 0.0) / spots.size();
if (spots.back() > ave) res += (spots.back() - ave) / numeraires.back();
}
val = res / numSim;
}
// Hard coded asian
inline void simpleBsCallsVal(
const Date& today,
const double spot,
const double vol,
const double rate,
const bool normal, // true = normal, false = lognormal
const Date mat,
const vector<double>& strikes,
const unsigned numSim,
const unsigned seed, // 0 = default
vector<double>& vals)
{
// Initialize model and random generator
BasicRanGen random(seed);
unique_ptr<Model<double>> model;
if (normal) model.reset(new SimpleBachelier<double>(today, spot, vol, rate));
else model.reset(new SimpleBlackScholes<double>(today, spot, vol, rate));
// Initialize simulator
MonteCarloSimulator<double> simulator(*model, random);
vector<double> spots(1), numeraires(1);
simulator.init(vector<Date>{mat});
// Loop over simulations
const size_t nk = strikes.size();
vals.resize(nk, 0);
for (size_t i = 0; i<numSim; ++i)
{
// Generate next scenario into scen
simulator.simulateOnePath(spots, numeraires);
const double s = spots[0], num = numeraires[0];
// Evaluate calls
for (size_t j = 0; j < nk; ++j) if (s > strikes[j]) vals[j] += (s - strikes[j]) / num;
}
for (auto& val: vals) val /= numSim;
}