-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Expand file tree
/
Copy pathvolume.pyx
More file actions
443 lines (369 loc) · 12.2 KB
/
Copy pathvolume.pyx
File metadata and controls
443 lines (369 loc) · 12.2 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
# -------------------------------------------------------------------------------------------------
# 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
import pandas as pd
from nautilus_trader.indicators.averages import MovingAverageFactory
from nautilus_trader.indicators.volatility import AverageTrueRange
from cpython.datetime cimport datetime
from nautilus_trader.core.correctness cimport Condition
from nautilus_trader.indicators.averages cimport MovingAverageType
from nautilus_trader.indicators.base cimport Indicator
from nautilus_trader.model.data cimport Bar
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"
cdef class OnBalanceVolume(Indicator):
"""
An indicator which calculates the momentum of relative positive or negative
volume.
Parameters
----------
period : int
The period for the indicator, zero indicates no window (>= 0).
Raises
------
ValueError
If `period` is negative (< 0).
"""
def __init__(self, int period=0):
Condition.not_negative(period, "period")
super().__init__(params=[period])
self.period = period
self._obv = deque(maxlen=None if period == 0 else period)
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.open.as_double(),
bar.close.as_double(),
bar.volume.as_double(),
)
cpdef void update_raw(
self,
double open,
double close,
double volume,
):
"""
Update the indicator with the given raw values.
Parameters
----------
open : double
The high price.
close : double
The low price.
volume : double
The close price.
"""
if close > open:
self._obv.append(volume)
elif close < open:
self._obv.append(-volume)
else:
self._obv.append(0)
self.value = sum(self._obv)
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if (self.period == 0 and len(self._obv) > 0) or len(self._obv) >= self.period:
self._set_initialized(True)
cpdef void _reset(self):
self._obv.clear()
self.value = 0
cdef class VolumeWeightedAveragePrice(Indicator):
"""
An indicator which calculates the volume weighted average price for the day.
"""
def __init__(self):
super().__init__(params=[])
self._day = 0
self._price_volume = 0
self._volume_total = 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.close.as_double() +
bar.high.as_double() +
bar.low.as_double()
) / 3.0,
bar.volume.as_double(),
pd.Timestamp(bar.ts_init, tz="UTC"),
)
cpdef void update_raw(
self,
double price,
double volume,
datetime timestamp,
):
"""
Update the indicator with the given raw values.
Parameters
----------
price : double
The update price.
volume : double
The update volume.
timestamp : datetime
The current timestamp.
"""
# On a new day reset the indicator
if timestamp.day != self._day:
self.reset()
self._day = timestamp.day
self.value = price
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
self._set_initialized(True)
# No weighting for this price (also avoiding divide by zero)
if volume == 0:
return
self._price_volume += price * volume
self._volume_total += volume
self.value = self._price_volume / self._volume_total
cpdef void _reset(self):
self._day = 0
self._price_volume = 0
self._volume_total = 0
self.value = 0
cdef class KlingerVolumeOscillator(Indicator):
"""
This indicator was developed by Stephen J. Klinger. It is designed to predict
price reversals in a market by comparing volume to price.
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 the moving average difference's moving average (> 0).
ma_type : MovingAverageType
The moving average type for the calculations.
"""
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._signal_ma = MovingAverageFactory.create(signal_period, ma_type)
self._hlc3 = 0
self._previous_hlc3 = 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(),
bar.close.as_double(),
bar.volume.as_double(),
)
cpdef void update_raw(
self,
double high,
double low,
double close,
double volume,
):
"""
Update the indicator with the given raw values.
Parameters
----------
high : double
The high price.
low : double
The low price.
close : double
The close price.
volume : double
The volume.
"""
self._hlc3 = (high + low + close)/3.0
if self._hlc3 > self._previous_hlc3:
self._fast_ma.update_raw(volume)
self._slow_ma.update_raw(volume)
elif self._hlc3 < self._previous_hlc3:
self._fast_ma.update_raw(-volume)
self._slow_ma.update_raw(-volume)
else:
self._fast_ma.update_raw(0)
self._slow_ma.update_raw(0)
if self._slow_ma.initialized:
self._signal_ma.update_raw(self._fast_ma.value - self._slow_ma.value)
self.value = self._signal_ma.value
# Initialization logic
if not self.initialized:
self._set_has_inputs(True)
if self._signal_ma.initialized:
self._set_initialized(True)
self._previous_hlc3 = self._hlc3
cpdef void _reset(self):
self._fast_ma.reset()
self._slow_ma.reset()
self._signal_ma.reset()
self._hlc3 = 0
self._previous_hlc3 = 0
self.value = 0
cdef class Pressure(Indicator):
"""
An indicator which calculates the relative volume (multiple of average volume)
to move the market across a relative range (multiple of ATR).
Parameters
----------
period : int
The period for the indicator (> 0).
ma_type : MovingAverageType
The moving average type for the calculations.
atr_floor : double
The ATR floor (minimum) output value for the indicator (>= 0.).
Raises
------
ValueError
If `period` is not positive (> 0).
ValueError
If `atr_floor` is negative (< 0).
"""
def __init__(
self,
int period,
MovingAverageType ma_type=MovingAverageType.EXPONENTIAL,
double atr_floor=0,
):
Condition.positive_int(period, "period")
Condition.not_negative(atr_floor, "atr_floor")
params=[
period,
get_ma_type_name(ma_type),
atr_floor,
]
super().__init__(params=params)
self.period = period
self._atr = AverageTrueRange(period, ma_type, True, atr_floor)
self._average_volume = MovingAverageFactory.create(period, ma_type)
self.value = 0
self.value_cumulative = 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(),
bar.close.as_double(),
bar.volume.as_double(),
)
cpdef void update_raw(
self,
double high,
double low,
double close,
double volume,
):
"""
Update the indicator with the given raw values.
Parameters
----------
high : double
The high price.
low : double
The low price.
close : double
The close price.
volume : double
The volume.
"""
self._atr.update_raw(high, low, close)
self._average_volume.update_raw(volume)
# Initialization logic (do not move this to the bottom as guard against zero will return)
if not self.initialized:
self._set_has_inputs(True)
if self._atr.initialized:
self._set_initialized(True)
# Guard against zero values
if self._average_volume.value == 0 or self._atr.value == 0:
self.value = 0
return
cdef double relative_volume = volume / self._average_volume.value
cdef double buy_pressure = ((close - low) / self._atr.value) * relative_volume
cdef double sell_pressure = ((high - close) / self._atr.value) * relative_volume
self.value = buy_pressure - sell_pressure
self.value_cumulative += self.value
cpdef void _reset(self):
self._atr.reset()
self._average_volume.reset()
self.value = 0
self.value_cumulative = 0