forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwindow.pyx
1737 lines (1348 loc) · 50.1 KB
/
window.pyx
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
# cython: profile=False
# cython: boundscheck=False, wraparound=False, cdivision=True
from cython cimport Py_ssize_t
cimport numpy as np
import numpy as np
cimport cython
np.import_array()
cimport util
from libc.stdlib cimport malloc, free
from numpy cimport ndarray, double_t, int64_t, float64_t
from skiplist cimport (IndexableSkiplist,
node_t, skiplist_t,
skiplist_init, skiplist_destroy,
skiplist_get, skiplist_insert, skiplist_remove)
cdef np.float32_t MINfloat32 = np.NINF
cdef np.float64_t MINfloat64 = np.NINF
cdef np.float32_t MAXfloat32 = np.inf
cdef np.float64_t MAXfloat64 = np.inf
cdef double NaN = <double> np.NaN
cdef inline int int_max(int a, int b): return a if a >= b else b
cdef inline int int_min(int a, int b): return a if a <= b else b
from util cimport numeric
cdef extern from "../src/headers/math.h":
int signbit(double) nogil
double sqrt(double x) nogil
# Cython implementations of rolling sum, mean, variance, skewness,
# other statistical moment functions
#
# Misc implementation notes
# -------------------------
#
# - In Cython x * x is faster than x ** 2 for C types, this should be
# periodically revisited to see if it's still true.
#
def _check_minp(win, minp, N, floor=None):
"""
Parameters
----------
win: int
minp: int or None
N: len of window
floor: int, optional
default 1
Returns
-------
minimum period
"""
if minp is None:
minp = 1
if not util.is_integer_object(minp):
raise ValueError("min_periods must be an integer")
if minp > win:
raise ValueError("min_periods (%d) must be <= "
"window (%d)" % (minp, win))
elif minp > N:
minp = N + 1
elif minp < 0:
raise ValueError('min_periods must be >= 0')
if floor is None:
floor = 1
return max(minp, floor)
# original C implementation by N. Devillard.
# This code in public domain.
# Function : kth_smallest()
# In : array of elements, # of elements in the array, rank k
# Out : one element
# Job : find the kth smallest element in the array
# Reference:
# Author: Wirth, Niklaus
# Title: Algorithms + data structures = programs
# Publisher: Englewood Cliffs: Prentice-Hall, 1976
# Physical description: 366 p.
# Series: Prentice-Hall Series in Automatic Computation
# ----------------------------------------------------------------------
# The indexer objects for rolling
# These define start/end indexers to compute offsets
cdef class WindowIndexer:
cdef:
ndarray start, end
int64_t N, minp, win
bint is_variable
def get_data(self):
return (self.start, self.end, <int64_t>self.N,
<int64_t>self.win, <int64_t>self.minp,
self.is_variable)
cdef class MockFixedWindowIndexer(WindowIndexer):
"""
We are just checking parameters of the indexer,
and returning a consistent API with fixed/variable
indexers.
Parameters
----------
input: ndarray
input data array
win: int64_t
window size
minp: int64_t
min number of obs in a window to consider non-NaN
index: object
index of the input
floor: optional
unit for flooring
left_closed: bint
left endpoint closedness
right_closed: bint
right endpoint closedness
"""
def __init__(self, ndarray input, int64_t win, int64_t minp,
bint left_closed, bint right_closed,
object index=None, object floor=None):
assert index is None
self.is_variable = 0
self.N = len(input)
self.minp = _check_minp(win, minp, self.N, floor=floor)
self.start = np.empty(0, dtype='int64')
self.end = np.empty(0, dtype='int64')
self.win = win
cdef class FixedWindowIndexer(WindowIndexer):
"""
create a fixed length window indexer object
that has start & end, that point to offsets in
the index object; these are defined based on the win
arguments
Parameters
----------
input: ndarray
input data array
win: int64_t
window size
minp: int64_t
min number of obs in a window to consider non-NaN
index: object
index of the input
floor: optional
unit for flooring the unit
left_closed: bint
left endpoint closedness
right_closed: bint
right endpoint closedness
"""
def __init__(self, ndarray input, int64_t win, int64_t minp,
bint left_closed, bint right_closed,
object index=None, object floor=None):
cdef ndarray start_s, start_e, end_s, end_e
assert index is None
self.is_variable = 0
self.N = len(input)
self.minp = _check_minp(win, minp, self.N, floor=floor)
start_s = np.zeros(win, dtype='int64')
start_e = np.arange(win, self.N, dtype='int64') - win + 1
self.start = np.concatenate([start_s, start_e])
end_s = np.arange(win, dtype='int64') + 1
end_e = start_e + win
self.end = np.concatenate([end_s, end_e])
self.win = win
cdef class VariableWindowIndexer(WindowIndexer):
"""
create a variable length window indexer object
that has start & end, that point to offsets in
the index object; these are defined based on the win
arguments
Parameters
----------
input: ndarray
input data array
win: int64_t
window size
minp: int64_t
min number of obs in a window to consider non-NaN
index: ndarray
index of the input
left_closed: bint
left endpoint closedness
True if the left endpoint is closed, False if open
right_closed: bint
right endpoint closedness
True if the right endpoint is closed, False if open
floor: optional
unit for flooring the unit
"""
def __init__(self, ndarray input, int64_t win, int64_t minp,
bint left_closed, bint right_closed, ndarray index,
object floor=None):
self.is_variable = 1
self.N = len(index)
self.minp = _check_minp(win, minp, self.N, floor=floor)
self.start = np.empty(self.N, dtype='int64')
self.start.fill(-1)
self.end = np.empty(self.N, dtype='int64')
self.end.fill(-1)
self.build(index, win, left_closed, right_closed)
# max window size
self.win = (self.end - self.start).max()
def build(self, ndarray[int64_t] index, int64_t win, bint left_closed,
bint right_closed):
cdef:
ndarray[int64_t] start, end
int64_t start_bound, end_bound, N
Py_ssize_t i, j
start = self.start
end = self.end
N = self.N
start[0] = 0
# right endpoint is closed
if right_closed:
end[0] = 1
# right endpoint is open
else:
end[0] = 0
with nogil:
# start is start of slice interval (including)
# end is end of slice interval (not including)
for i in range(1, N):
end_bound = index[i]
start_bound = index[i] - win
# left endpoint is closed
if left_closed:
start_bound -= 1
# advance the start bound until we are
# within the constraint
start[i] = i
for j in range(start[i - 1], i):
if index[j] > start_bound:
start[i] = j
break
# end bound is previous end
# or current index
if index[end[i - 1]] <= end_bound:
end[i] = i + 1
else:
end[i] = end[i - 1]
# right endpoint is open
if not right_closed:
end[i] -= 1
def get_window_indexer(input, win, minp, index, closed,
floor=None, use_mock=True):
"""
return the correct window indexer for the computation
Parameters
----------
input: 1d ndarray
win: integer, window size
minp: integer, minimum periods
index: 1d ndarray, optional
index to the input array
closed: string, default None
{'right', 'left', 'both', 'neither'}
window endpoint closedness. Defaults to 'right' in
VariableWindowIndexer and to 'both' in FixedWindowIndexer
floor: optional
unit for flooring the unit
use_mock: boolean, default True
if we are a fixed indexer, return a mock indexer
instead of the FixedWindow Indexer. This is a type
compat Indexer that allows us to use a standard
code path with all of the indexers.
Returns
-------
tuple of 1d int64 ndarrays of the offsets & data about the window
"""
cdef:
bint left_closed = False
bint right_closed = False
assert closed is None or closed in ['right', 'left', 'both', 'neither']
# if windows is variable, default is 'right', otherwise default is 'both'
if closed is None:
closed = 'right' if index is not None else 'both'
if closed in ['right', 'both']:
right_closed = True
if closed in ['left', 'both']:
left_closed = True
if index is not None:
indexer = VariableWindowIndexer(input, win, minp, left_closed,
right_closed, index, floor)
elif use_mock:
indexer = MockFixedWindowIndexer(input, win, minp, left_closed,
right_closed, index, floor)
else:
indexer = FixedWindowIndexer(input, win, minp, left_closed,
right_closed, index, floor)
return indexer.get_data()
# ----------------------------------------------------------------------
# Rolling count
# this is only an impl for index not None, IOW, freq aware
def roll_count(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed):
cdef:
double val, count_x = 0.0
int64_t s, e, nobs, N
Py_ssize_t i, j
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, _ = get_window_indexer(input, win,
minp, index, closed)
output = np.empty(N, dtype=float)
with nogil:
for i in range(0, N):
s = start[i]
e = end[i]
if i == 0:
# setup
count_x = 0.0
for j in range(s, e):
val = input[j]
if val == val:
count_x += 1.0
else:
# calculate deletes
for j in range(start[i - 1], s):
val = input[j]
if val == val:
count_x -= 1.0
# calculate adds
for j in range(end[i - 1], e):
val = input[j]
if val == val:
count_x += 1.0
if count_x >= minp:
output[i] = count_x
else:
output[i] = NaN
return output
# ----------------------------------------------------------------------
# Rolling sum
cdef inline double calc_sum(int64_t minp, int64_t nobs, double sum_x) nogil:
cdef double result
if nobs >= minp:
result = sum_x
else:
result = NaN
return result
cdef inline void add_sum(double val, int64_t *nobs, double *sum_x) nogil:
""" add a value from the sum calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] + 1
sum_x[0] = sum_x[0] + val
cdef inline void remove_sum(double val, int64_t *nobs, double *sum_x) nogil:
""" remove a value from the sum calc """
if val == val:
nobs[0] = nobs[0] - 1
sum_x[0] = sum_x[0] - val
def roll_sum(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed):
cdef:
double val, prev_x, sum_x = 0
int64_t s, e, range_endpoint
int64_t nobs = 0, i, j, N
bint is_variable
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, is_variable = get_window_indexer(input, win,
minp, index,
closed,
floor=0)
output = np.empty(N, dtype=float)
# for performance we are going to iterate
# fixed windows separately, makes the code more complex as we have 2 paths
# but is faster
if is_variable:
# variable window
with nogil:
for i in range(0, N):
s = start[i]
e = end[i]
if i == 0:
# setup
sum_x = 0.0
nobs = 0
for j in range(s, e):
add_sum(input[j], &nobs, &sum_x)
else:
# calculate deletes
for j in range(start[i - 1], s):
remove_sum(input[j], &nobs, &sum_x)
# calculate adds
for j in range(end[i - 1], e):
add_sum(input[j], &nobs, &sum_x)
output[i] = calc_sum(minp, nobs, sum_x)
else:
# fixed window
range_endpoint = int_max(minp, 1) - 1
with nogil:
for i in range(0, range_endpoint):
add_sum(input[i], &nobs, &sum_x)
output[i] = NaN
for i in range(range_endpoint, N):
val = input[i]
add_sum(val, &nobs, &sum_x)
if i > win - 1:
prev_x = input[i - win]
remove_sum(prev_x, &nobs, &sum_x)
output[i] = calc_sum(minp, nobs, sum_x)
return output
# ----------------------------------------------------------------------
# Rolling mean
cdef inline double calc_mean(int64_t minp, Py_ssize_t nobs,
Py_ssize_t neg_ct, double sum_x) nogil:
cdef double result
if nobs >= minp:
result = sum_x / <double>nobs
if neg_ct == 0 and result < 0:
# all positive
result = 0
elif neg_ct == nobs and result > 0:
# all negative
result = 0
else:
pass
else:
result = NaN
return result
cdef inline void add_mean(double val, Py_ssize_t *nobs, double *sum_x,
Py_ssize_t *neg_ct) nogil:
""" add a value from the mean calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] + 1
sum_x[0] = sum_x[0] + val
if signbit(val):
neg_ct[0] = neg_ct[0] + 1
cdef inline void remove_mean(double val, Py_ssize_t *nobs, double *sum_x,
Py_ssize_t *neg_ct) nogil:
""" remove a value from the mean calc """
if val == val:
nobs[0] = nobs[0] - 1
sum_x[0] = sum_x[0] - val
if signbit(val):
neg_ct[0] = neg_ct[0] - 1
def roll_mean(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed):
cdef:
double val, prev_x, result, sum_x = 0
int64_t s, e
bint is_variable
Py_ssize_t nobs = 0, i, j, neg_ct = 0, N
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, is_variable = get_window_indexer(input, win,
minp, index,
closed)
output = np.empty(N, dtype=float)
# for performance we are going to iterate
# fixed windows separately, makes the code more complex as we have 2 paths
# but is faster
if is_variable:
with nogil:
for i in range(0, N):
s = start[i]
e = end[i]
if i == 0:
# setup
sum_x = 0.0
nobs = 0
for j in range(s, e):
val = input[j]
add_mean(val, &nobs, &sum_x, &neg_ct)
else:
# calculate deletes
for j in range(start[i - 1], s):
val = input[j]
remove_mean(val, &nobs, &sum_x, &neg_ct)
# calculate adds
for j in range(end[i - 1], e):
val = input[j]
add_mean(val, &nobs, &sum_x, &neg_ct)
output[i] = calc_mean(minp, nobs, neg_ct, sum_x)
else:
with nogil:
for i from 0 <= i < minp - 1:
val = input[i]
add_mean(val, &nobs, &sum_x, &neg_ct)
output[i] = NaN
for i from minp - 1 <= i < N:
val = input[i]
add_mean(val, &nobs, &sum_x, &neg_ct)
if i > win - 1:
prev_x = input[i - win]
remove_mean(prev_x, &nobs, &sum_x, &neg_ct)
output[i] = calc_mean(minp, nobs, neg_ct, sum_x)
return output
# ----------------------------------------------------------------------
# Rolling variance
cdef inline double calc_var(int64_t minp, int ddof, double nobs,
double ssqdm_x) nogil:
cdef double result
# Variance is unchanged if no observation is added or removed
if (nobs >= minp) and (nobs > ddof):
# pathological case
if nobs == 1:
result = 0
else:
result = ssqdm_x / (nobs - <double>ddof)
if result < 0:
result = 0
else:
result = NaN
return result
cdef inline void add_var(double val, double *nobs, double *mean_x,
double *ssqdm_x) nogil:
""" add a value from the var calc """
cdef double delta
# Not NaN
if val == val:
nobs[0] = nobs[0] + 1
# a part of Welford's method for the online variance-calculation
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
delta = val - mean_x[0]
mean_x[0] = mean_x[0] + delta / nobs[0]
ssqdm_x[0] = ssqdm_x[0] + ((nobs[0] - 1) * delta ** 2) / nobs[0]
cdef inline void remove_var(double val, double *nobs, double *mean_x,
double *ssqdm_x) nogil:
""" remove a value from the var calc """
cdef double delta
# Not NaN
if val == val:
nobs[0] = nobs[0] - 1
if nobs[0]:
# a part of Welford's method for the online variance-calculation
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
delta = val - mean_x[0]
mean_x[0] = mean_x[0] - delta / nobs[0]
ssqdm_x[0] = ssqdm_x[0] - ((nobs[0] + 1) * delta ** 2) / nobs[0]
else:
mean_x[0] = 0
ssqdm_x[0] = 0
def roll_var(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed, int ddof=1):
"""
Numerically stable implementation using Welford's method.
"""
cdef:
double val, prev, mean_x = 0, ssqdm_x = 0, nobs = 0, delta, mean_x_old
int64_t s, e
bint is_variable
Py_ssize_t i, j, N
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, is_variable = get_window_indexer(input, win,
minp, index,
closed)
output = np.empty(N, dtype=float)
# Check for windows larger than array, addresses #7297
win = min(win, N)
# for performance we are going to iterate
# fixed windows separately, makes the code more complex as we
# have 2 paths but is faster
if is_variable:
with nogil:
for i in range(0, N):
s = start[i]
e = end[i]
# Over the first window, observations can only be added
# never removed
if i == 0:
for j in range(s, e):
add_var(input[j], &nobs, &mean_x, &ssqdm_x)
else:
# After the first window, observations can both be added
# and removed
# calculate adds
for j in range(end[i - 1], e):
add_var(input[j], &nobs, &mean_x, &ssqdm_x)
# calculate deletes
for j in range(start[i - 1], s):
remove_var(input[j], &nobs, &mean_x, &ssqdm_x)
output[i] = calc_var(minp, ddof, nobs, ssqdm_x)
else:
with nogil:
# Over the first window, observations can only be added, never
# removed
for i from 0 <= i < win:
add_var(input[i], &nobs, &mean_x, &ssqdm_x)
output[i] = calc_var(minp, ddof, nobs, ssqdm_x)
# a part of Welford's method for the online variance-calculation
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
# After the first window, observations can both be added and
# removed
for i from win <= i < N:
val = input[i]
prev = input[i - win]
if val == val:
if prev == prev:
# Adding one observation and removing another one
delta = val - prev
mean_x_old = mean_x
mean_x += delta / nobs
ssqdm_x += ((nobs - 1) * val
+ (nobs + 1) * prev
- 2 * nobs * mean_x_old) * delta / nobs
else:
add_var(val, &nobs, &mean_x, &ssqdm_x)
elif prev == prev:
remove_var(prev, &nobs, &mean_x, &ssqdm_x)
output[i] = calc_var(minp, ddof, nobs, ssqdm_x)
return output
# ----------------------------------------------------------------------
# Rolling skewness
cdef inline double calc_skew(int64_t minp, int64_t nobs, double x, double xx,
double xxx) nogil:
cdef double result, dnobs
cdef double A, B, C, R
if nobs >= minp:
dnobs = <double>nobs
A = x / dnobs
B = xx / dnobs - A * A
C = xxx / dnobs - A * A * A - 3 * A * B
# #18044: with uniform distribution, floating issue will
# cause B != 0. and cause the result is a very
# large number.
#
# in core/nanops.py nanskew/nankurt call the function
# _zero_out_fperr(m2) to fix floating error.
# if the variance is less than 1e-14, it could be
# treat as zero, here we follow the original
# skew/kurt behaviour to check B <= 1e-14
if B <= 1e-14 or nobs < 3:
result = NaN
else:
R = sqrt(B)
result = ((sqrt(dnobs * (dnobs - 1.)) * C) /
((dnobs - 2) * R * R * R))
else:
result = NaN
return result
cdef inline void add_skew(double val, int64_t *nobs, double *x, double *xx,
double *xxx) nogil:
""" add a value from the skew calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] + 1
# seriously don't ask me why this is faster
x[0] = x[0] + val
xx[0] = xx[0] + val * val
xxx[0] = xxx[0] + val * val * val
cdef inline void remove_skew(double val, int64_t *nobs, double *x, double *xx,
double *xxx) nogil:
""" remove a value from the skew calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] - 1
# seriously don't ask me why this is faster
x[0] = x[0] - val
xx[0] = xx[0] - val * val
xxx[0] = xxx[0] - val * val * val
def roll_skew(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed):
cdef:
double val, prev
double x = 0, xx = 0, xxx = 0
int64_t nobs = 0, i, j, N
int64_t s, e
bint is_variable
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, is_variable = get_window_indexer(input, win,
minp, index,
closed)
output = np.empty(N, dtype=float)
if is_variable:
with nogil:
for i in range(0, N):
s = start[i]
e = end[i]
# Over the first window, observations can only be added
# never removed
if i == 0:
for j in range(s, e):
val = input[j]
add_skew(val, &nobs, &x, &xx, &xxx)
else:
# After the first window, observations can both be added
# and removed
# calculate adds
for j in range(end[i - 1], e):
val = input[j]
add_skew(val, &nobs, &x, &xx, &xxx)
# calculate deletes
for j in range(start[i - 1], s):
val = input[j]
remove_skew(val, &nobs, &x, &xx, &xxx)
output[i] = calc_skew(minp, nobs, x, xx, xxx)
else:
with nogil:
for i from 0 <= i < minp - 1:
val = input[i]
add_skew(val, &nobs, &x, &xx, &xxx)
output[i] = NaN
for i from minp - 1 <= i < N:
val = input[i]
add_skew(val, &nobs, &x, &xx, &xxx)
if i > win - 1:
prev = input[i - win]
remove_skew(prev, &nobs, &x, &xx, &xxx)
output[i] = calc_skew(minp, nobs, x, xx, xxx)
return output
# ----------------------------------------------------------------------
# Rolling kurtosis
cdef inline double calc_kurt(int64_t minp, int64_t nobs, double x, double xx,
double xxx, double xxxx) nogil:
cdef double result, dnobs
cdef double A, B, C, D, R, K
if nobs >= minp:
dnobs = <double>nobs
A = x / dnobs
R = A * A
B = xx / dnobs - R
R = R * A
C = xxx / dnobs - R - 3 * A * B
R = R * A
D = xxxx / dnobs - R - 6 * B * A * A - 4 * C * A
# #18044: with uniform distribution, floating issue will
# cause B != 0. and cause the result is a very
# large number.
#
# in core/nanops.py nanskew/nankurt call the function
# _zero_out_fperr(m2) to fix floating error.
# if the variance is less than 1e-14, it could be
# treat as zero, here we follow the original
# skew/kurt behaviour to check B <= 1e-14
if B <= 1e-14 or nobs < 4:
result = NaN
else:
K = (dnobs * dnobs - 1.) * D / (B * B) - 3 * ((dnobs - 1.) ** 2)
result = K / ((dnobs - 2.) * (dnobs - 3.))
else:
result = NaN
return result
cdef inline void add_kurt(double val, int64_t *nobs, double *x, double *xx,
double *xxx, double *xxxx) nogil:
""" add a value from the kurotic calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] + 1
# seriously don't ask me why this is faster
x[0] = x[0] + val
xx[0] = xx[0] + val * val
xxx[0] = xxx[0] + val * val * val
xxxx[0] = xxxx[0] + val * val * val * val
cdef inline void remove_kurt(double val, int64_t *nobs, double *x, double *xx,
double *xxx, double *xxxx) nogil:
""" remove a value from the kurotic calc """
# Not NaN
if val == val:
nobs[0] = nobs[0] - 1
# seriously don't ask me why this is faster
x[0] = x[0] - val
xx[0] = xx[0] - val * val
xxx[0] = xxx[0] - val * val * val
xxxx[0] = xxxx[0] - val * val * val * val
def roll_kurt(ndarray[double_t] input, int64_t win, int64_t minp,
object index, object closed):
cdef:
double val, prev
double x = 0, xx = 0, xxx = 0, xxxx = 0
int64_t nobs = 0, i, j, N
int64_t s, e
bint is_variable
ndarray[int64_t] start, end
ndarray[double_t] output
start, end, N, win, minp, is_variable = get_window_indexer(input, win,
minp, index,
closed)
output = np.empty(N, dtype=float)