forked from CamDavidsonPilon/PyProcess
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpyprocess.py
More file actions
Latest commit
1764 lines (1428 loc) · 62.5 KB
/
Copy pathpyprocess.py
File metadata and controls
1764 lines (1428 loc) · 62.5 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on 2011-07-29
@author: Cameron Davidson-Pilon
Feel free to use this under the MIT license.
'''
"""
The second iteration of stochastic processes.
"""
importscipy.statsasstats
fromscipy.specialimport*
frommathimport*
importrandom
classStep_process(object):
"""
This is the class of finite activity jump/event processes (eg poisson process, renewel process etc). For this library, I will use
the terms "jump" and "event" interchangeably.
"""
def__init__(self, dict):
"'dict' contains the time and space constraints"
try:
self.startTime=dict["startTime"]
self.startPosition=dict["startPosition"]
self.conditional=False
ifdict.has_key("endTime") ordict.has_key("endPosition"):
self.endTime=dict["endTime"]
self.endPosition=dict["endPosition"]
self.conditional=True
exceptKeyError:
print"Missing constraint in initial\end value dictionary. Check spelling?"
def_check_time(self,t):
ift<self.startTime:
print"Attn: inputted time not valid (check if beginning time is less than startTime)."
defgenerate_sample_path(self,times):
self._check_time(times[0])
returnself._generate_sample_path(times)
defgenerate_sample_jumps(self,T):
self._check_time(T)
returnself._generate_sample_jumps(T)
defget_mean_at(self,t):
self._check_time(t)
returnself._get_mean_at(t)
defget_variance_at(self,t):
self._check_time(t)
returnself._get_variance_at(t)
defget_mean_number_of_jumps(self,t):
self._check_time(t)
returnself._get_mean_number_of_jumps(t)
defgenerate_position_at(self,t):
self._check_time(t)
returnself._generate_position_at(t)
def_get_mean_number_of_jumps(self,t):
self._check_time(t)
#need a proper stopping criterion
print"Attn: performing MC simulation"
N=10000
sum=0.0
foriinrange(N):
n=0
sum_t=self.T.rvs()
whilesum_t<t:
n+=1
sum_t+=self.T.rvs()
sum+=n
returnsum/N
classRenewal_process(Step_process):
"""
Note that user-inputed endTime and endPosition will not be satisfied.
parameters:
{T:see below, J:see below}
T is a scipy "frozen" random variable object, from the scipy.stats library, that has the same distribution as the inter-arrival times
i.e. t_{i+1} - t_{i} equal in distribution to T, where t_i are jump/event times.
T must be a non-negative random variable, possibly constant. The constant case in included in this library, see the Constant class in the auxillary
functions and class at the bottom.
J is a scipy "frozen" random variable object that has the same distribution as the jump distribution. It can have any real support. Ex: for the poisson process,
J is equal to 1 with probability 1, but for the compound poisson process J is distributed as a non-constant.
Ex:
import scipy.stats as stats
#create a standard renewal process
timespace_constraints = {"startTime": 0, "startPosition": 10 }
parameters = {"J":Constant(3.5), "T":stats.poisson(lambda=1)}}
RnwlPs= Renewal_process(parameters, timespace_constraints)
"""
def__init__(self, parameters, time_space_constraints):
super(Renewal_process, self).__init__(time_space_constraints)
self.T=parameters["T"]
self.J=parameters["J"]
self.renewal_rate=1/self.T.mean()
defforward_recurrence_time_pdf(self,x):
"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time"
returnself.renewal_rate*self.T.sf(x)
defbackwards_recurrence_time_pdf(self,x):
"the backwards recurrence time is the time since the last event after arriving to the system at a large future time"
returnself.forward_recurrence_time_pdf(x)
defforward_recurrence_time_cdf(self,x):
"the forward recurrence time RV is the time need to wait till the next event, after arriving to the system at a large future time"
returnint.quad(self.forward_recurrence_time_pdf, 0, x)
defbackward_recurrence_time_cdf(self,x):
"the backwards recurrence time is the time since the last event after arriving to the system at a large future time"
returnint.quad(self.forward_recurrence_time_pdf, 0, x)
defspread_pdf(self,x):
"""the RV distributed according to the spread_pdf is the (random) length of time between the previous and next event/jump
when you arrive at a large future time."""
try:
returnself.renewal_rate*x*self.T.pdf(x)
exceptAttributeError:
returnself.renewal_rate*x*self.T.pmf(x)
def_generate_sample_path(self,times):
pathOfJumps=self.generate_sample_jumps(times[-1])
count=0
path=[]
N=len(pathOfJumps)
#what happens when no jumps occur?
try:
tao=pathOfJumps[0][0]
exceptIndexError:
tao=times[-1]
x=self.startPosition
fortintimes:
ift<tao:
path.append((t,x))
else:
whilet>taoandcount<N-1:
count+=1
tao=pathOfJumps[count][0]
x=pathOfJumps[count][1]
path.append((t,x))
returnpath
def_generate_sample_jumps(self,T):
"T-self.startTime is the time window we are looking for jumps in."
t=self.startTime
x=self.startPosition
path=[]
tao=self.T.rvs()
delta=self.J.rvs()
t=t+tao
x=x+delta
whilet<T:
path.append((t,x))
tao=self.T.rvs()
delta=self.J.rvs()
t=t+tao
x=x+delta
returnpath
def_get_mean_at(self,t):
try:
returnself.J.mean()*self.T.mean()
except:
returnself.J.mean()*self.get_mean_number_of_jumps(t)
def_get_variance_at(self,t):
pass
def_generate_position_at(self,t):
tao=self.startTime+self.T.rvs()
x=self.startPosition
whiletao<t:
x+=self.J.rvs()
tao+=self.T.rvs()
returnx
classPoisson_process(Renewal_process):
"""
This class creates the Poisson process defined by N(t) being distributed according to a poisson distribution.
parameters:
$\{'rate': \text{scalar}>0\}$
"""
def__init__(self,parameters,time_space_constraints):
self.rate=float(parameters["rate"])
self.Exp=stats.expon(1/self.rate)
self.Con=Constant(1)
super(Poisson_process,self).__init__({"J":self.Con, "T":self.Exp}, time_space_constraints)
self.Poi=stats.poisson
ifself.conditional:
self.Bin=stats.binom
def_get_mean_at(self,t):
#recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t/T)
ifnotself.conditional:
returnself.startPosition+self.rate*(t-self.startTime)
else:
returnself.endPosition*float(t)/self.endTime
def_get_variance_at(self,t):
ifself.conditional:
returnself.endPosition*(1-float(t)/self.endTime)*float(t)/self.endTime
else:
returnself.rate*(t-self.startTime)
def_generate_sample_jumps(self,T):
ifself.conditional:
p=self.Bin.rvs(self.endPosition, T/self.endTime)
else:
p=self.Poi.rvs(self.rate*(T-self.startTime))
x=self.startPosition
path=[]
array= [self.startTime+(T-self.startTime)*random.random() foriinrange(p)]
array.sort()
foriinrange(p):
x+=1
path.append((array[i],x))
i+=1
returnpath
def_generate_position_at(self,t):
ifself.conditional:
returnself.Bin.rvs(self.endPosition-self.startPosition, float(t)/self.endTime)+self.startPosition
else:
returnself.Poi.rvs(self.rate*(t-self.startTime))+self.startPosition
classMarked_poisson_process(Renewal_process):
"""
This class constructs marked poisson process ie at exponentially distributed times, a
Uniform(L,U) is generated.
parameters:
$\{\text{'rate':scalar}>0, U:\text{(scalar, upper-bound )} , L:\text{(scalar, less than U, lower-bound)}, \text{startTime:scalar} \}$
*the bounds refer to the uniform distribution
Note there are no other time-space constraints
"""
def__init__(self, parameters):
self.L=parameters["L"]
self.U=parameters["U"]
self.startTime=parameters["startTime"]
self.rate=parameters["rate"]
self.Uni=stats.uniform()
self.Poi=stats.poisson
defgenerate_marked_process(self,T):
process= []
p=self.Poi.rvs(self.rate*(T-self.startTime))
path=[]
array= [self.startTime+(T-self.startTime)*random.random() foriinrange(p)]
array.sort()
foriinrange(p):
x=self.L+(self.U-self.L)*self.Uni.rvs()
path.append((array[i],x))
i+=1
returnpath
classCompound_poisson_process(Renewal_process):
"""
This process has expontially distributed inter-arrival times (i.e. 'rate'-poisson distributed number of jumps at any time),
and has jump distribution J.
parameters:
{"J":see below, "rate":scalar>0}
J is a frozen scipy.stats random variable instance. It can have any support.
Note: endTime and endPosition constraints will not be statisfied.
Ex:
import stats.scipy as stats
Nor = stats.norm(0,1)
cmp = Compound_poisson_process({"J":Nor})
"""
def__init__(self, parameters,time_space_constraints):
self.J=parameters["J"]
self.rate=float(parameters["rate"])
self.Exp=stats.expon(1/self.rate)
super(Compound_poisson_process, self).__init__({"J":self.J, "T":self.Exp}, time_space_constraints)
self.Poi=stats.poisson
def_get_mean_at(self,t):
returnself.startPosition+self.rate*(t-self.startTime)*self.J.mean()
def_get_variance_at(self,t):
returnself.rate*(t-self.startTime)*(self.J.var()-self.J.mean()**2)
def_generate_sample_jumps(self,T):
p=self.Poi.rvs(self.rate*(T-self.startTime))
x=self.startPosition
path=[]
array= [self.startTime+(T-self.startTime)*random.random() foriinrange(p)]
array.sort()
foriinrange(p):
x+=self.J.rvs()
path.append((array[i],x))
i+=1
returnpath
classDiffusion_process(object):
#
# Class that can be overwritten in the subclasses:
# _get_position_at(t)
# _get_mean_at(t)
# _get_variance_at(t)
# _generate_position_at(t)
# _generate_sample_path(times)
#
# Class that should be present in subclasses:
#
# _transition_pdf(x,t,y)
#
#
def__init__(self, dict):
"'dict' contains the time and space constraints"
try:
self.startTime=float(dict["startTime"])
self.startPosition=float(dict["startPosition"])
self.conditional=False
ifdict.has_key("endTime"):
self.endTime=float(dict["endTime"])
self.endPosition=float(dict["endPosition"])
self.conditional=True
exceptKeyError:
print"Missing constraint in initial\end value dictionary. Check spelling?"
deftransition_pdf(self,t,y):
self._check_time(t)
"this method calls self._transition_pdf(x) in the subclass"
try:
ifnotself.conditional:
returnself._transition_pdf(self.startPosition, t-self.startTime, y)
else:
returnself._transition_pdf(self.startPosition, t-self.startTime, y)*self._transition_pdf(y, self.endTime-t, self.endPosition)\
/self._transition_pdf(self.startPosition,self.endTime-self.startTime, self.endPosition)
except:
print"Attn: transition density is not defined"
defexpected_value(self,f,t,N):
self._check_time(t)
"uses a monte carlo approach to evaluate the expected value of the process f(X_t). N is the number of iterations. The parameter f\
is a univariate python function."
print"Attn: performing a Monte Carlo simulation..."
ifnotself.conditional:
sum=0
foriinrange(N):
sum+=f(self.generate_position_at(t))
returnsum/N
else:
#This uses a change of measure technique.
sum=0
self.conditional=False
foriinrange(N):
X=self.generate_position_at(t)
sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X)
self.conditional=True
returnsum/(N*self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition))
defgenerate_position_at(self,t):
self._check_time(t)
"if _get_position_at() is not overwritten in a subclass, this function will use euler scheme"
ifself.startTime<t:
returnself._generate_position_at(t)
defget_mean_at(self,t):
self._check_time(t)
returnself._get_mean_at(t)
defget_variance_at(self,t):
self._check_time(t)
returnself._get_variance_at(t)
defgenerate_sample_path(self,times):
try:
self._check_time(times[0])
except:
pass
returnself._generate_sample_path(times)
def_generate_sample_path(self,times):
returnself.Euler_scheme(times)
def_get_variance_at(self,t):
var=SampleVarStat()
foriinrange(10000):
var.push(self.generate_position_at(t))
returnvar.get_variance()
def_get_mean_at(self,t):
"if _get_mean_at() is not overwritten, then we use MC methods; 100000 iterations"
defid(x):
returnx
returnself.expected_value(id, t, 100000)
def_generate_position_at(self,t,delta=0.001):
returnself.Euler_scheme([t])
def_transition_pdf(self,x,t,y):
print"Attn: transition pdf not defined"
def_check_time(self,t):
ift<self.startTime:
print"Attn: inputed time not valid (check if beginning time is less than startTime)."
defEuler_scheme(self, times,delta=0.001):
"returns an array!"
"The process needs the methods drift() and diffusion() defined."
print"Attn: starting a Euler scheme..."
Nor=stats.norm()
finalTime=times[-1]
steps=int(finalTime/delta)
t=self.startTime
x=self.startPosition
path=[]
j=0
time=times[j]
foriinxrange(steps):
ift+delta>time>t:
delta=time-t
x+=drift(x,t)*delta+sqrt(delta)*diffusion(x,t)*Nor.rvs()
path.append((x,time))
delta=0.001
j+=1
time=times[j]
else:
x+=drift(x,t)*delta+sqrt(delta)*diffusion(x,t)*Nor.rvs()
t+=delta
returnpath
defprocess2latex(self):
return_process2latex(self)
classWiener_process(Diffusion_process):
"""
$dW_t = \mu*dt + \sigma*dB_t$
parameters:
$\{\mu: \text{scalar}, \sigma: \text{scalar}>0\}$
"""
def__init__(self, parameters, time_space_constraints):
super(Wiener_process,self).__init__(time_space_constraints)
forpinparameters:
setattr(self,p,parameters[p])
self.Nor=stats.norm()
def_transition_pdf(self,x,t,y):
returnexp(-(y-x-self.mu*(t-self.startTime))**2/(2*self.sigma**2*(t-self.startTime)))\
/sqrt(2*pi*self.sigma*(t-self.startTime))
def_get_mean_at(self,t):
ifself.conditional:
delta1=t-self.startTime
delta2=self.endTime-self.startTime
returnself.startPosition+self.mu*delta1+ (self.endPosition-self.startPosition-self.mu*delta2)*delta1/delta2
else:
returnself.startPosition+self.mu*(t-self.startTime)
def_get_variance_at(self,t):
ifself.conditional:
delta1=self.sigma**2*(t-self.startTime)*(self.endTime-t)
delta2=self.endTime-self.startTime
returndelta1/delta2
else:
returnself.sigma**2*(t-self.startTime)
def_generate_position_at(self,t):
returnself.get_mean_at(t) +sqrt(self.get_variance_at(t))*self.Nor.rvs()
def_generate_sample_path(self,times):
t=self.startTime
x=self.startPosition
path=[]
ifnotself.conditional:
fortimeintimes:
delta=time-t
x=x+self.mu*delta+self.sigma*sqrt(delta)*self.Nor.rvs()
path.append((time,x))
t=time
else:
T=self.endTime-self.startTime
fortimeintimes:
delta=float(time-t)
try:
x=x*(1-delta/T)+self.endPosition*delta/T+self.sigma*sqrt(delta/T*(T-delta))*self.Nor.rvs()
except:
x=self.endPosition
T=T-delta
t=time
path.append((time,x))
returnpath
defgenerate_max(self,t):
pass
defgenerate_min(self,t):
pass
def_process2latex(self):
"""This function will return a string that shows a latex representation of the inputed parameters."""
return"$dW_t = %.3fdt + %.3fdB_t$"%(self.mu, self.sigma)
classOU_process(Diffusion_process):
"""
The Orstein-Uhlenbeck process
$dOU_t = \theta*(\mu-OU_t)*dt + \sigma*dB_t$
parameters:
$\{\theta:\text{scalar}, \not = 0, \mu:\text{scalar}, \sigma:\text{scalar}>0\}$
"""
def__init__(self, parameters, time_space_constraints):
super(OU_process, self).__init__(time_space_constraints)
forpinparameters:
setattr(self, p, float(parameters[p]))
self.Normal=stats.norm()
def_get_mean_at(self,t):
deff(s):
returnself.startPosition*exp(-self.theta*(s-self.startTime))+self.mu*(1-exp(-self.theta*(s-self.startTime)))
ifself.conditional:
returnsuper(OU_process,self)._get_mean_at(t)
else:
returnf(t)
def_get_variance_at(self,t):
defv(s):
returnself.sigma**2*(1-exp(-2*self.theta*s))/(2*self.theta)
ifself.conditional:
returnsuper(OU_process,self)._get_variance_at(t)
else:
returnv(t)
def_transition_pdf(self,x,t,y):
mu=x*exp(-self.theta*t)+self.mu*(1-exp(-self.theta*t))
sigmaSq=self.sigma**2*(1-exp(-self.theta*2*t))/(2*self.theta)
returnexp(-(y-mu)**2/(2*sigmaSq))/sqrt(2*pi*sigmaSq)
def_generate_position_at(self,t):
ifnotself.conditional:
returnself.get_mean_at(t)+sqrt(self.get_variance_at(t))*self.Normal.rvs()
else:
#this needs to be completed
pass
returnsuper(OU_process,self)._generate_position_at(t)
defgenerate_sample_path(self,times, Normals=0):
"the parameter Normals = 0 is used for the Integrated OU Process"
ifnotself.conditional:
path= []
listOfNormals= []
t=self.startTime
x=self.startPosition
fortimeintimes:
delta=time-t
mu=self.mu+exp(-self.theta*delta)*(x-self.mu)
sigma=sqrt(self.sigma**2*(1-exp(-2*self.theta*delta))/(2*self.theta))
N=self.Normal.rvs()
x=mu+sigma*N
listOfNormals.append(N)
t=time
path.append((t,x))
if (Normals==0):
returnpath
else:
returnpath, listOfNormals
else:
path=bridge_creation(self,times)
returnpath
def_process2latex(self):
return"dOU_t = %.3f(%.3f-OU_t)dt + %.3fdB_t$"%(self.theta, self.mu, self.sigma)
classIntegrated_OU_process(Diffusion_process):
"""
The time-integrated Orstein-Uhlenbeck process
$IOU_t = IOU_0 + \int_0^t OU_s ds$
where $dOU_t = \theta*(\mu-OU_t)*dt + \sigma*dB_t,
OU_0 = x0$
parameters:
{theta:scalar > 0, mu:scalar, sigma:scalar>0, x0:scalar}
modified from http://www.fisica.uniud.it/~milotti/DidatticaTS/Segnali/Gillespie_1996.pdf
"""
def__init__(self, parameters, time_space_constraints):
super(Integrated_OU_process,self).__init__( time_space_constraints)
self.OU=OU_process({"theta":parameters["theta"], "mu":parameters["mu"], "sigma":parameters["sigma"]}, {"startTime":time_space_constraints["startTime"], "startPosition":parameters["x0"]})
forpinparameters:
setattr(self, p, float(parameters[p]))
self.Normal=stats.norm()
def_get_mean_at(self,t):
delta=t-self.startTime
ifself.conditional:
pass
else:
returnself.startPosition+ (self.x0-self.mu)/self.theta+self.mu*delta\
-(self.x0-self.mu)*exp(-self.theta*delta)/self.theta
def_get_variance_at(self,t):
delta=t-self.startTime
ifself.conditional:
pass
else:
returnself.sigma**2*(2*self.theta*delta-3+4*exp(-self.theta*delta)
-2*exp(-2*self.theta*delta))/(2*self.sigma**3)
def_generate_position_at(self,t):
ifself.conditional:
pass
else:
returnself.get_mean_at(t)+sqrt(self.get_variance_at(t))*self.Normal.rvs()
def_transition_pdf(self,x,t,y):
mu=x+ (self.x0-self.mu)/self.theta+self.mu*t- (self.x0-self.mu)*exp(-self.theta*t)/self.theta
sigmaSq=self.sigma**2*(2*self.theta*t-3+4*exp(-self.theta*t)-2*exp(-2*self.theta*t))/(2*self.sigma**3)
returnexp(-(y-mu)**2/(2*sigmaSq))/sqrt(2*pi*sigmaSq)
defgenerate_sample_path(self,times, returnUO=0):
"set returnUO to 1 to return the underlying UO path as well as the integrated UO path."
ifnotself.conditional:
xPath, listOfNormals=self.OU.generate_sample_path(times, 1)
path= []
t=self.startTime
y=self.startPosition
fori, positioninenumerate(xPath):
delta=position[0]-t
x=position[1]
ifdelta!=0:
#there is an error here, I can smell it.
sigmaX=self.sigma**2*(1-exp(-2*self.theta*delta))/(2*self.theta)
sigmaY=self.sigma**2*(2*self.theta*delta-3+4*exp(-self.theta*delta)
-exp(-2*self.theta*delta))/(2*self.sigma**3)
muY=y+ (x-self.mu)/self.theta+self.mu*delta-(x-self.mu)*exp(-self.theta*delta)/self.theta
covXY=self.sigma**2*(1+exp(-2*self.theta*delta)-2*exp(-self.theta*delta))/(2*self.theta**2)
y=muY+sqrt(sigmaY-covXY**2/sigmaX)*self.Normal.rvs()+covXY/sqrt(sigmaX)*listOfNormals[i]
t=position[0]
path.append((t,y))
ifreturnUO==0:
returnpath
else:
returnpath, xPath
else:
path=bridge_creation(self,times)
ifreturnUO==0:
returnpath
else:
returnpath, xPath
def_process2latex(self):
return"""$IOU_t = IOU_0 + \int_0^t OU_s ds
\text{where} dOU_t = %.3f(%.3f-OU_t)dt + %.3fdB_t,
OU_0 = x0
"""%(self.theta, self.mu, self.sigma)
classSqBessel_process(Diffusion_process):
"""
The (lambda0 dimensional) squared Bessel process is defined by the SDE:
$dX_t = \lambda_0*dt + \nu*\sqrt(X_t)dB_t$
Due to the nature of this interface, the process will not be absorbed at the $x=0$ boundary. See the
PyProcess library in order to do this. For this to occur, $\lambda_0>0$.
parameters:
$\{\lambda_0:\text{scalar}, \nu:\text{scalar}>0\}$
Attn: startPosition and endPosition>0
Based on R.N. Makarov and D. Glew's research on simulating squared bessel process. See "Exact
Simulation of Bessel Diffusions", 2011.
"""
#This needs to be completed.
def__init__(self,parameters, time_space_constraints):
super(SqBessel_process, self).__init__(time_space_constraints)
try:
self.endPosition=4.0/parameters["nu"]**2*self.endPosition
self.x_T=self.endPosition
except:
pass
self.x_0=self.startPosition
self.startPosition=4.0/parameters["nu"]**2*self.startPosition
ifparameters.has_key("mu"):
self.mu=float(parameters["mu"])
else:
forpinparameters:
setattr(self, p, float(parameters[p]))
self.mu=2*float(self.lambda0)/(self.nu*self.nu)-1
self.Poi=stats.poisson
self.Gamma=stats.gamma
self.Nor=stats.norm
self.InGamma=IncompleteGamma
def_process2latex(self):
#lambda0 and nu must be defined.
return
"""
$dX_t = %.3fdt + %.3f \sqrt{X_t} dB_t
"""%(self.lambda0, self.nu)
defgenerate_sample_path(self,times,absb=0):
"""
absb is a boolean, true if absorbtion at 0, false else. See class' __doc__ for when
absorbtion is valid.
"""
ifabsb:
returnself._generate_sample_path_with_absorption(times)
else:
returnself._generate_sample_path_no_absorption(times)
def_transition_pdf(self,x,t,y):
try:
return (y/x)**(0.5*self.mu)*exp(-0.5*(x+y)/self.nu**2/t)/(0.5*self.nu**2*t)*iv(abs(self.mu),4*sqrt(x*y)/(self.nu**2*t))
exceptAttributeError:
print"Attn: nu must be known and defined to calculate the transition pdf."
def_generate_sample_path_no_absorption(self, times):
"mu must be greater than -1. The parameter times is a list of times to sample at."
ifself.mu<=-1:
print"Attn: mu must be greater than -1. It is currently %f."%self.mu
return
else:
ifnotself.conditional:
x=self.startPosition
t=self.startTime
path=[]
fortimeintimes:
delta=float(time-t)
try:
y=self.Poi.rvs(0.5*x/delta)
x=self.Gamma.rvs(y+self.mu+1)*2*delta
except:
pass
path.append((time,x))
t=time
else:
path=bridge_creation(self, times, 0)
returnpath
return [(p[0],self.rescalePath(p[1])) forpinpath]
def_generate_sample_path_with_absorption(self,times):
"mu must be less than 0."
ifself.mu>=0:
print"Attn: mu must be less than 0. It is currently %f."%self.mu
else:
ifnotself.conditional:
path=[]
X=self.startPosition
t=self.startTime
tauEst=times[-1]+1
fortimeintimes:
delta=float(time-t)
iftauEst>times[-1]:
p_a=gammaincc(abs(self.mu),0.5*X/(delta))
ifrandom.random() <p_a:
tauEst=time
iftime<tauEst:
Y=self.InGamma.rvs(abs(self.mu),0.5*X/(delta))
X=self.Gamma.rvs(Y+1)*2*delta
else:
X=0
t=time
path.append((t,X))
else:
path=bridge_creation(self, times, 1)
return [(p[0],self.rescalePath(p[1])) forpinpath]
def_generate_position_at(self,t):
p=self.generate_sample_path([t])
returnp[0][1]
defgenerate_sample_FHT_bridge(self,times):
"mu must be less than 0. This process has absorption at L=0. It simulates the absorption at 0 at some random time, tao, and creates a bridge process."
ifself.mu>0:
print"mu must be less than 0. It is currently %f."%self.mu
else:
X=self.startPosition
t=self.t_0
path=[]
FHT=self.startPosition/(2*self.Gamma.rvs(abs(self.mu)))
fortimeintimes:
iftime<FHT:
d=(FHT-t)*(time-t)
Y=self.Poi.rvs(X*(FHT-time)/(2*d))
X=self.Gamma.rvs(Y-self.mu+1)*d/(FHT-t)
else:
X=0
t=time
path.append((t,X))
return [(p[0],self.rescalePath(p[1])) forpinpath]
defrescalePath(self,x):
#All of the simulation algorithms assume nu=2, so we must
# rescale the process to output a path that is has the user specified
# nu. Note that this rescaling does not change mu.
returnself.nu**2/4.0*x
classCIR_process(Diffusion_process):
"""
The CIR process is defined by
dCIR_t = (lambda_0 - lambda_1*CIR_t)dt + nu*sqrt(CIR_t)*dB_t
Due to the nature of this interface, absorption at 0 is impossible. See the PyProcess library for
the ability to aborb at 0.
This is a mean reverting process if both lambdas are positive: the process flucuates around lambda_0/lambda_1
parameters:
{lambda_0:scalar, lambda_1:scalar, nu:scalar>0}
"""
def__init__(self, parameters, space_time_constraints):
super(CIR_process,self).__init__(space_time_constraints)
forpinparameters:
setattr(self, p, float(parameters[p]))
self.Normal=stats.norm()
#transform the space time positions
_space_time_constraints= {}
_space_time_constraints['startTime'] =self._time_transformation(space_time_constraints['startTime'])
_space_time_constraints['startPosition'] =self._inverse_space_transformation(space_time_constraints['startTime'], space_time_constraints['startPosition'])
try:
_space_time_constraints['endPosition'] =self._inverse_space_transformation(space_time_constraints['endTime'], space_time_constraints['endPosition'])
_space_time_constraints['endTime'] =self._time_transformation(space_time_constraints['endTime'])
except:
pass
self.SqB=SqBessel_process({"lambda0":parameters["lambda_0"], "nu":parameters["nu"]}, _space_time_constraints) #need to change start position for non-zero startTime
self.mu=self.SqB.mu
def_process2latex(self):
return"""
$dCIR_t = (%.3f - %.3fCIR_t)dt + %.3f\sqrt(CIR_t)dB_t$
"""%(self.lambda_0, self.lambda_1, self.nu)
def_transition_pdf(self,x,t,y):
returnexp(self.lambda_1*t)*SqB._transition_pdf(x,self._time_transformation(t), exp(self.lambda_1*t)*y)
defgenerate_sample_path(self, times, abs=0):
"abs is a boolean: true if desire nonzero probability of absorption at 0, false else."
#first, transform times:
transformedTimes= [self._time_transformation(t) fortintimes]
path=self.SqB.generate_sample_path(transformedTimes,abs)
tpath= [self._space_transformation(times[i],p[1]) fori,pinenumerate(path) ]
path=[]
foriinxrange(len(tpath)):
path.append((times[i],tpath[i]))
returnpath
def_generate_position_at(self,t):
t_prime=self._time_transformation(t)
x=self.SqB.generate_position_at(t_prime)
returnself._space_transformation(t,x)
def_time_transformation(self,t):
ifself.lambda_1==0:
returnt
else:
return (exp(self.lambda_1*t)-1)/self.lambda_1
def_space_transformation(self,t,x):
returnexp(-self.lambda_1*t)*x
def_inverse_space_transformation(self,t,x):
returnexp(self.lambda_1*t)*x
def_inverse_time_transformation(self, t):
ifself.lambda_1==0:
returnt
else:
returnlog(self.lambda_1*t+1)/self.lambda_1
def_get_mean_at(self,t):
pass
def_get_variance_at(self,t):
pass
classCEV_process(Diffusion_process):
"""
defined by:
$$dCEV = rCEVdt + \deltaCEV^{\beta+1}dW_t$$
parameters:
{r: scalar, delta:scalar>0, beta:scalar<0} #typically beta<=-1/2
"""
def__init__(self,parameters, time_space_constraints):
super(CEV_process,self).__init__(time_space_constraints)
forpinparameters:
setattr(self, p, parameters[p])
time_space_constraints["startPosition"]=self.CEV_to_SqB(self.startPosition)
self.SqB=SqBessel_process({"lambda0":(2-1/self.beta), "nu":2}, time_space_constraints)
def_process2latex(self):
return
"""
$dCEV_t = %.3fCEVdt + %.3fCEV^{\%.3f + 1}dB_t$
"""%(self.r, self.delta, self.beta)
def_time_transform(self,t):
ifself.r*self.beta==0:
returnt
else:
return (exp(self.r*self.beta*2*t)-1)/(self.r*self.beta*2)
defCEV_to_SqB(self,x):
returnx**(-2*self.beta)/(self.delta*self.beta)**2
def_scalar_space_transform(self,t,x):
returnexp(self.r*t)*x
defSqB_to_CEV(self,x):
ans= (self.delta**2*self.beta**2*x)**(-1/(2.0*self.beta))
returnans
defgenerate_sample_path(self,times, abs=0):
ifself.r==0:
SqBPath=self.SqB.generate_sample_path(times, abs)
return [(x[0],self.SqB_to_CEV(x[1])) forxinSqBPath]
else:
transformedTimes= [self._time_transform(t) fortintimes]
SqBPath=self.SqB.generate_sample_path(transformedTimes, abs)
tempPath= [self.SqB_to_CEV(x[1]) forxinSqBPath]
return [(times[i], self._scalar_space_transform(times[i], p) ) fori,pinenumerate(tempPath)]
def_generate_position_at(self,t):
ifself.r==0:
SqBpos=self.SqB.generate_position_at(t)
returnself.SqB_to_CEV(SqBpos)
else:
transformedTime=self._time_transform(t)
SqBpos=self.SqB.generate_position_at(transformedTime)
returnself._scalar_space_transform(t,self.SqB_to_CEV(SqBpos))
classPeriodic_drift_process(Diffusion_process):
"""
dX_t = psi*sin(X_t + theta)dt + dBt
parameters:
{psi:scalar>0, theta:scalar>0}
This cannot be conditioned on start or end conditions.
Extensions to come.
"""
def__init__(self, parameters, space_time_constraints):
"""Note that space-time constraints cannot be given"""
space_time_constraints= {"startTime":0, "startPosition":0}