-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathtrend.pyx
More file actions
912 lines (753 loc) · 26.9 KB
/
Copy pathtrend.pyx
File metadata and controls
912 lines (753 loc) · 26.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
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
# -------------------------------------------------------------------------------------------------
# Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
# https://nautechsystems.io
#
# Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -------------------------------------------------------------------------------------------------
from collections import deque
from statistics import mean
import numpy as np
import pandas as pd
from nautilus_trader.indicators.averages import MovingAverageFactory
cimport numpy as np
from cpython.datetime cimport datetime
from nautilus_trader.core.correctness cimport Condition
from nautilus_trader.indicators.averages cimport MovingAverageType
cdef str get_ma_type_name(MovingAverageType ma_type):
if ma_type == MovingAverageType.SIMPLE:
return "SIMPLE"
elif ma_type == MovingAverageType.EXPONENTIAL:
return "EXPONENTIAL"
elif ma_type == MovingAverageType.DOUBLE_EXPONENTIAL:
return "DOUBLE_EXPONENTIAL"
elif ma_type == MovingAverageType.WILDER:
return "WILDER"
elif ma_type == MovingAverageType.HULL:
return "HULL"
elif ma_type == MovingAverageType.ADAPTIVE:
return "ADAPTIVE"
elif ma_type == MovingAverageType.WEIGHTED:
return "WEIGHTED"
elif ma_type == MovingAverageType.VARIABLE_INDEX_DYNAMIC:
return "VARIABLE_INDEX_DYNAMIC"
else:
return "UNKNOWN"
from nautilus_trader.core.rust.model cimport PriceType
from nautilus_trader.indicators.base cimport Indicator
from nautilus_trader.model.data cimport Bar
from nautilus_trader.model.data cimport QuoteTick
from nautilus_trader.model.data cimport TradeTick
from nautilus_trader.model.objects cimport Price
cdef class ArcherMovingAveragesTrends(Indicator):
"""
Archer Moving Averages Trends indicator.
Parameters
----------
fast_period : int
The period for the fast moving average (> 0).
slow_period : int
The period for the slow moving average (> 0 & > fast_sma).
signal_period : int
The period for lookback price array (> 0).
ma_type : MovingAverageType
The moving average type for the calculations.
References
----------
https://github.com/twopirllc/pandas-ta/blob/bc3b292bf1cc1d5f2aba50bb750a75209d655b37/pandas_ta/trend/amat.py
"""
def __init__(
self,
int fast_period,
int slow_period,
int signal_period,
MovingAverageType ma_type=MovingAverageType.EXPONENTIAL,
):
Condition.positive_int(fast_period, "fast_period")
Condition.positive_int(slow_period, "slow_period")
Condition.is_true(slow_period > fast_period, "fast_period was >= slow_period")
Condition.positive_int(signal_period, "signal_period")
params = [
fast_period,
slow_period,
signal_period,
get_ma_type_name(ma_type),
]
super().__init__(params=params)
self.fast_period = fast_period
self.slow_period = slow_period
self.signal_period = signal_period
self._fast_ma = MovingAverageFactory.create(fast_period, ma_type)
self._slow_ma = MovingAverageFactory.create(slow_period, ma_type)
self._fast_ma_price = deque(maxlen = signal_period + 1)
self._slow_ma_price = deque(maxlen = signal_period + 1)
self.long_run = 0
self.short_run = 0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(
bar.close.as_double(),
)
cpdef void update_raw(self, double close):
"""
Update the indicator with the given close price value.
Parameters
----------
close : double
The close price.
"""
self._fast_ma.update_raw(close)
self._slow_ma.update_raw(close)
if self._slow_ma.initialized:
self._fast_ma_price.append(self._fast_ma.value)
self._slow_ma_price.append(self._slow_ma.value)
self.long_run = (self._fast_ma_price[-1] - self._fast_ma_price[0] > 0 and \
self._slow_ma_price[-1] - self._slow_ma_price[0] < 0 )
self.long_run = (self._fast_ma_price[-1] - self._fast_ma_price[0] > 0 and \
self._slow_ma_price[-1] - self._slow_ma_price[0] > 0 ) or self.long_run
self.short_run = (self._fast_ma_price[-1] - self._fast_ma_price[0] < 0 and \
self._slow_ma_price[-1] - self._slow_ma_price[0] > 0 )
self.short_run = (self._fast_ma_price[-1] - self._fast_ma_price[0] < 0 and \
self._slow_ma_price[-1] - self._slow_ma_price[0] < 0 ) or self.short_run
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if len(self._slow_ma_price) >= self.signal_period + 1 and self._slow_ma.initialized:
self._set_initialized(True)
cpdef void _reset(self):
self._fast_ma.reset()
self._slow_ma.reset()
self._fast_ma_price.clear()
self._slow_ma_price.clear()
self.long_run = 0
self.short_run = 0
cdef class AroonOscillator(Indicator):
"""
The Aroon (AR) indicator developed by Tushar Chande attempts to
determine whether an instrument is trending, and how strong the trend is.
AroonUp and AroonDown lines make up the indicator with their formulas below.
Parameters
----------
period : int
The rolling window period for the indicator (> 0).
"""
def __init__(self, int period):
Condition.positive_int(period, "period")
params = [
period,
]
super().__init__(params = params)
self.period = period
self._high_inputs = deque(maxlen = self.period + 1)
self._low_inputs = deque(maxlen = self.period + 1)
self.aroon_up = 0
self.aroon_down = 0
self.value = 0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(
bar.high.as_double(),
bar.low.as_double(),
)
cpdef void update_raw(
self,
double high,
double low,
):
"""
Update the indicator with the given raw values.
Parameters
----------
high : double
The high price.
low : double
The low price.
"""
# Update inputs
self._high_inputs.appendleft(high)
self._low_inputs.appendleft(low)
# Convert to double to compute values
cdef double periods_from_hh = np.argmax(self._high_inputs)
cdef double periods_from_ll = np.argmin(self._low_inputs)
self.aroon_up = 100.0 * (1.0 - periods_from_hh / self.period)
self.aroon_down = 100.0 * (1.0 - periods_from_ll / self.period)
self.value = self.aroon_up - self.aroon_down
self._check_initialized()
cdef void _check_initialized(self):
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if len(self._high_inputs) >= self.period + 1:
self._set_initialized(True)
cpdef void _reset(self):
self._high_inputs.clear()
self._low_inputs.clear()
self.aroon_up = 0
self.aroon_down = 0
self.value = 0
cdef class DirectionalMovement(Indicator):
"""
Two oscillators that capture positive and negative trend movement.
Parameters
----------
period : int
The rolling window period for the indicator (> 0).
ma_type : MovingAverageType
The moving average type for the indicator (cannot be None).
"""
def __init__(
self,
int period,
MovingAverageType ma_type=MovingAverageType.EXPONENTIAL,
):
Condition.positive_int(period, "period")
params = [
period,
get_ma_type_name(ma_type),
]
super().__init__(params=params)
self.period = period
self._pos_ma = MovingAverageFactory.create(period, ma_type)
self._neg_ma = MovingAverageFactory.create(period, ma_type)
self._previous_high = 0
self._previous_low = 0
self.pos = 0
self.neg = 0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(
bar.high.as_double(),
bar.low.as_double(),
)
cpdef void update_raw(
self,
double high,
double low,
):
"""
Update the indicator with the given raw values.
Parameters
----------
high : double
The high price.
low : double
The low price.
"""
if not self.has_inputs:
self._previous_high = high
self._previous_low = low
cdef double up = high - self._previous_high
cdef double dn = self._previous_low - low
self._pos_ma.update_raw(((up > dn) and (up > 0)) * up)
self._neg_ma.update_raw(((dn > up) and (dn > 0)) * dn)
self.pos = self._pos_ma.value
self.neg = self._neg_ma.value
self._previous_high = high
self._previous_low = low
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if self._neg_ma.initialized:
self._set_initialized(True)
cpdef void _reset(self):
"""
Reset the indicator.
All stateful fields are reset to their initial value.
"""
self._pos_ma.reset()
self._neg_ma.reset()
self._previous_high = 0
self._previous_low = 0
self.pos = 0
self.neg = 0
cdef class MovingAverageConvergenceDivergence(Indicator):
"""
An indicator which calculates the difference between two moving averages.
Different moving average types can be selected for the inner calculation.
Parameters
----------
fast_period : int
The period for the fast moving average (> 0).
slow_period : int
The period for the slow moving average (> 0 & > fast_sma).
ma_type : MovingAverageType
The moving average type for the calculations.
price_type : PriceType
The specified price type for extracting values from quotes.
Raises
------
ValueError
If `fast_period` is not positive (> 0).
ValueError
If `slow_period` is not positive (> 0).
ValueError
If `fast_period` is not < `slow_period`.
"""
def __init__(
self,
int fast_period,
int slow_period,
MovingAverageType ma_type=MovingAverageType.EXPONENTIAL,
PriceType price_type=PriceType.LAST,
):
Condition.positive_int(fast_period, "fast_period")
Condition.positive_int(slow_period, "slow_period")
Condition.is_true(slow_period > fast_period, "slow_period was <= fast_period")
params=[
fast_period,
slow_period,
get_ma_type_name(ma_type),
]
super().__init__(params=params)
self.fast_period = fast_period
self.slow_period = slow_period
self._fast_ma = MovingAverageFactory.create(fast_period, ma_type)
self._slow_ma = MovingAverageFactory.create(slow_period, ma_type)
self.price_type = price_type
self.value = 0
cpdef void handle_quote_tick(self, QuoteTick tick):
"""
Update the indicator with the given quote tick.
Parameters
----------
tick : QuoteTick
The update tick to handle.
"""
Condition.not_none(tick, "tick")
cdef Price price = tick.extract_price(self.price_type)
self.update_raw(Price.raw_to_f64_c(price._mem.raw))
cpdef void handle_trade_tick(self, TradeTick tick):
"""
Update the indicator with the given trade tick.
Parameters
----------
tick : TradeTick
The update tick to handle.
"""
Condition.not_none(tick, "tick")
self.update_raw(Price.raw_to_f64_c(tick._mem.price.raw))
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(bar.close.as_double())
cpdef void update_raw(self, double close):
"""
Update the indicator with the given close price.
Parameters
----------
close : double
The close price.
"""
self._fast_ma.update_raw(close)
self._slow_ma.update_raw(close)
self.value = self._fast_ma.value - self._slow_ma.value
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if self._fast_ma.initialized and self._slow_ma.initialized:
self._set_initialized(True)
cpdef void _reset(self):
self._fast_ma.reset()
self._slow_ma.reset()
self.value = 0
cdef class IchimokuCloud(Indicator):
"""
Ichimoku Cloud (Kinko Hyo) with five components.
- Tenkan-sen (Conversion Line): (tenkan_period high + tenkan_period low) / 2.
- Kijun-sen (Base Line): (kijun_period high + kijun_period low) / 2.
- Senkou Span A (Leading Span A): (Tenkan + Kijun) / 2, displaced forward by displacement.
- Senkou Span B (Leading Span B): (senkou_period high + senkou_period low) / 2, displaced forward by displacement.
- Chikou Span (Lagging Span): Close displaced backward by displacement.
The indicator becomes ``initialized`` after ``senkou_period`` bars,
at which point tenkan_sen, kijun_sen are valid. The displaced outputs
(senkou_span_a, senkou_span_b, chikou_span) require an additional
``displacement`` bars before they become non-zero.
Parameters
----------
tenkan_period : int
Period for Tenkan-sen (default 9).
kijun_period : int
Period for Kijun-sen (default 26).
senkou_period : int
Period for Senkou Span B (default 52).
displacement : int
Displacement for leading/lagging spans (default 26).
Raises
------
ValueError
If any period or displacement is not positive.
ValueError
If senkou_period is not >= kijun_period or kijun_period is not >= tenkan_period.
"""
def __init__(
self,
int tenkan_period=9,
int kijun_period=26,
int senkou_period=52,
int displacement=26,
):
Condition.positive_int(tenkan_period, "tenkan_period")
Condition.positive_int(kijun_period, "kijun_period")
Condition.positive_int(senkou_period, "senkou_period")
Condition.positive_int(displacement, "displacement")
Condition.is_true(
kijun_period >= tenkan_period,
"kijun_period was < tenkan_period",
)
Condition.is_true(
senkou_period >= kijun_period,
"senkou_period was < kijun_period",
)
super().__init__(params=[tenkan_period, kijun_period, senkou_period, displacement])
self.tenkan_period = tenkan_period
self.kijun_period = kijun_period
self.senkou_period = senkou_period
self.displacement = displacement
self._highs_tenkan = deque(maxlen=tenkan_period)
self._lows_tenkan = deque(maxlen=tenkan_period)
self._highs_kijun = deque(maxlen=kijun_period)
self._lows_kijun = deque(maxlen=kijun_period)
self._highs_senkou = deque(maxlen=senkou_period)
self._lows_senkou = deque(maxlen=senkou_period)
self._senkou_a = deque(maxlen=displacement)
self._senkou_b = deque(maxlen=displacement)
self._chikou = deque(maxlen=displacement)
self.tenkan_sen = 0.0
self.kijun_sen = 0.0
self.senkou_span_a = 0.0
self.senkou_span_b = 0.0
self.chikou_span = 0.0
cpdef void handle_bar(self, Bar bar):
Condition.not_none(bar, "bar")
self.update_raw(
bar.high.as_double(),
bar.low.as_double(),
bar.close.as_double(),
)
cpdef void update_raw(self, double high, double low, double close):
self._highs_tenkan.append(high)
self._lows_tenkan.append(low)
self._highs_kijun.append(high)
self._lows_kijun.append(low)
self._highs_senkou.append(high)
self._lows_senkou.append(low)
if not self.initialized:
self._set_has_inputs(True)
if (
len(self._highs_tenkan) >= self.tenkan_period
and len(self._highs_kijun) >= self.kijun_period
and len(self._highs_senkou) >= self.senkou_period
):
self._set_initialized(True)
if len(self._highs_tenkan) >= self.tenkan_period:
self.tenkan_sen = (max(self._highs_tenkan) + min(self._lows_tenkan)) / 2.0
if len(self._highs_kijun) >= self.kijun_period:
self.kijun_sen = (max(self._highs_kijun) + min(self._lows_kijun)) / 2.0
cdef double mid52 = 0.0
if len(self._highs_senkou) >= self.senkou_period:
mid52 = (max(self._highs_senkou) + min(self._lows_senkou)) / 2.0
if self.initialized:
if len(self._senkou_a) == self.displacement:
self.senkou_span_a = self._senkou_a[0]
self._senkou_a.append((self.tenkan_sen + self.kijun_sen) / 2.0)
if len(self._senkou_b) == self.displacement:
self.senkou_span_b = self._senkou_b[0]
self._senkou_b.append(mid52)
if len(self._chikou) == self.displacement:
self.chikou_span = self._chikou[0]
self._chikou.append(close)
cpdef void _reset(self):
self._highs_tenkan.clear()
self._lows_tenkan.clear()
self._highs_kijun.clear()
self._lows_kijun.clear()
self._highs_senkou.clear()
self._lows_senkou.clear()
self._senkou_a.clear()
self._senkou_b.clear()
self._chikou.clear()
self.tenkan_sen = 0.0
self.kijun_sen = 0.0
self.senkou_span_a = 0.0
self.senkou_span_b = 0.0
self.chikou_span = 0.0
cdef class LinearRegression(Indicator):
"""
An indicator that calculates a simple linear regression.
Parameters
----------
period : int
The period for the indicator.
Raises
------
ValueError
If `period` is not greater than zero.
"""
def __init__(self, int period=0):
Condition.positive_int(period, "period")
super().__init__(params=[period])
self.period = period
self._inputs = deque(maxlen=self.period)
self.slope = 0.0
self.intercept = 0.0
self.degree = 0.0
self.cfo = 0.0
self.R2 = 0.0
self.value = 0.0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(bar.close.as_double())
cpdef void update_raw(self, double close):
"""
Update the indicator with the given raw values.
Parameters
----------
close_price : double
The close price.
"""
self._inputs.append(close)
# Warmup indicator logic
if not self.initialized:
self._set_has_inputs(True)
if len(self._inputs) >= self.period:
self._set_initialized(True)
else:
return
cdef np.ndarray x_arr = np.arange(1, self.period + 1, dtype=np.float64)
cdef np.ndarray y_arr = np.asarray(self._inputs, dtype=np.float64)
cdef double x_sum = 0.5 * self.period * (self.period + 1)
cdef double x2_sum = x_sum * (2 * self.period + 1) / 3
cdef double divisor = self.period * x2_sum - x_sum * x_sum
cdef double y_sum = sum(y_arr)
cdef double xy_sum = sum(x_arr * y_arr)
self.slope = (self.period * xy_sum - x_sum * y_sum) / divisor
self.intercept = (y_sum * x2_sum - x_sum * xy_sum) / divisor
cdef np.ndarray residuals = np.zeros(self.period, dtype=np.float64)
cdef int i
for i in np.arange(self.period):
residuals[i] = self.slope * x_arr[i] + self.intercept - y_arr[i]
self.value = residuals[-1] + y_arr[-1]
self.degree = 180.0 / np.pi * np.arctan(self.slope)
self.cfo = 100.0 * residuals[-1] / y_arr[-1]
# Compute R2 with handling for zero variance in y_arr
cdef double ssr = sum(residuals * residuals)
cdef double sst = sum((y_arr - mean(y_arr)) * (y_arr - mean(y_arr)))
if sst == 0.0:
self.R2 = -np.inf
else:
self.R2 = 1.0 - ssr / sst
cpdef void _reset(self):
self._inputs.clear()
self.slope = 0.0
self.intercept = 0.0
self.degree = 0.0
self.cfo = 0.0
self.R2 = 0.0
self.value = 0.0
cdef class Bias(Indicator):
"""
Rate of change between the source and a moving average.
Parameters
----------
period : int
The rolling window period for the indicator (> 0).
ma_type : MovingAverageType
The moving average type for the indicator (cannot be None).
"""
def __init__(
self,
int period,
MovingAverageType ma_type=MovingAverageType.SIMPLE,
):
Condition.positive_int(period, "period")
params = [
period,
get_ma_type_name(ma_type),
]
super().__init__(params=params)
self.period = period
self._ma = MovingAverageFactory.create(period, ma_type)
self.value = 0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(
bar.close.as_double(),
)
cpdef void update_raw(self, double close):
"""
Update the indicator with the given raw values.
Parameters
----------
close : double
The close price.
"""
# Calculate average
self._ma.update_raw(close)
self.value = (close / self._ma.value) - 1.0
self._check_initialized()
cdef void _check_initialized(self):
if not self.initialized:
self._set_has_inputs(True)
if self._ma.initialized:
self._set_initialized(True)
cpdef void _reset(self):
self._ma.reset()
self.value = 0
cdef class Swings(Indicator):
"""
A swing indicator which calculates and stores various swing metrics.
Parameters
----------
period : int
The rolling window period for the indicator (> 0).
"""
def __init__(self, int period):
Condition.positive_int(period, "period")
super().__init__(params=[period])
self.period = period
self._high_inputs = deque(maxlen=self.period)
self._low_inputs = deque(maxlen=self.period)
self.direction = 0
self.changed = False
self.high_datetime = None
self.low_datetime = None
self.high_price = 0
self.low_price = 0
self.length = 0
self.duration = 0
self.since_high = 0
self.since_low = 0
cpdef void handle_bar(self, Bar bar):
"""
Update the indicator with the given bar.
Parameters
----------
bar : Bar
The update bar.
"""
Condition.not_none(bar, "bar")
self.update_raw(
bar.high.as_double(),
bar.low.as_double(),
pd.Timestamp(bar.ts_init, tz="UTC"),
)
cpdef void update_raw(
self,
double high,
double low,
datetime timestamp,
):
"""
Update the indicator with the given raw values.
Parameters
----------
high : double
The high price.
low : double
The low price.
timestamp : datetime
The current timestamp.
"""
# Update inputs
self._high_inputs.append(high)
self._low_inputs.append(low)
# Update max high and min low
cdef double max_high = max(self._high_inputs)
cdef double min_low = min(self._low_inputs)
# Calculate if swings
cdef bint is_swing_high = high >= max_high and low >= min_low
cdef bint is_swing_low = low <= min_low and high <= max_high
# Swing logic
self.changed = False
if is_swing_high and not is_swing_low:
if self.direction == -1:
self.changed = True
self.high_price = high
self.high_datetime = timestamp
self.direction = 1
self.since_high = 0
self.since_low += 1
elif is_swing_low and not is_swing_high:
if self.direction == 1:
self.changed = True
self.low_price = low
self.low_datetime = timestamp
self.direction = -1
self.since_low = 0
self.since_high += 1
else:
self.since_high += 1
self.since_low += 1
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if self.high_price != 0. and self.low_price != 0.0:
self._set_initialized(True)
# Calculate current values
else:
self.length = self.high_price - self.low_price
if self.direction == 1:
self.duration = self.since_low
else:
self.duration = self.since_high
cpdef void _reset(self):
self._high_inputs.clear()
self._low_inputs.clear()
self.direction = 0
self.changed = False
self.high_datetime = None
self.low_datetime = None
self.high_price = 0
self.low_price = 0
self.length = 0
self.duration = 0
self.since_high = 0
self.since_low = 0