Qubx 0.1.84__cp311-cp311-manylinux_2_35_x86_64.whl → 0.1.86__cp311-cp311-manylinux_2_35_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of Qubx might be problematic. Click here for more details.

qubx/_nb_magic.py CHANGED
@@ -1,7 +1,6 @@
1
1
  """"
2
2
  Here stuff we want to have in every Jupyter notebook after calling %qube magic
3
3
  """
4
- import importlib_metadata
5
4
 
6
5
  import qubx
7
6
  from qubx.utils import runtime_env
@@ -15,11 +14,19 @@ def np_fmt_short():
15
14
 
16
15
  def np_fmt_reset():
17
16
  # reset default np printing options
18
- np.set_printoptions(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan', precision=8,
19
- suppress=False, threshold=1000, formatter=None)
17
+ np.set_printoptions(
18
+ edgeitems=3,
19
+ infstr="inf",
20
+ linewidth=75,
21
+ nanstr="nan",
22
+ precision=8,
23
+ suppress=False,
24
+ threshold=1000,
25
+ formatter=None,
26
+ )
20
27
 
21
28
 
22
- if runtime_env() in ['notebook', 'shell']:
29
+ if runtime_env() in ["notebook", "shell"]:
23
30
 
24
31
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
25
32
  # -- all imports below will appear in notebook after calling %%alphalab magic ---
@@ -39,19 +46,18 @@ if runtime_env() in ['notebook', 'shell']:
39
46
  # - - - - Learn stuff - - - -
40
47
  # - - - - Charting stuff - - - -
41
48
  from matplotlib import pyplot as plt
42
- from qubx.utils.charting.mpl_helpers import fig, subplot, sbp
49
+ from qubx.utils.charting.mpl_helpers import fig, subplot, sbp, plot_trends, ohlc_plot
43
50
 
44
51
  # - - - - Utils - - - -
45
52
  from qubx.pandaz.utils import scols, srows, ohlc_resample, continuous_periods, generate_equal_date_ranges
46
53
 
47
54
  # - setup short numpy output format
48
55
  np_fmt_short()
49
-
56
+
50
57
  # - add project home to system path
51
58
  add_project_to_system_path()
52
59
 
53
60
  # show logo first time
54
- if not hasattr(qubx.QubxMagics, '__already_initialized__'):
61
+ if not hasattr(qubx.QubxMagics, "__already_initialized__"):
55
62
  setattr(qubx.QubxMagics, "__already_initialized__", True)
56
63
  logo()
57
-
qubx/core/series.pxd CHANGED
@@ -15,7 +15,7 @@ cdef class TimeSeries:
15
15
  cdef public long long timeframe
16
16
  cdef public Indexed times
17
17
  cdef public Indexed values
18
- cdef float max_series_length
18
+ cdef public float max_series_length
19
19
  cdef unsigned short _is_new_item
20
20
  cdef public str name
21
21
  cdef dict indicators # it's used for indicators caching
@@ -28,8 +28,12 @@ cdef class TimeSeries:
28
28
 
29
29
 
30
30
  cdef class Indicator(TimeSeries):
31
- cdef TimeSeries series
32
- cdef TimeSeries parent
31
+ cdef public TimeSeries series
32
+ cdef public TimeSeries parent
33
+
34
+
35
+ cdef class IndicatorOHLC(Indicator):
36
+ pass
33
37
 
34
38
 
35
39
  cdef class RollingSum:
qubx/core/series.pyx CHANGED
@@ -142,6 +142,14 @@ cdef class TimeSeries:
142
142
  def __len__(self) -> int:
143
143
  return len(self.times)
144
144
 
145
+ def loc(self, str t):
146
+ _t = np.datetime64(t, 'ns').item()
147
+ ix = int(np.searchsorted(self.times.values, _t, side='right'))
148
+ ix = min(ix, len(self.values))
149
+ if ix == 0:
150
+ raise ValueError(f"Time {t} not found in {self.name} !")
151
+ return np.datetime64(self.times.values[ix - 1], 'ns'), self.values.values[ix - 1]
152
+
145
153
  def _on_attach_indicator(self, indicator: Indicator, indicator_input: TimeSeries):
