-
Notifications
You must be signed in to change notification settings - Fork 31
/
pyprocess.py
2012 lines (1589 loc) · 71.4 KB
/
pyprocess.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
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
from __future__ import division
"""
PyProcess
@author: Cameron Davidson-Pilon
"""
import numpy as np
import scipy as sp
import scipy.stats as stats
from scipy.special import gammainc
import warnings
import matplotlib.pyplot as plt
import pdb
np.seterr( divide="raise")
#TODO change all generate_ to sample_
class Step_process(object):
"""
This is the class of finite activity jump/event processes (eg poisson process, renewel process etc).
Parameters:
time_space_constraints: a dictionary contraining AT LEAST "startTime":float, "startPosition":float,
"""
def __init__(self, startTime = 0, startPosition = 0, endTime = None, endPosition = None):
self.conditional=False
self.startTime = startTime
self.startPosition = startPosition
if ( endTime != None ) and ( endPosition != None ):
assert endTime > startTime, "invalid parameter: endTime > startTime"
self.endTime = endTime
self.endPosition = endPosition
self.condition = True
elif ( endTime != None ) != ( endPosition != None ):
raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" )
def _check_time(self,t):
if t<self.startTime:
raise Exception("Attn: inputed time not valid. Check if beginning time is less than startTime (0 by default).")
def sample_path(self,times, N=1):
try:
self._check_time(times[0])
except TypeError:
self._check_time( times )
return self._sample_path(times, N)
def sample_jumps(self,T, N = 1):
self._check_time(T)
return self._sample_jumps(T,N)
def mean(self,t):
self._check_time(t)
return self._mean(t)
def var(self,t):
self._check_time(t)
return self._var(t)
def mean_number_of_jumps(self,t):
self._check_time(t)
return self._mean_number_of_jumps(t)
def sample_position(self,t, N=1):
self._check_time(t)
return self._sample_position(t, N)
def _mean_number_of_jumps(self,t, n_simulations = 10000):
self._check_time(t)
"""
This needs to solve the following:
E[ min(N) | T_1 + T_2 + .. T_N >= t ]
<=>
E[ N | T_1 + T_2 + .. T_{N-1} < t, T_1 + T_2 + .. T_N >= t ]
where we can sample T only.
"""
warnings.warn("Attn: performing MC simulation. %d simulations."%n_simulations)
v = np.zeros( n_simulations )
continue_ = True
i = 1
t = t - self.startTime #should be positive.
size = v.shape[0]
sum = 0
sum_sq = 0
while continue_:
v += self.T.rvs( size )
#count how many are greater than t
n_greater_than_t = (v>=t).sum()
sum += n_greater_than_t*i
v = v[v < t]
i+=1
size = v.shape[0]
empty = size == 0
if empty:
continue_ = False
if i > 10000:
warnings.warn("The algorithm did not converge. Be sure 'T' is a non negative random \
variable, or set 't' lower.")
break
return sum/n_simulations
def _var(self,t):
self._check_time(t)
return self._mean_number_of_jumps(t)*self.J.var()
def plot(self, t,N=1, **kwargs):
assert N >= 1, "N must be greater than 0."
for n in range(N):
path = [self.startPosition, self.startPosition]
times = [self.startTime]
_path, _times = self.sample_path(t,1)
for i in range(2*_path.shape[1]):
j = int( (i - i%2)/2)
path.append( _path[0][j] )
times.append( _times[0][j] )
#path.append( _path[0][-1] )
times.append( t)
#pdb.set_trace()
plt.plot( times, path, **kwargs )
plt.xlabel( "time, $t$")
plt.ylabel( "position of process")
plt.show()
return
class Renewal_process(Step_process):
"""
parameters:
T: 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, it
can be called as Contant(c), where c is the interarrival time.
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 a poisson process, J is equal to 1 with probability 1, and we can use the Constant(1) class,
but J is random for the compound poisson process.
Note 1. endTime and endPosition are not allowed for this class.
Note 2. If you are interested in Poisson or Compound poisson process, they are implemented in PyProcess.
Those implementations are recommened to use versus using a Renewal_process. See Poisson_process
and Compound_poisson_process.
Ex:
import scipy.stats as stats
#create a standard renewal process
renewal_ps= Renewal_process( J = Constant(3.5), T = stats.poisson(1), startTime = 0, startPosition = 0 )
"""
def __init__(self, T, J, startPosition = 0, startTime = 0):
super(Renewal_process, self).__init__(startTime = startTime,startPosition = startPosition)
self.T = T
self.J = J
self.renewal_rate = 1/self.T.mean()
def forward_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"
return self.renewal_rate*self.T.sf(x)
def backwards_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"
return self.forward_recurrence_time_pdf(x)
def forward_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"
return int.quad(self.forward_recurrence_time_pdf, 0, x)
def backward_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"
return int.quad(self.forward_recurrence_time_pdf, 0, x)
def spread_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:
return self.renewal_rate*x*self.T.pdf(x)
except AttributeError:
return self.renewal_rate*x*self.T.pmf(x)
def _sample_path(self,time, N =1):
"""
parameters:
time: an interable that returns floats OR if a single float, returns (path,jumps) up to time t.
N: the number of paths to return. negative N returns an iterator of size N.
returns:
path: the sample path at the times in times
jumps: the times when the process jumps
Scales linearly with number of sequences and time.
"""
if N < 0:
return self._iterator_sample_paths(time, -N)
else:
return self.__sample_path( time, N ) #np.asarray( [self.__sample_path(times) for i in xrange(N) ] )
def _iterator_sample_paths( self, times, N):
for i in xrange(N):
yield self.__sample_path(times)
def __sample_path( self, times, N=1 ):
if isinstance( times, int): #not the best way to do this.
"""user wants a path up to time times."""
def generate_jumps( x, J, start_position):
n = x.shape[0]
return start_position + J.rvs(n).cumsum()
_times = self.sample_jumps(times,N)
_path = np.asarray( map( lambda x: generate_jumps(x, self.J, self.startPosition), _times) )
return (_path, _times )
else:
# times is an iterable, user requests "give me positions at these times."
pass
#TODO
def __sample_jumps(self, t ):
quantity_per_i = 10
times = np.array([])
c = 0 #measure of size
while True:
c += quantity_per_i
times = np.append( times, self.T.rvs(quantity_per_i) )
times = times[ times.cumsum() < t ]
if times.shape[0] < c:
#this will only happen if the list is truncated.
return times.cumsum()
def iterator_sample_jumps(self, t, N):
for i in xrange(N):
yield __sample_jumps(t)
def _sample_jumps(self,t, N=1):
"""
Generate N simulations of jump times prior to some time t > startTime.
parameters:
t: the end of the processes.
N: the number of samples to return, -N to return a generator of size N
returns:
An irregular numpy array, with first dimension N, and each element an np.array
with random length.
example:
>> print renewal_ps.generate_sample_jumps( 1, N=2)
np.array( [ [2,2.5,3.0], [1.0,2.0] ], dtype=0bject )
"""
if N<0:
return ( self.__sample_jumps(t) for i in xrange(-N) )
else:
return np.asarray( [ self.__sample_jumps(t) for i in xrange(N) ] )
def _mean(self,t):
#try:
#return self.J.mean()*self.T.mean()
#except:
return self.J.mean()*self.mean_number_of_jumps(t)
def _var(self,t):
return self.mean_number_of_jumps(t)*self.J.var()
def _sample_position(self,t, N = 1):
"""
Generate the position of the process at time t > startTime
parameters:
N: number of samples
t: position to sample at.
returns:
returns a (n,) np.array
"""
v = np.zeros( N )
iv = np.ones( N, dtype=bool )
x = self.startPosition*np.ones( N)
continue_ = True
i = 1
t = t - self.startTime #should be positive.
size = v.shape[0]
while continue_:
n_samples = iv.sum()
v[iv] += self.T.rvs( n_samples )
#if the next time is beyond reach, we do not add a new jump
iv[ v >= t] = False
n_samples = iv.sum()
x[iv] += self.J.rvs( n_samples )
size = iv.sum() #any left?
empty = size == 0
i+=1
if empty:
continue_ = False
if i > 10000:
warnings.warn("The algorithm did not converge. Be sure 'T' is a non negative random \
variable, or set 't' to a smaller value.")
break
return x
class Poisson_process(Renewal_process):
"""
This implements a Poisson process with rate parameter 'rate' (lambda was already taken!).
Parameters:
rate: float > 0 that define the inter-arrival rate.
startTime: (default 0) The start time of the process
startPosition: (default 0) The starting position of the process at startTime
conditional processes:
If the process is known at some future time, endPosition and endTime
condition the process to arrive there.
endTime: (default None) the time in the future the process is known at, > startTime
endPosition: (default None) the position the process is at in the future.
> startPosition and equal to startPosition + int.
ex:
#condition the process to be at position 5 at time 10.
pp = Poisson_process( rate = 3, endTime = 10, endPosition = 5 )
"""
def __init__(self,rate=1, startTime = 0, startPosition = 0, endPosition = None, endTime = None):
assert rate > 0, "invalid parameter: rate parameter must be greater than 0."
self.rate = rate
self.Exp = stats.expon(1/self.rate)
self.Con = Constant(1)
super(Poisson_process,self).__init__(J=self.Con, T=self.Exp, startTime = startTime, startPosition = startPosition)
self.Poi = stats.poisson
if ( endTime != None ) and ( endPosition != None ):
assert endTime > startTime, "invalid times: endTime > startTime."
self.endTime = endTime
self.endPosition = endPosition
self.condition = True
self.Bin = stats.binom
elif ( endTime != None ) != ( endPosition != None ):
raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" )
def _mean(self,t):
"""
recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t/T)
"""
if not self.conditional:
return self.startPosition + self.rate*(t-self.startTime)
else:
return self.endPosition*float(t)/self.endTime
def _var(self,t):
"""
parameters:
t: a time > startTime (and less than endTime if present).
returns:
a float.
recall that a conditional poisson process N_t | N_T=n ~ Bin(n, t/T)
"""
if self.conditional:
return self.endPosition*(1-float(t)/self.endTime)*float(t)/self.endTime
else:
return self.rate*(t-self.startTime)
def __sample_jumps(self,t):
if self.conditional:
p = self.Bin.rvs(self.endPosition, t/self.endTime)
else:
p = self.Poi.rvs(self.rate*(t-self.startTime))
path=[]
#array = [self.startTime+(T-self.startTime)*np.random.random() for i in xrange(p)]
jump_times = self.startTime + (t - self.startTime)*np.random.random(p)
jump_times.sort()
#for i in xrange(p):
# x+=1
# path.append((array[i],x))
# i+=1
return jump_times
def _sample_jumps(self, t, N=1):
"""
Probably to be deleted.
T: a float
N: the number of sample paths
Returns:
an (N,) np.array of jump times.
"""
if N<0:
return ( self.__sample_jumps(t) for i in xrange(-N) )
else:
return np.asarray( [self.__sample_jumps(t) for i in xrange(N)] )
def _sample_position(self,t, N=1):
if self.conditional:
return self.Bin.rvs(self.endPosition-self.startPosition, float(t)/self.endTime, size = N)+self.startPosition
else:
return self.Poi.rvs(self.rate*(t-self.startTime), size = N)+self.startPosition
class Marked_poisson_process(Renewal_process):
"""
This class constructs marked poisson process i.e. at exponentially distributed times, a
Uniform(L,U) is generated.
parameters:
rate: the rate for the poisson process
U: the upper bound of uniform random variate generation
L: the lower bound of uniform random variate generation
Note there are no other time-space constraints besides startTime
"""
def __init__(self,rate =1, L= 0, U = 1, startTime = 0):
self.Poi = stats.poisson
self.L = L
self.U = U
self.startTime = startTime
self.rate = rate
def generate_marked_process(self,T):
p = self.Poi.rvs(self.rate*(T-self.startTime))
times = self.startTime + (T-self.startTime)*np.random.random( p )
path = self.L+(self.U-self.L)*np.random.random( p )
return ( path, times )
class Compound_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: a frozen scipy.stats random variable instance. It can have any support.
Note: endTime and endPosition constraints will not be statisfied.
Example:
>> import stats.scipy as stats
>> Nor = stats.norm(0,1)
>> cmp = Compound_poisson_process(J = Nor)
"""
def __init__(self, J, rate = 1,startTime = 0, startPosition = 0):
assert rate > 0, "Choose rate to be greater than 0."
self.J = J
self.rate = rate
self.Exp = stats.expon(1./self.rate)
super(Compound_poisson_process, self).__init__(J = J, T= T, startTime = startTime, startPosition = startPosition)
self.Poi = stats.poisson
def _mean(self,t):
return self.startPosition + self.rate*(t-self.startTime)*self.J.mean()
def _var(self,t):
return self.rate*(t-self.startTime)*(self.J.var()-self.J.mean()**2)
"""
def __sample_jumps(self,T):
p = self.Poi.rvs(self.rate*(T-self.startTime))
x = self.startPosition
path=[]
array = [self.startTime+(T-self.startTime)*np.random.rand() for i in range(p)]
array.sort()
for i in range(p):
x+=self.J.rvs()
path.append((array[i],x))
i+=1
return path
"""
class Diffusion_process(object):
#
# Class that can be overwritten in the subclasses:
# _sample_position(t, N=1)
# _mean(t)
# _var(t)
# _sample_path(times, N=1)
#
# Class that should be present in subclasses:
#
# _transition_pdf(x,t,y)
#
#
def __init__(self, startTime = 0, startPosition = 0, endTime = None, endPosition = None):
self.conditional=False
self.startTime = startTime
self.startPosition = startPosition
if ( endTime != None ) and ( endPosition != None ):
assert endTime > startTime, "invalid parameter: endTime > startTime"
self.endTime = endTime
self.endPosition = endPosition
self.conditional = True
elif ( endTime != None ) != ( endPosition != None ):
raise Exception( "invalid parameter:", "Must include both endTime AND endPosition or neither" )
def transition_pdf(self,t,y):
self._check_time(t)
"this method calls self._transition_pdf(x,t,y) in the subclass"
try:
if not self.conditional:
return self._transition_pdf(self.startPosition, t-self.startTime, y)
else:
return self._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 AttributeError:
raise AttributeError("Attn: transition density for process is not defined.")
def expected_value(self,t, f= lambda x:x, N=1e6):
"""
This function calculates the expected value of E[ X_t | F ] where F includes start conditions and possibly end conditions.
"""
warnings.warn( "Performing Monte Carlo with %d simulations."%N)
self._check_time(t)
if not self.conditional:
return f( self.sample_position(t, N) ).mean()
else:
#This uses a change of measure technique.
"""
sum=0
self.conditional=False
for i in range(N):
X = self.generate_position_at(t)
sum+=self._transition_pdf(X,self.endTime-t,self.endPosition)*f(X)
self.conditional=True
"""
x = self.sample_position(t, N)
mean = (self._transition_pdf(x,self.endTime-t,self.endPosition)*f(x)).mean()
return mean/self._transition_pdf(self.startPosition, self.endTime-self.startTime, self.endPosition)
def sample_position(self,t, N=1):
"""
if _get_position_at() is not overwritten in a subclass, this function will use euler scheme
"""
self._check_time(t)
return self._sample_position(t, N)
def mean(self,t):
self._check_time(t)
return self._mean(t)
def var(self,t):
self._check_time(t)
return self._var(t)
def sample_path(self,times, N = 1):
self._check_time(times[0])
return self._sample_path(times, N)
def _sample_path(self,times, N=1 ):
return self.Euler_scheme(times, N)
def _var(self,t, N = 1e6):
"""
var = SampleVarStat()
for i in range(10000):
var.push(self.generate_position_at(t))
return var.get_variance()
"""
return self.sample_position(t, n).var()
def _mean(self,t):
return self.expected_value( t)
def _sample_position(self,t):
return self.Euler_scheme(t)
def _transition_pdf(self,x,t,y):
warning.warn( "Attn: transition pdf not defined" )
def _check_time(self,t):
if t<self.startTime:
warnings.warn( "Attn: inputed time not valid (check if beginning time is less than startTime)." )
def Euler_scheme(self, times,delta=0.001):
"""
times is an array of floats.
The process needs the methods drift() and diffusion() defined.
"""
warnings.warn("Attn: starting an Euler scheme to approxmiate process.")
Nor = stats.norm()
finalTime = times[-1]
steps = int(finalTime/delta)
t = self.startTime
x=self.startPosition
path=[]
j=0
time = times[j]
for i in xrange(steps):
if t+delta>time>t:
delta = time-t
x += drift(x,t)*delta + np.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 + np.sqrt(delta)*diffusion(x,t)*Nor.rvs()
t += delta
return path
def Milstein_Scheme(self, times, delta = 0.01 ):
if not all( map( lambda x: hasattr(self, x), ( 'drift', 'diffusion', 'diffusion_prime' ) ) ):
raise AttributeError("The process does not have 'drift', 'diffusion', or 'diffusion_prime' methods")
pass
def plot(self, times ,N=1, **kwargs):
assert N >= 1, "N must be greater than 0."
try:
self._check_time(times[-1] )
plt.plot(times, self.sample_path(times, N).T, **kwargs )
except:
self._check_time(times)
times = np.linspace(self.startTime, times, 100)
path = self.sample_path(times, N).T
plt.plot(times, path, **kwargs )
plt.xlabel( "time, $t$")
plt.ylabel( "position of process")
plt.show()
return
class Wiener_process(Diffusion_process):
"""
This implements the famous Wiener process. I choose not to call it Brownian motion, as
brownian motion is a special case of this with 0 drift and variance equal to t.
dW_t = mu*dt + sigma*dB_t
W_t ~ N(mu*t, sigma**2t)
parameters:
mu: the constant drift term, float
sigma: the constant volatility term, float > 0
"""
def __init__(self, mu, sigma, startTime = 0, startPosition = 0, endPosition = None, endTime = None):
super(Wiener_process,self).__init__(startTime, startPosition, endTime, endPosition)
self.mu = mu
self.sigma = sigma
self.Nor = stats.norm()
def _transition_pdf(self,x,t,y):
return np.exp(-(y-x-self.mu*(t-self.startTime))**2/(2*self.sigma**2*(t-self.startTime)))\
/np.sqrt(2*pi*self.sigma*(t-self.startTime))
def _mean(self,t):
if self.conditional:
delta1 = t - self.startTime
delta2 = self.endTime - self.startTime
return self.startPosition + self.mu*delta1 + (self.endPosition-self.startPosition-self.mu*delta2)*delta1/delta2
else:
return self.startPosition+self.mu*(t-self.startTime)
def _var(self,t):
if self.conditional:
delta1 = self.sigma**2*(t-self.startTime)*(self.endTime-t)
delta2 = self.endTime-self.startTime
return delta1/delta2
else:
return self.sigma**2*(t-self.startTime)
def _sample_position(self,t, n=1):
"""
This incorporates both conditional and unconditional
"""
return self.mean(t) + np.sqrt(self.var(t))*self.Nor.rvs(n)
def _sample_path(self,times, N = 1):
path=np.zeros( (N,len(times)) )
path[ :, 0] = self.startPosition
times = np.insert( times, 0,self.startTime)
deltas = np.diff( times )
if not self.conditional:
path += np.random.randn( N, len(times)-1 )*self.sigma*np.sqrt(deltas) + self.mu*deltas
return path.cumsum(axis=1)
else:
"""
Alternatively, this can be accomplished by sampling directly from a multivariate normal given a linear
projection. Ie
N | N dot 1 = endPosition ~ Nor( 0, Sigma ), where Sigma is a diagonal matrix with elements proportional to
the delta. This only problem with this is Sigma is too large for very large len(times).
"""
T = self.endTime - self.startTime
x = self.startTime
for i, delta in enumerate( deltas ):
x = x*(1-delta/T)+(self.endPosition - self.startPosition)*delta/T + self.sigma*np.sqrt(delta/T*(T-delta))*self.Nor.rvs(N)
T = T - delta
path[:,i] = x
if abs(T -0)<1e-10:
path[:,-1] = (self.endPosition - self.startPosition)
path = path + self.startPosition
return path
def generate_max(self,t):
pass
def generate_min(self,t):
pass
def drift(t,x):
return self.mu
def diffusion(t,x):
return self.sigma
def diffusion_prime(t,x):
return 0
#have a Vasicek model that has an alternative parameterizatiom but essentially just maps to OU_process
class OU_process(Diffusion_process):
"""
The Orstein-Uhlenbeck process is a mean reverting model that is often used in finance to model interest rates.
It is also known as a Vasicek model. It is defined by the SDE:
dOU_t = theta*(mu-OU_t)*dt + sigma*dB_t$
The model flucuates around its long term mean mu. mu is also a good starting Position of the process.
There exists a solution to the SDE, see wikipedia.
parameters:
theta: float > 0
mu: float
sigma: float > 0
"""
def __init__(self, theta, mu, sigma, startTime = 0, startPosition = 0, endPosition = None, endTime = None ):
assert sigma > 0 and theta > 0, "theta > 0 and sigma > 0."
super(OU_process, self).__init__(startTime, startPosition, endTime, endPosition)
self.theta = theta
self.mu = mu
self.sigma = sigma
self.Normal = stats.norm()
def _mean(self,t):
if self.conditional:
return super(OU_process,self)._mean(t) #TODO
else:
return self.startPosition*np.exp(-self.theta*(t-self.startTime))+self.mu*(1-np.exp(-self.theta*(t-self.startTime)))
def _var(self,t):
if self.conditional:
return super(OU_process,self)._get_variance_at(t)
else:
return self.sigma**2*(1-np.exp(-2*self.theta*t))/(2*self.theta)
def _transition_pdf(self,x,t,y):
mu = x*np.exp(-self.theta*t)+self.mu*(1-np.exp(-self.theta*t))
sigmaSq = self.sigma**2*(1-np.exp(-self.theta*2*t))/(2*self.theta)
return np.exp(-(y-mu)**2/(2*sigmaSq))/np.sqrt(2*pi*sigmaSq)
def _sample_position(self,t):
if not self.conditional:
return self.get_mean_at(t)+np.sqrt(self.get_variance_at(t))*self.Normal.rvs()
else:
#this needs to be completed
return super(OU_process,self)._generate_position_at(t)
def sample_path(self,times, N= 1, return_normals = False):
"the parameter Normals = 0 is used for the Integrated OU Process"
if not self.conditional:
path=np.zeros( (N,len(times)) )
times = np.insert( times, 0,self.startTime)
path[ :, 0] = self.startPosition
deltas = np.diff(times )
normals = np.random.randn( N, len(times)-1 )
x = self.startPosition*np.ones( N)
sigma = np.sqrt(self.sigma**2*(1-np.exp(-2*self.theta*deltas))/(2*self.theta))
for i, delta in enumerate(deltas):
mu = self.mu + np.exp(-self.theta*delta)*(x-self.mu)
path[:, i] = mu + sigma[i]*normals[:,i]
x = path[:,i]
"""
It would be really cool if there was a numpy func like np.cumf( func, array )
that applies func(next_x, prev_x) to each element. For example, lambda x,y: y + x
is the cumsum, and lambda x,y: x*y is the cumprod function.
"""
if return_normals:
return (path, normals )
else:
return path
else:
#TODO
path = bridge_creation(self,times)
return path
def drift(self, x, t):
return self.theta*(self.mu-x)
def diffusion( self, x,t ):
return self.sigma
class Integrated_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"]})
for p in parameters:
setattr(self, p, float(parameters[p]))
self.Normal = stats.norm()
def _get_mean_at(self,t):
delta = t - self.startTime
if self.conditional:
pass
else:
return self.startPosition + (self.x0-self.mu)/self.theta + self.mu*delta\
-(self.x0-self.mu)*np.exp(-self.theta*delta)/self.theta
def _get_variance_at(self,t):
delta = t - self.startTime
if self.conditional:
pass
else:
return self.sigma**2*(2*self.theta*delta-3+4*np.exp(-self.theta*delta)
-2*np.exp(-2*self.theta*delta))/(2*self.sigma**3)
def _generate_position_at(self,t):
if self.conditional:
pass
else:
return self.get_mean_at(t)+np.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)*np.exp(-self.theta*t)/self.theta
sigmaSq = self.sigma**2*(2*self.theta*t-3+4*np.exp(-self.theta*t)-2*np.exp(-2*self.theta*t))/(2*self.sigma**3)
return np.exp(-(y-mu)**2/(2*sigmaSq))/np.sqrt(2*pi*sigmaSq)
def generate_sample_path(self,times, returnUO = 0):
"set returnUO to 1 to return the underlying UO path as well as the integrated UO path."
if not self.conditional:
xPath, listOfNormals = self.OU.generate_sample_path(times, 1)
path = []
t = self.startTime
y = self.startPosition
for i, position in enumerate(xPath):
delta = position[0]-t
x = position[1]
if delta != 0:
#there is an error here, I can smell it.
sigmaX = self.sigma**2*(1-np.exp(-2*self.theta*delta))/(2*self.theta)
sigmaY = self.sigma**2*(2*self.theta*delta-3+4*np.exp(-self.theta*delta)
-np.exp(-2*self.theta*delta))/(2*self.sigma**3)
muY = y + (x-self.mu)/self.theta + self.mu*delta-(x-self.mu)*np.exp(-self.theta*delta)/self.theta
covXY = self.sigma**2*(1+np.exp(-2*self.theta*delta)-2*np.exp(-self.theta*delta))/(2*self.theta**2)
y = muY + np.sqrt(sigmaY - covXY**2/sigmaX)*self.Normal.rvs()+ covXY/np.sqrt(sigmaX)*listOfNormals[i]
t = position[0]
path.append((t,y))
if returnUO==0:
return path
else:
return path, xPath
else:
path = bridge_creation(self,times)
if returnUO==0:
return path
else:
return path, 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)
class SqBessel_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
parameters:
lambda_0: float,
nu: float > 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.
"""
def __init__(self, lambda_0, nu, startTime = 0, startPosition = 1, endTime = None, endPosition = None ):
super(SqBessel_process, self).__init__(startTime, startPosition, endTime, endPosition)
try:
self.endPosition = 4.0/parameters["nu"]**2*self.endPosition
self.x_T = self.endPosition
except:
pass
self.x_0 = 4.0/nu**2*self.startPosition
self.nu = nu
self.lambda0 = lambda_0
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 generate_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.
"""
if absb:
return self._generate_sample_path_with_absorption(times)
else:
return self._generate_sample_path_no_absorption(times)
def _transition_pdf(self,x,t,y):
try:
return (y/x)**(0.5*self.mu)*np.exp(-0.5*(x+y)/self.nu**2/t)/(0.5*self.nu**2*t)*iv(abs(self.mu),4*np.sqrt(x*y)/(self.nu**2*t))