146
154
  self.calculation_order.append((
147
155
  id(indicator_input), indicator, id(indicator)
@@ -169,7 +177,7 @@ cdef class TimeSeries:
169
177
  # - disable first notification because first item may be incomplete
170
178
  self._is_new_item = False
171
179
 
172
- elif time - self.times[0] >= self.timeframe:
180
+ elif (_dt := time - self.times[0]) >= self.timeframe:
173
181
  # - add new item
174
182
  self._add_new_item(item_start_time, value)
175
183
 
@@ -186,6 +194,8 @@ cdef class TimeSeries:
186
194
 
187
195
  return self._is_new_item
188
196
  else:
197
+ if _dt < 0:
198
+ raise ValueError(f"Attempt to update past data at {time_to_str(time)} !")
189
199
  self._update_last_item(item_start_time, value)
190
200
 
191
201
  # - update indicators by new data
@@ -300,6 +310,9 @@ def _wrap_indicator(series: TimeSeries, clz, *args, **kwargs):
300
310
 
301
311
 
302
312
  cdef class Indicator(TimeSeries):
313
+ """
314
+ Basic class for indicator that can be attached to TimeSeries
315
+ """
303
316
 
304
317
  def __init__(self, str name, TimeSeries series):
305
318
  if not name:
@@ -309,7 +322,7 @@ cdef class Indicator(TimeSeries):
309
322
  self.name = name
310
323
 
311
324
  # - we need to make a empty copy and fill it
312
- self.series = TimeSeries(series.name, series.timeframe, series.max_series_length)
325
+ self.series = self._instantiate_base_series(series.name, series.timeframe, series.max_series_length)
313
326
  self.parent = series
314
327
 
315
328
  # - notify the parent series that indicator has been attached
@@ -318,6 +331,9 @@ cdef class Indicator(TimeSeries):
318
331
  # - recalculate indicator on data as if it would being streamed
319
332
  self._initial_data_recalculate(series)
320
333
 
334
+ def _instantiate_base_series(self, str name, long long timeframe, float max_series_length):
335
+ return TimeSeries(name, timeframe, max_series_length)
336
+
321
337
  def _on_attach_indicator(self, indicator: Indicator, indicator_input: TimeSeries):
322
338
  self.parent._on_attach_indicator(indicator, indicator_input)
323
339
 
@@ -345,6 +361,17 @@ cdef class Indicator(TimeSeries):
345
361
  return _wrap_indicator(series, clz, *args, **kwargs)
346
362
 
347
363
 
364
+ cdef class IndicatorOHLC(Indicator):
365
+ """
366
+ Extension of indicator class to be used for OHLCV series
367
+ """
368
+ def _instantiate_base_series(self, str name, long long timeframe, float max_series_length):
369
+ return OHLCV(name, timeframe, max_series_length)
370
+
371
+ def calculate(self, long long time, Bar value, short new_item_started) -> object:
372
+ raise ValueError("Indicator must implement calculate() method")
373
+
374
+
348
375
  cdef class Lag(Indicator):
349
376
  cdef int period
350
377
 
@@ -729,7 +756,7 @@ cdef class OHLCV(TimeSeries):
729
756
  # Here we disable first notification because first item may be incomplete
730
757
  self._is_new_item = False
731
758
 
732
- elif time - self.times[0] >= self.timeframe:
759
+ elif (_dt := time - self.times[0]) >= self.timeframe:
733
760
  b = Bar(bar_start_time, price, price, price, price, volume, bvolume)
734
761
 
735
762
  # - add new item
@@ -740,6 +767,9 @@ cdef class OHLCV(TimeSeries):
740
767
 
741
768
  return self._is_new_item
742
769
  else:
770
+ if _dt < 0:
771
+ raise ValueError(f"Attempt to update past data at {time_to_str(time)} !")
772
+
743
773
  self._update_last_item(bar_start_time, self[0].update(price, volume, bvolume))
744
774
 
745
775
  # - update indicators by new data
qubx/core/utils.pyx CHANGED
@@ -50,5 +50,5 @@ cpdef recognize_timeframe(timeframe):
50
50
  tf = np.int64(timeframe.item().total_seconds() * NS)
51
51
 
52
52
  else:
53
- raise ValueError('Unknown timeframe type !')
53
+ raise ValueError(f'Unknown timeframe type: {timeframe} !')
54
54
  return tf
qubx/math/__init__.py CHANGED
@@ -1 +1 @@
1
- from .math import percentile_rank
1
+ from .stats import compare_to_norm, percentile_rank, kde
qubx/math/stats.py CHANGED
@@ -30,13 +30,30 @@ def compare_to_norm(xs, xranges=None):
30
30
  fit = stats.norm.pdf(sorted(xs), _m, _s)
31
31
 
32
32
  sbp(12, 1)
33
- plt.plot(sorted(xs), fit, 'r--', lw=2, label='N(%.2f, %.2f)' % (_m, _s))
34
- plt.legend(loc='upper right')
33
+ plt.plot(sorted(xs), fit, "r--", lw=2, label="N(%.2f, %.2f)" % (_m, _s))
34
+ plt.legend(loc="upper right")
35
35
 
36
- sns.kdeplot(xs, color='g', label='Data', shade=True)
36
+ sns.kdeplot(xs, color="g", label="Data", fill=True)
37
37
  if xranges is not None and len(xranges) > 1:
38
38
  plt.xlim(xranges)
39
- plt.legend(loc='upper right')
39
+ plt.legend(loc="upper right")
40
40
 
41
41
  sbp(12, 2)
42
42
  stats.probplot(xs, dist="norm", sparams=(_m, _s), plot=plt)
43
+
44
+
45
+ def kde(array, cut_down=True, bw_method="scott"):
46
+ """
47
+ Kernel dense estimation
48
+ """
49
+ from scipy.stats import gaussian_kde
50
+
51
+ if cut_down:
52
+ bins, counts = np.unique(array, return_counts=True)
53
+ f_mean = counts.mean()
54
+ f_above_mean = bins[counts > f_mean]
55
+ if len(f_above_mean) > 0:
56
+ bounds = [f_above_mean.min(), f_above_mean.max()]
57
+ array = array[np.bitwise_and(bounds[0] < array, array < bounds[1])]
58
+
59
+ return gaussian_kde(array, bw_method=bw_method)