onetick-py 1.177.0__py3-none-any.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.
Files changed (152) hide show
  1. locator_parser/__init__.py +0 -0
  2. locator_parser/acl.py +73 -0
  3. locator_parser/actions.py +262 -0
  4. locator_parser/common.py +368 -0
  5. locator_parser/io.py +43 -0
  6. locator_parser/locator.py +150 -0
  7. onetick/__init__.py +101 -0
  8. onetick/doc_utilities/__init__.py +3 -0
  9. onetick/doc_utilities/napoleon.py +40 -0
  10. onetick/doc_utilities/ot_doctest.py +140 -0
  11. onetick/doc_utilities/snippets.py +279 -0
  12. onetick/lib/__init__.py +4 -0
  13. onetick/lib/instance.py +141 -0
  14. onetick/py/__init__.py +293 -0
  15. onetick/py/_stack_info.py +89 -0
  16. onetick/py/_version.py +2 -0
  17. onetick/py/aggregations/__init__.py +11 -0
  18. onetick/py/aggregations/_base.py +648 -0
  19. onetick/py/aggregations/_docs.py +948 -0
  20. onetick/py/aggregations/compute.py +286 -0
  21. onetick/py/aggregations/functions.py +2216 -0
  22. onetick/py/aggregations/generic.py +104 -0
  23. onetick/py/aggregations/high_low.py +80 -0
  24. onetick/py/aggregations/num_distinct.py +83 -0
  25. onetick/py/aggregations/order_book.py +501 -0
  26. onetick/py/aggregations/other.py +1014 -0
  27. onetick/py/backports.py +26 -0
  28. onetick/py/cache.py +374 -0
  29. onetick/py/callback/__init__.py +5 -0
  30. onetick/py/callback/callback.py +276 -0
  31. onetick/py/callback/callbacks.py +131 -0
  32. onetick/py/compatibility.py +798 -0
  33. onetick/py/configuration.py +771 -0
  34. onetick/py/core/__init__.py +0 -0
  35. onetick/py/core/_csv_inspector.py +93 -0
  36. onetick/py/core/_internal/__init__.py +0 -0
  37. onetick/py/core/_internal/_manually_bound_value.py +6 -0
  38. onetick/py/core/_internal/_nodes_history.py +250 -0
  39. onetick/py/core/_internal/_op_utils/__init__.py +0 -0
  40. onetick/py/core/_internal/_op_utils/every_operand.py +9 -0
  41. onetick/py/core/_internal/_op_utils/is_const.py +10 -0
  42. onetick/py/core/_internal/_per_tick_scripts/tick_list_sort_template.script +121 -0
  43. onetick/py/core/_internal/_proxy_node.py +140 -0
  44. onetick/py/core/_internal/_state_objects.py +2312 -0
  45. onetick/py/core/_internal/_state_vars.py +93 -0
  46. onetick/py/core/_source/__init__.py +0 -0
  47. onetick/py/core/_source/_symbol_param.py +95 -0
  48. onetick/py/core/_source/schema.py +97 -0
  49. onetick/py/core/_source/source_methods/__init__.py +0 -0
  50. onetick/py/core/_source/source_methods/aggregations.py +809 -0
  51. onetick/py/core/_source/source_methods/applyers.py +296 -0
  52. onetick/py/core/_source/source_methods/columns.py +141 -0
  53. onetick/py/core/_source/source_methods/data_quality.py +301 -0
  54. onetick/py/core/_source/source_methods/debugs.py +272 -0
  55. onetick/py/core/_source/source_methods/drops.py +120 -0
  56. onetick/py/core/_source/source_methods/fields.py +619 -0
  57. onetick/py/core/_source/source_methods/filters.py +1002 -0
  58. onetick/py/core/_source/source_methods/joins.py +1413 -0
  59. onetick/py/core/_source/source_methods/merges.py +605 -0
  60. onetick/py/core/_source/source_methods/misc.py +1455 -0
  61. onetick/py/core/_source/source_methods/pandases.py +155 -0
  62. onetick/py/core/_source/source_methods/renames.py +356 -0
  63. onetick/py/core/_source/source_methods/sorts.py +183 -0
  64. onetick/py/core/_source/source_methods/switches.py +142 -0
  65. onetick/py/core/_source/source_methods/symbols.py +117 -0
  66. onetick/py/core/_source/source_methods/times.py +627 -0
  67. onetick/py/core/_source/source_methods/writes.py +986 -0
  68. onetick/py/core/_source/symbol.py +205 -0
  69. onetick/py/core/_source/tmp_otq.py +222 -0
  70. onetick/py/core/column.py +209 -0
  71. onetick/py/core/column_operations/__init__.py +0 -0
  72. onetick/py/core/column_operations/_methods/__init__.py +4 -0
  73. onetick/py/core/column_operations/_methods/_internal.py +28 -0
  74. onetick/py/core/column_operations/_methods/conversions.py +216 -0
  75. onetick/py/core/column_operations/_methods/methods.py +292 -0
  76. onetick/py/core/column_operations/_methods/op_types.py +160 -0
  77. onetick/py/core/column_operations/accessors/__init__.py +0 -0
  78. onetick/py/core/column_operations/accessors/_accessor.py +28 -0
  79. onetick/py/core/column_operations/accessors/decimal_accessor.py +104 -0
  80. onetick/py/core/column_operations/accessors/dt_accessor.py +537 -0
  81. onetick/py/core/column_operations/accessors/float_accessor.py +184 -0
  82. onetick/py/core/column_operations/accessors/str_accessor.py +1367 -0
  83. onetick/py/core/column_operations/base.py +1121 -0
  84. onetick/py/core/cut_builder.py +150 -0
  85. onetick/py/core/db_constants.py +20 -0
  86. onetick/py/core/eval_query.py +245 -0
  87. onetick/py/core/lambda_object.py +441 -0
  88. onetick/py/core/multi_output_source.py +232 -0
  89. onetick/py/core/per_tick_script.py +2256 -0
  90. onetick/py/core/query_inspector.py +464 -0
  91. onetick/py/core/source.py +1744 -0
  92. onetick/py/db/__init__.py +2 -0
  93. onetick/py/db/_inspection.py +1128 -0
  94. onetick/py/db/db.py +1327 -0
  95. onetick/py/db/utils.py +64 -0
  96. onetick/py/docs/__init__.py +0 -0
  97. onetick/py/docs/docstring_parser.py +112 -0
  98. onetick/py/docs/utils.py +81 -0
  99. onetick/py/functions.py +2398 -0
  100. onetick/py/license.py +190 -0
  101. onetick/py/log.py +88 -0
  102. onetick/py/math.py +935 -0
  103. onetick/py/misc.py +470 -0
  104. onetick/py/oqd/__init__.py +22 -0
  105. onetick/py/oqd/eps.py +1195 -0
  106. onetick/py/oqd/sources.py +325 -0
  107. onetick/py/otq.py +216 -0
  108. onetick/py/pyomd_mock.py +47 -0
  109. onetick/py/run.py +916 -0
  110. onetick/py/servers.py +173 -0
  111. onetick/py/session.py +1347 -0
  112. onetick/py/sources/__init__.py +19 -0
  113. onetick/py/sources/cache.py +167 -0
  114. onetick/py/sources/common.py +128 -0
  115. onetick/py/sources/csv.py +642 -0
  116. onetick/py/sources/custom.py +85 -0
  117. onetick/py/sources/data_file.py +305 -0
  118. onetick/py/sources/data_source.py +1045 -0
  119. onetick/py/sources/empty.py +94 -0
  120. onetick/py/sources/odbc.py +337 -0
  121. onetick/py/sources/order_book.py +271 -0
  122. onetick/py/sources/parquet.py +168 -0
  123. onetick/py/sources/pit.py +191 -0
  124. onetick/py/sources/query.py +495 -0
  125. onetick/py/sources/snapshots.py +419 -0
  126. onetick/py/sources/split_query_output_by_symbol.py +198 -0
  127. onetick/py/sources/symbology_mapping.py +123 -0
  128. onetick/py/sources/symbols.py +374 -0
  129. onetick/py/sources/ticks.py +825 -0
  130. onetick/py/sql.py +70 -0
  131. onetick/py/state.py +251 -0
  132. onetick/py/types.py +2131 -0
  133. onetick/py/utils/__init__.py +70 -0
  134. onetick/py/utils/acl.py +93 -0
  135. onetick/py/utils/config.py +186 -0
  136. onetick/py/utils/default.py +49 -0
  137. onetick/py/utils/file.py +38 -0
  138. onetick/py/utils/helpers.py +76 -0
  139. onetick/py/utils/locator.py +94 -0
  140. onetick/py/utils/perf.py +498 -0
  141. onetick/py/utils/query.py +49 -0
  142. onetick/py/utils/render.py +1374 -0
  143. onetick/py/utils/script.py +244 -0
  144. onetick/py/utils/temp.py +471 -0
  145. onetick/py/utils/types.py +120 -0
  146. onetick/py/utils/tz.py +84 -0
  147. onetick_py-1.177.0.dist-info/METADATA +137 -0
  148. onetick_py-1.177.0.dist-info/RECORD +152 -0
  149. onetick_py-1.177.0.dist-info/WHEEL +5 -0
  150. onetick_py-1.177.0.dist-info/entry_points.txt +2 -0
  151. onetick_py-1.177.0.dist-info/licenses/LICENSE +21 -0
  152. onetick_py-1.177.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,948 @@
1
+ from typing import List, Dict, Union, Optional, Callable, TYPE_CHECKING
2
+ from onetick.py.backports import Literal
3
+
4
+ from functools import wraps
5
+ from inspect import Signature, Parameter
6
+ from onetick.py.core.column import Column
7
+ from onetick.py.core.column_operations.base import Operation, OnetickParameter
8
+ from onetick.py.core._source._symbol_param import _SymbolParamColumn
9
+ from onetick.py.types import OTPBaseTimeOffset
10
+
11
+ if TYPE_CHECKING:
12
+ from onetick.py.core.source import Source # hack for annotations
13
+
14
+ from onetick.py.docs.docstring_parser import Docstring
15
+ from onetick.py.docs.utils import param_doc
16
+ from onetick.py.aggregations.high_low import HighTick, LowTick
17
+
18
+
19
+ _column_doc = param_doc(
20
+ name='column',
21
+ str_annotation='str or Column or Operation',
22
+ desc='''
23
+ String with the name of the column to be aggregated or :py:class:`~onetick.py.Column` object.
24
+ :py:class:`~onetick.py.Operation` object can also be used -- in this case
25
+ the results of this operation for each tick are aggregated
26
+ (see example in :ref:`common aggregation examples <aggregations_funcs>`).
27
+ ''',
28
+ annotation=Union[str, Column, Operation]
29
+ )
30
+
31
+ _running_doc = param_doc(
32
+ name='running',
33
+ desc='''
34
+ See :ref:`Aggregation buckets guide <buckets_guide>` to see examples of how this parameter works.
35
+
36
+ Specifies if the aggregation will be calculated as a sliding window.
37
+ ``running`` and ``bucket_interval`` parameters determines when new buckets are created.
38
+
39
+ * ``running`` = True
40
+
41
+ aggregation will be calculated in a sliding window.
42
+
43
+ * ``bucket_interval`` = N (N > 0)
44
+
45
+ Window size will be N. Output tick will be generated when tick "enter" window (**arrival event**) and
46
+ when "exit" window (**exit event**)
47
+
48
+ * ``bucket_interval`` = 0
49
+
50
+ Left boundary of window will be set to query start time. For each tick aggregation will be calculated in
51
+ the interval [start_time; tick_t] from query start time to the tick's timestamp (inclusive).
52
+
53
+ * ``running`` = False (default)
54
+
55
+ buckets partition the [query start time, query end time) interval into non-overlapping intervals
56
+ of size ``bucket_interval`` (with the last interval possibly of a smaller size).
57
+ If ``bucket_interval`` is set to **0** a single bucket for the entire interval is created.
58
+
59
+ Note that in non-running mode OneTick unconditionally divides the whole time interval
60
+ into specified number of buckets.
61
+ It means that you will always get this specified number of ticks in the result,
62
+ even if you have less ticks in the input data.
63
+
64
+ Default: False
65
+ ''',
66
+ default=False,
67
+ annotation=bool
68
+ )
69
+
70
+ _all_fields_doc = param_doc(
71
+ name='all_fields',
72
+ desc="""
73
+ See :ref:`Aggregation buckets guide <buckets_guide>` to see examples of how this parameter works.
74
+
75
+ * ``all_fields`` = True
76
+
77
+ output ticks include all fields from the input ticks
78
+
79
+ * ``running`` = True
80
+
81
+ an output tick is created only when a tick enters the sliding window
82
+
83
+ * ``running`` = False
84
+
85
+ fields of first tick in bucket will be used
86
+
87
+ * ``all_fields`` = False and ``running`` = True
88
+
89
+ output ticks are created when a tick enters or leaves the sliding window.
90
+
91
+ * ``all_fields`` = "when_ticks_exit_window" and ``running`` = True
92
+
93
+ output ticks are generated only for exit events, but all attributes from the exiting tick are copied over
94
+ to the output tick and the aggregation is added as another attribute.
95
+ """,
96
+ default=False,
97
+ annotation=Union[bool, str]
98
+ )
99
+ _all_fields_with_policy_doc = param_doc(
100
+ name='all_fields',
101
+ desc="""
102
+ See :ref:`Aggregation buckets guide <buckets_guide>` to see examples of how this parameter works.
103
+
104
+ - If ``all_fields`` False - output tick will have only aggregation fields.
105
+
106
+ - If ``all_fields`` is True and ``running`` is False - additional fields will be copied from the first
107
+ tick in the bucket to the output tick.
108
+
109
+ - If ``all_fields`` False and ``running`` True - output ticks are created when a tick enters or leaves the
110
+ sliding window.
111
+
112
+ - If ``all_fields`` True and ``running`` True - an output tick is generated only for arrival events,
113
+ but all attributes from the input tick causing an arrival event are copied over to the output tick
114
+ and the aggregation is added as another attribute.
115
+
116
+ - If ``all_fields`` True and ``running`` "when_ticks_exit_window" -
117
+ an output tick is generated only for exit events,
118
+ but all attributes from the exiting tick are copied over to the output tick
119
+ and the aggregation is added as another attribute.
120
+
121
+ - If ``all_fields`` set to "first", "last", "high", or "low" - explicitly set tick selection policy for all
122
+ fields values. For "high" and "low" "PRICE" field will be selected as an input.
123
+ Otherwise, you will get the runtime error.
124
+ If ``all_fields`` is set to one of these values, ``running`` can't be `True`.
125
+
126
+ - If ``all_fields`` is aggregation ``HighTick`` or ``LowTick`` - set tick selection policy for all fields values to
127
+ "high" or "low" accordingly. But instead of "PRICE" the field selected as input will be set as aggregation's
128
+ first parameter.
129
+ """,
130
+ default=False,
131
+ str_annotation=("True, False, 'when_ticks_exit_window', 'first', 'last', 'high', 'low', "
132
+ ":py:func:`~onetick.py.agg.high_tick`, :py:func:`~onetick.py.agg.low_tick`"),
133
+ )
134
+ _bucket_interval_doc = param_doc(
135
+ name='bucket_interval',
136
+ desc="""
137
+ Determines the length of each bucket (units depends on ``bucket_units``).
138
+
139
+ If :py:class:`~onetick.py.Operation` of bool type is passed, acts as ``bucket_end_condition``.
140
+
141
+ Bucket interval can also be set as a *float* value
142
+ if ``bucket_units`` is set to *seconds*.
143
+ Note that values less than 0.001 (1 millisecond) are not supported.
144
+
145
+ Bucket interval can be set via some of the :ref:`datetime offset objects <datetime_offsets>`:
146
+ :py:func:`otp.Milli <onetick.py.Milli>`, :py:func:`otp.Second <onetick.py.Second>`,
147
+ :py:func:`otp.Minute <onetick.py.Minute>`, :py:func:`otp.Hour <onetick.py.Hour>`,
148
+ :py:func:`otp.Day <onetick.py.Day>`, :py:func:`otp.Month <onetick.py.Month>`.
149
+ In this case you could omit setting ``bucket_units`` parameter.
150
+
151
+ Bucket interval can also be set with integer :py:class:`~onetick.py.core.column_operations.base.OnetickParameter`
152
+ or :py:meth:`symbol parameter <onetick.py.core._source.symbol.SymbolType.__getitem__>`.
153
+ """,
154
+ default=0,
155
+ annotation=Union[int, float, Operation, OnetickParameter, _SymbolParamColumn, OTPBaseTimeOffset],
156
+ str_annotation=('int or float or :py:class:`~onetick.py.Operation`'
157
+ ' or :py:class:`~onetick.py.core.column_operations.base.OnetickParameter`'
158
+ ' or :py:meth:`symbol parameter <onetick.py.core._source.symbol.SymbolType.__getitem__>`'
159
+ ' or :ref:`datetime offset object <datetime_offsets>`'),
160
+ )
161
+ _bucket_time_doc = param_doc(
162
+ name='bucket_time',
163
+ desc="""
164
+ Control output timestamp.
165
+
166
+ * **start**
167
+
168
+ the timestamp assigned to the bucket is the start time of the bucket.
169
+
170
+ * **end**
171
+
172
+ the timestamp assigned to the bucket is the end time of the bucket.
173
+ """,
174
+ default="end",
175
+ annotation=Literal["start", "end"]
176
+ )
177
+ _bucket_units_doc_kwargs = dict(
178
+ name='bucket_units',
179
+ desc="""
180
+ Set bucket interval units.
181
+
182
+ By default, if ``bucket_units`` and ``bucket_end_condition`` not specified, set to **seconds**.
183
+ If ``bucket_end_condition`` specified, then ``bucket_units`` set to **flexible**.
184
+
185
+ If set to **flexible** then ``bucket_end_condition`` must be set.
186
+
187
+ Note that **seconds** bucket unit doesn't take into account daylight-saving time of the timezone,
188
+ so you may not get expected results when using, for example, 24 * 60 * 60 seconds as bucket interval.
189
+ In such case use **days** bucket unit instead.
190
+ See example in :py:func:`onetick.py.agg.sum`.
191
+ """,
192
+ default=None,
193
+ annotation=Optional[Literal["seconds", "ticks", "days", "months", "flexible"]]
194
+ )
195
+ _bucket_units_doc = param_doc(**_bucket_units_doc_kwargs)
196
+ _bucket_units_ob_doc = param_doc(**{
197
+ **_bucket_units_doc_kwargs,
198
+ # OB eps do not support 'ticks' bucket units
199
+ 'annotation': Optional[Literal["seconds", "days", "months", "flexible"]]
200
+ })
201
+
202
+ _bucket_end_condition_doc = param_doc(
203
+ name='bucket_end_condition',
204
+ str_annotation='condition',
205
+ desc='''
206
+ An expression that is evaluated on every tick. If it evaluates to "True", then a new bucket is created.
207
+ This parameter is only used if ``bucket_units`` is set to "flexible".
208
+
209
+ Also can be set via ``bucket_interval`` parameter by passing :py:class:`~onetick.py.Operation` object.
210
+ ''',
211
+ annotation=Optional[Operation],
212
+ default=None
213
+ )
214
+ _end_condition_per_group_doc = param_doc(
215
+ name='end_condition_per_group',
216
+ desc='''
217
+ Controls application of ``bucket_end_condition`` in groups.
218
+
219
+ * ``end_condition_per_group`` = True
220
+
221
+ ``bucket_end_condition`` is applied only to the group defined by ``group_by``
222
+
223
+ * ``end_condition_per_group`` = False
224
+
225
+ ``bucket_end_condition`` applied across all groups
226
+
227
+ This parameter is only used if ``bucket_units`` is set to "flexible".
228
+
229
+ When set to True, applies to all bucketing conditions. Useful, for example, if you need to specify ``group_by``,
230
+ and you want to group items first, and create buckets after that.
231
+ ''',
232
+ annotation=bool,
233
+ default=False
234
+ )
235
+ _boundary_tick_bucket_doc = param_doc(
236
+ name='boundary_tick_bucket',
237
+ desc='''
238
+ Controls boundary tick ownership.
239
+
240
+ * **previous**
241
+
242
+ A tick on which ``bucket_end_condition`` evaluates to "true" belongs to the bucket being closed.
243
+
244
+ * **new**
245
+
246
+ tick belongs to the new bucket.
247
+
248
+ This parameter is only used if ``bucket_units`` is set to "flexible"
249
+ ''',
250
+ annotation=Literal["new", "previous"],
251
+ default="new"
252
+ )
253
+ _group_by_doc = param_doc(
254
+ name='group_by',
255
+ str_annotation='list, str or expression',
256
+ desc='''
257
+ When specified, each bucket is broken further into additional sub-buckets based on specified field values.
258
+ If :py:class:`~onetick.py.Operation` is used then GROUP_{i} column is added. Where i is index in group_by list.
259
+ For example, if Operation is the only element in ``group_by`` list then GROUP_0 field will be added.
260
+ ''',
261
+ annotation=Optional[Union[List, str, Operation]],
262
+ default=None
263
+ )
264
+ _groups_to_display_doc = param_doc(
265
+ name='groups_to_display',
266
+ desc='''
267
+ Specifies for which sub-buckets (groups) ticks should be shown for each bucket interval.
268
+ By default **all** groups are shown at the end of each bucket interval.
269
+ If this parameter is set to **event_in_last_bucket**, only the groups that received at least one tick
270
+ within a given bucket interval are shown.
271
+ ''',
272
+ annotation=Literal["all", "previous"],
273
+ default="all",
274
+ )
275
+ _biased_doc = param_doc(
276
+ name='biased',
277
+ annotation=bool,
278
+ desc='''
279
+ Switches between biased and unbiased standard deviation calculation.
280
+ ''',
281
+ default=True
282
+ )
283
+ _n_doc = param_doc(
284
+ name='n',
285
+ default=1,
286
+ desc='''
287
+ Number of ticks to output''',
288
+ annotation=int
289
+ )
290
+ _keep_timestamp_doc = param_doc(
291
+ name='keep_timestamp',
292
+ desc="""
293
+ If True, timestamps of the output ticks are the same as timestamps of the original ticks.
294
+ Otherwise, timestamps of the output ticks are determined by bucket_time, and original timestamps
295
+ are put in the TICK_TIME field.
296
+ """,
297
+ annotation=bool,
298
+ default=True
299
+ )
300
+ _time_series_type_common = dict(
301
+ name='time_series_type',
302
+ desc='''
303
+ Controls initial value for each bucket
304
+
305
+ * **event_ts**
306
+
307
+ only ticks from current bucket used for calculations
308
+
309
+ * **state_ts**
310
+
311
+ * if there is a tick in bucket with timestamp = bucket start
312
+
313
+ only ticks in bucket used for calculation max value
314
+ * else
315
+
316
+ latest tick from previous bucket included in current bucket
317
+ ''',
318
+ annotation=Literal["event_ts", "state_ts"],
319
+ )
320
+ _time_series_type_doc = param_doc(
321
+ default="event_ts",
322
+ **_time_series_type_common,
323
+ )
324
+ _time_series_type_w_doc = param_doc(
325
+ default="state_ts",
326
+ **_time_series_type_common,
327
+ )
328
+ _selection_doc = param_doc(
329
+ name='selection',
330
+ desc='''
331
+ Controls the selection of the respective beginning or trailing part of ticks.
332
+ ''',
333
+ annotation=Literal["first", "last"],
334
+ default="first"
335
+ )
336
+ _side_doc = param_doc(
337
+ name='side',
338
+ desc="""
339
+ Specifies whether the function is to be applied to sell orders (ASK), buy orders (BID), or both (empty).
340
+ """,
341
+ annotation=Literal['ASK', 'BID'],
342
+ default=None,
343
+ )
344
+ _max_levels_doc = param_doc(
345
+ name='max_levels',
346
+ desc="""
347
+ Number of order book levels (between 1 and 100_000) that need to be computed.
348
+ If empty, all levels will be computed.
349
+ """,
350
+ annotation=int,
351
+ default=None,
352
+ )
353
+ _min_levels_doc = param_doc(
354
+ name='min_levels',
355
+ desc="""
356
+ Minimum number of order book levels, if so many levels are available in the book,
357
+ that need to be included into the computation when either ``max_depth_shares`` or/and ``max_depth_for_price``
358
+ are specified
359
+ """,
360
+ annotation=int,
361
+ default=None,
362
+ )
363
+ _max_depth_shares_doc = param_doc(
364
+ name='max_depth_shares',
365
+ desc="""
366
+ The total number of shares (i.e., the combined SIZE across top several levels of the book)
367
+ that determines the number of order book levels that need to be part of the order book computation.
368
+ If that number of levels exceeds `max_levels`, only `max_levels` levels of the book will be computed.
369
+ The shares in excess of `max_depth_shares`, from the last included level, are not taken into account.
370
+ """,
371
+ annotation=int,
372
+ default=None,
373
+ )
374
+ _max_depth_for_price_doc = param_doc(
375
+ name='max_depth_for_price',
376
+ desc="""
377
+ The multiplier, product of which with the price at the top level of the book determines maximum price distance
378
+ from the top of the book for the levels that are to be included into the book.
379
+ In other words, only bids at <top_price>*(1-`max_depth_for_price`) and above
380
+ and only asks of <top_price>*(1+`max_depth_for_price`) and less will be returned.
381
+ If the number of the levels that are to be included into the book, according to this criteria,
382
+ exceeds `max_levels`, only `max_levels` levels of the book will be returned.
383
+ """,
384
+ annotation=float,
385
+ default=None,
386
+ )
387
+ _max_spread_doc = param_doc(
388
+ name='max_spread',
389
+ desc="""
390
+ An absolute value, price levels with price that satisfies ``abs(<MID price> - <order price>) <= max_spread/2``
391
+ contribute to computed book. If ``max_spread`` is specified, ``side`` should not be specified.
392
+ Empty book is returned when one side is empty.
393
+ """,
394
+ annotation=float,
395
+ default=None,
396
+ )
397
+ _min_levels_doc = param_doc(
398
+ name='min_levels',
399
+ desc="""
400
+ Minimum number of order book levels, if so many levels are available in the book, that need to be included
401
+ into the computation when either `max_depth_shares` or/and `max_depth_for_price` are specified.
402
+ """,
403
+ annotation=int,
404
+ default=None,
405
+ )
406
+ _max_initialization_days_doc = param_doc(
407
+ name='max_initialization_days',
408
+ desc="""
409
+ This parameter specifies how many days back book event processors should go in order to find
410
+ the latest full state of the book.
411
+ The query will not go back resulting number of days if it finds initial book state earlier.
412
+ When book event processors are used after VIRTUAL_OB EP, this parameter should be set to 0.
413
+ When set, this parameter takes precedence over the configuration parameter BOOKS.MAX_INITIALIZATION_DAYS.
414
+ """,
415
+ annotation=int,
416
+ default=1,
417
+ )
418
+ _book_uncross_method_doc = param_doc(
419
+ name='book_uncross_method',
420
+ desc="""
421
+ When set to "REMOVE_OLDER_CROSSED_LEVELS", all ask levels that have price lower or equal to
422
+ the price of a new bid tick get removed from the book, and all bid levels that have price higher or equal
423
+ to the price of a new ask tick get removed from the book.
424
+ """,
425
+ annotation=Literal['REMOVE_OLDER_CROSSED_LEVELS'],
426
+ default=None,
427
+ )
428
+ _dq_events_that_clear_book_doc = param_doc(
429
+ name='dq_events_that_clear_book',
430
+ desc="""
431
+ A list of names of data quality events arrival of which should clear the order book.
432
+ """,
433
+ annotation=List[str],
434
+ default=None,
435
+ )
436
+ _best_ask_price_field_doc = param_doc(
437
+ name='best_ask_price_field',
438
+ desc="""
439
+ If specified, this parameter represents the name of the field value of which represents the lowest ask price
440
+ starting from which the book ask size is to be computed.
441
+ This value would also be used as the top price, relative to which ``max_depth_for_price`` would be computed.
442
+ """,
443
+ annotation=Union[str, Column],
444
+ default=None,
445
+ )
446
+ _best_bid_price_field_doc = param_doc(
447
+ name='best_bid_price_field',
448
+ desc="""
449
+ If specified, this parameter represents the name of the field value of which represents the highest bid price
450
+ starting from which the book bid size is to be computed.
451
+ This value would also be used as the top price, relative to which ``max_depth_for_price`` would be computed.
452
+ """,
453
+ annotation=Union[str, Column],
454
+ default=None,
455
+ )
456
+ _bucket_interval_ob_num_levels_doc = param_doc(
457
+ name='bucket_interval',
458
+ desc="""
459
+ Determines the length of each bucket in seconds.
460
+
461
+ Bucket interval can be set via :ref:`datetime offset objects <datetime_offsets>`
462
+ like :py:func:`otp.Second <onetick.py.Second>`, :py:func:`otp.Minute <onetick.py.Minute>`,
463
+ :py:func:`otp.Hour <onetick.py.Hour>`, :py:func:`otp.Day <onetick.py.Day>`.
464
+ In this case it will be converted to seconds.
465
+ """,
466
+ default=0,
467
+ annotation=Union[int, OTPBaseTimeOffset],
468
+ str_annotation='int or :ref:`datetime offset object <datetime_offsets>`',
469
+ )
470
+ _identify_source_doc = param_doc(
471
+ name='identify_source',
472
+ desc="""
473
+ When this parameter is set to "true" and the input stream is fed through the VIRTUAL_OB event processor
474
+ (with the QUOTE_SOURCE_FIELDS parameter specified) and `group_by` is not set to be "SOURCE"
475
+ it will separate a tick with the same price from different sources into multiple ticks.
476
+ The parameter can also be used when merging ticks from multiple feeds.
477
+ Each feed going into the merge would need an ADD_FIELD EP source value set for the VALUE parameter,
478
+ where the value would be different for each leg.
479
+ """,
480
+ annotation=bool,
481
+ default=False,
482
+ )
483
+ _show_full_detail_doc = param_doc(
484
+ name='show_full_detail',
485
+ desc="""
486
+ When set to "true" and if the state key of the input ticks consists of some fields besides PRICE,
487
+ output ticks will contain all fields from the input ticks for each price level.
488
+ When set to "false" only PRICE, UPDATE_TIME, SIZE, LEVEL, and BUY_SELL_FLAG fields will be populated.
489
+ Note: setting this flag to "true" has no effect on a time series that does not have a state key.
490
+ """,
491
+ annotation=bool,
492
+ default=False,
493
+ )
494
+ _show_only_changes_doc = param_doc(
495
+ name='show_only_changes',
496
+ desc="""
497
+ When set to true, the output stream carries only changes to the book. The representation is as follows:
498
+ * Changed and added levels are represented by themselves.
499
+ * Deleted levels are shown with a size and level of zero.
500
+
501
+ As with other modes, correct detection of update boundaries may require setting the `book_delimiters` option.
502
+ """,
503
+ annotation=bool,
504
+ default=False,
505
+ )
506
+ _book_delimiters_doc = param_doc(
507
+ name='book_delimiters',
508
+ desc="""
509
+ When set to "D" an extra tick is created after each book.
510
+ Also, an additional column, called DELIMITER, is added to output ticks.
511
+ The extra tick has values of all fields set to the defaults (0,NaN,""),
512
+ except the delimiter field, which is set to "D."
513
+ All other ticks have the DELIMITER set to zero (0).
514
+ """,
515
+ annotation=Literal['D'],
516
+ default=None,
517
+ )
518
+ _state_key_max_inactivity_sec_doc = param_doc(
519
+ name='state_key_max_inactivity_sec',
520
+ desc="""
521
+ If set, specifies in how many seconds after it was added
522
+ a given state key should be automatically removed from the book.
523
+ """,
524
+ annotation=int,
525
+ default=None,
526
+ )
527
+ _size_max_fractional_digits_doc = param_doc(
528
+ name='size_max_fractional_digits',
529
+ desc="""
530
+ Specifies maximum number of digits after dot in SIZE, if SIZE can be fractional.
531
+ """,
532
+ annotation=int,
533
+ default=0,
534
+ )
535
+ _include_market_order_ticks_doc = param_doc(
536
+ name='include_market_order_ticks',
537
+ desc="""
538
+ If set, market order ticks (they have price NaN) are included into the order book,
539
+ and are at the order book's top level.
540
+
541
+ Default is False.
542
+ """,
543
+ annotation=bool,
544
+ default=None,
545
+ )
546
+ _query_fun_doc = param_doc(
547
+ name='query_fun',
548
+ desc="""
549
+ Function that takes :class:`~onetick.py.Source` as a parameter,
550
+ applies some aggregation logic to it
551
+ and returns :class:`~onetick.py.Source` as a result.
552
+ Note that currently only methods that support dynamic symbol change
553
+ could be used in the provided function.
554
+ For example, :meth:`~onetick.py.Source.rename` can't be used.
555
+ If you try to use such methods here, you will get an error during runtime.
556
+ """,
557
+ annotation=Callable,
558
+ )
559
+ _bucket_delimiter_doc = param_doc(
560
+ name='bucket_delimiter',
561
+ desc="""
562
+ When set to ``True`` an extra tick is created after each bucket.
563
+ Also, an additional column, called DELIMITER, is added to output ticks.
564
+ The extra tick has values of all fields set to the defaults (0,NaN,""),
565
+ except the delimiter field, which is set to "D"
566
+ All other ticks have the DELIMITER set to string zero "0".
567
+ """,
568
+ annotation=bool,
569
+ default=False,
570
+ )
571
+ _large_ints_doc = param_doc(
572
+ name='large_ints',
573
+ desc="""
574
+ This parameter should be set
575
+ if the input field of this aggregation may contain integer values that consist of 15 digits or more.
576
+
577
+ Such large integer values cannot be represented by the double type without precision errors
578
+ and thus require special handling.
579
+
580
+ If set to **True** , the input field is expected to be a 64-bit integer number.
581
+ The output field will also have 64-bit integer type.
582
+ When no tick belongs to a given time bucket, the output value is set to a minimum of 64-bit integer.
583
+
584
+ When this parameter set to :py:class:`onetick.py.adaptive`, the aggregation behaves the same way
585
+ as when this parameter is set to True when the input field is a 64-bit integer type,
586
+ and the same way as when this parameter is set to **False** when the input field is not a 64-bit integer type.
587
+ """,
588
+ annotation=bool,
589
+ str_annotation="bool or :py:class:`onetick.py.adaptive`",
590
+ default=False,
591
+ )
592
+ _null_int_val_doc = param_doc(
593
+ name='null_int_val',
594
+ desc="""
595
+ The value of this parameter is considered to be the equivalent of ``NaN``
596
+ when ``large_ints`` is set to ``True`` or
597
+ when ``large_ints`` is set to :py:class:`onetick.py.adaptive` and the input field is a 64-bit integer type.
598
+ """,
599
+ annotation=int,
600
+ default=0,
601
+ )
602
+ _skip_tick_if_doc = param_doc(
603
+ name='skip_tick_if',
604
+ desc="""
605
+ If value of the input field is equal to the value in this parameter,
606
+ this tick is ignored in the aggregation computation.
607
+
608
+ This parameter is currently only supported for numeric fields.
609
+ """,
610
+ annotation=Optional[int],
611
+ default=None,
612
+ )
613
+ _default_tick_doc = param_doc(
614
+ name='default_tick',
615
+ desc="""
616
+ Mapping of input stream field names to some values.
617
+ When set, exactly one tick with specified default values will be created for each empty bucket.
618
+ If default value is specified as ``None``, then fields are initialized to the corresponding "zero" values:
619
+ 0 for integer types, NaN for doubles, empty string for string types, etc.
620
+ """,
621
+ annotation=Optional[dict],
622
+ default=None,
623
+ )
624
+ _decay_doc = param_doc(
625
+ name='decay',
626
+ desc="""
627
+ Weight decay. If **decay_value_type** is set to ``lambda``,
628
+ **decay** provides the value of the **Lambda** variable in the aforementioned formula.
629
+ Otherwise, if **decay_value_type** is set to ``half_life_index``, **decay** specifies the necessary number
630
+ of consecutive ticks, the first one of which would have twice less the weight of the last one.
631
+ The **Lambda** value is then calculated using this number.
632
+ """,
633
+ annotation=float,
634
+ )
635
+ _decay_value_type_common = dict(
636
+ name='decay_value_type',
637
+ desc="""
638
+ The decay value can specified either directly or indirectly, controlled respectively by
639
+ **lambda** and **half_life_index** values of this parameter.
640
+ """,
641
+ annotation=Literal['lambda', 'half_life_index'],
642
+ )
643
+ _decay_value_type_doc = param_doc(
644
+ default='lambda',
645
+ **_decay_value_type_common,
646
+ )
647
+ _decay_value_type_hl_doc = param_doc(
648
+ default='half_life_index',
649
+ **_decay_value_type_common,
650
+ )
651
+ _degree_doc = param_doc(
652
+ name='degree',
653
+ annotation=int,
654
+ desc='''
655
+ The order (degree) of the standardized moment to compute, denoted as k in the description above.
656
+ ''',
657
+ default=3,
658
+ )
659
+ _weight_field_name_doc = param_doc(
660
+ name='weight_field_name',
661
+ str_annotation='Optional, str or Column',
662
+ annotation=Optional[Union[str, Column]],
663
+ desc='''
664
+ The name of the field that contains the current value of weight for a member of the portfolio
665
+ that contributed the tick.
666
+
667
+ You can also specify weight through the value of symbol parameter ``WEIGHT``.
668
+
669
+ If ``weight_field_name`` is specified, all ticks should have the field pointed by this parameter and the value
670
+ of this field is used as the weight.
671
+
672
+ If weights are not specified in any of these ways, and you are running a single-stage query,
673
+ the weights take the default value ``1``.
674
+ ''',
675
+ default='',
676
+ )
677
+ _weight_multiplier_field_name_doc = param_doc(
678
+ name='weight_multiplier_field_name',
679
+ desc="""
680
+ Name of the field, value from which is used for multiplying portfolio value result.
681
+ """,
682
+ annotation=str,
683
+ default='',
684
+ )
685
+ _portfolio_side_doc = param_doc(
686
+ name='side',
687
+ desc="""
688
+ When set to **long**, the price of the portfolio is computed only for the input time series with ``weight > 0``.
689
+
690
+ When set to **short**, the price of the portfolio is computed only for the input time series with ``weight < 0``.
691
+
692
+ When set to **both**, the price of the portfolio is computed for all input time series.
693
+ """,
694
+ annotation=Literal['long', 'short', 'both'],
695
+ default='both',
696
+ )
697
+ _weight_type_doc = param_doc(
698
+ name='weight_type',
699
+ desc="""
700
+ When set to ``absolute``, the portfolio price is computed as the sum of ``input_field_value*weight``
701
+ across all members of the portfolio.
702
+
703
+ When set to ``relative``, the portfolio price is computed as the sum of
704
+ ``input_field_value*weight/sum_of_all_weights`` across all members of the portfolio.
705
+ """,
706
+ annotation=Literal['absolute', 'relative'],
707
+ default='absolute',
708
+ )
709
+ _portfolios_query_doc = param_doc(
710
+ name='portfolios_query',
711
+ desc="""
712
+ A mandatory parameter that the specifies server-side `.otq` file that is expected to return
713
+ mandatory columns ``PORTFOLIO_NAME`` and ``SYMBOL_NAME``,
714
+ as well as an optional columns ``WEIGHT``, ``FX_SYMBOL_NAME`` and ``FX_MULTIPLY``.
715
+
716
+ For a local OneTick server you can pass `otp.Source` objects.
717
+ """,
718
+ str_annotation='str, :class:`Source`',
719
+ )
720
+ _portfolios_query_params_doc = param_doc(
721
+ name='portfolios_query_params',
722
+ desc="""
723
+ An optional parameter that specifies parameters of the query specified in `portfolios_query`.
724
+ """,
725
+ annotation=Union[str, Dict[str, str]],
726
+ default='',
727
+ )
728
+ _portfolio_value_field_name_doc = param_doc(
729
+ name='portfolio_value_field_name',
730
+ desc="""
731
+ List of the names (string with comma-separated list or ``list`` of strings/``Columns``) of the output fields
732
+ which contain computed values of the portfolio.
733
+
734
+ The number of the field names must match the number of the field names listed in the `columns` parameter.
735
+ """,
736
+ annotation=Union[str, List[Union[str, Column]]],
737
+ default='VALUE',
738
+ )
739
+ _columns_portfolio_doc = param_doc(
740
+ name='columns',
741
+ str_annotation='str or list of Column or str',
742
+ desc='''
743
+ A list of the names of the input fields for which portfolio value is computed.
744
+
745
+ Could be set as a comma-separated list of the names or ``list`` of name strings/``Columns`` objects.
746
+ ''',
747
+ annotation=Union[str, List[Union[str, Column]]],
748
+ default='PRICE',
749
+ )
750
+ _symbols_doc = param_doc(
751
+ name='symbols',
752
+ desc="""
753
+ Symbol(s) from which data should be taken.
754
+ """,
755
+ str_annotation=('str, list of str, :class:`Source`, :class:`query`, :py:func:`eval query <onetick.py.eval>`, '
756
+ ':py:class:`onetick.query.GraphQuery`.'),
757
+ default=None,
758
+ )
759
+ _interest_rate_doc = param_doc(
760
+ name='interest_rate',
761
+ desc='''
762
+ The risk-free interest rate.
763
+
764
+ Could be set via a tick field, by specifying name of that field as string or
765
+ passing :py:class:`~onetick.py.Column` object.
766
+ ''',
767
+ annotation=Optional[Union[int, float, str, Column]],
768
+ default=None,
769
+ )
770
+ _price_field_doc = param_doc(
771
+ name='price_field',
772
+ desc='''
773
+ The name of the field carrying the price value.
774
+ ''',
775
+ annotation=Union[str, Column],
776
+ default='PRICE',
777
+ )
778
+ _option_price_field_doc = param_doc(
779
+ name='option_price_field',
780
+ desc='''
781
+ The name of the field carrying the option price value.
782
+ ''',
783
+ annotation=Union[str, Column],
784
+ default='OPTION_PRICE',
785
+ )
786
+ _method_doc = param_doc(
787
+ name='method',
788
+ desc='''
789
+ Allowed values are ``newton``, ``newton_with_fallback`` and ``bisections``.
790
+
791
+ Choose between ``newton`` and ``bisections`` for finding successively better approximations
792
+ to the implied volatility value.
793
+
794
+ Choose ``newton_with_fallback`` to automatically fall back to ``bisections`` method
795
+ when ``newton`` fails to converge.
796
+ ''',
797
+ annotation=str,
798
+ default='newton',
799
+ )
800
+ _precision_doc = param_doc(
801
+ name='precision',
802
+ desc='''
803
+ Precision of the implied volatility value.
804
+ ''',
805
+ annotation=float,
806
+ default='1.0e-5',
807
+ )
808
+ _value_for_non_converge_doc = param_doc(
809
+ name='value_for_non_converge',
810
+ desc='''
811
+ Allowed values are ``nan_val`` and ``closest_found_val``, where ``closest_found_val`` stands
812
+ for the volatility value for which the difference between calculated option price and input option price is minimal.
813
+
814
+ Choose between ``nan_val`` and ``closest_found_val`` as implied volatility value,
815
+ when the root-finding method does not converge within the specified precision.
816
+ ''',
817
+ annotation=str,
818
+ default='nan_val',
819
+ )
820
+ _option_type_field_doc = param_doc(
821
+ name='option_type_field',
822
+ desc='''
823
+ Specifies name of the field, which carries the option type (either **CALL** or **PUT**).
824
+ ''',
825
+ annotation=Union[str, Column],
826
+ default='',
827
+ )
828
+ _strike_price_field_doc = param_doc(
829
+ name='strike_price_field',
830
+ desc='''
831
+ Specifies name of the field, which carries the strike price of the option.
832
+ ''',
833
+ annotation=Union[str, Column],
834
+ default='',
835
+ )
836
+ _days_in_year_doc = param_doc(
837
+ name='days_in_year',
838
+ desc='''
839
+ Specifies number of days in a year (say, 365 or 252 (business days, etc.).
840
+ Used with ``days_till_expiration`` parameter to compute the fractional years till expiration.
841
+ ''',
842
+ annotation=int,
843
+ default=365,
844
+ )
845
+ _days_till_expiration_field_doc = param_doc(
846
+ name='days_till_expiration_field',
847
+ desc='''
848
+ Specifies name of the field, which carries number of days till expiration of the option.
849
+ ''',
850
+ annotation=Union[str, Column],
851
+ default='',
852
+ )
853
+ _expiration_date_field_doc = param_doc(
854
+ name='expiration_date_field',
855
+ desc='''
856
+ Specifies name of the field, which carries the expiration date of the option, in **YYYYMMDD** format.
857
+ ''',
858
+ annotation=Union[str, Column],
859
+ default='',
860
+ )
861
+
862
+
863
+ class DocMetaclass(type):
864
+ def __new__(mcs, name, bases, attrs, parameters: Optional[list] = None):
865
+ cls = super().__new__(mcs, name, bases, attrs)
866
+ doc = None
867
+ if '__init__' in attrs and cls.__init__.__doc__: # type: ignore
868
+ doc = cls.__init__.__doc__ # type: ignore
869
+ elif '__doc__' in attrs:
870
+ doc = attrs['__doc__']
871
+ if doc and parameters:
872
+ doc = Docstring(doc)
873
+ for param in parameters:
874
+ doc['Parameters'] = param
875
+ cls.__init__.__doc__ = doc.build() # type: ignore
876
+
877
+ return cls
878
+
879
+
880
+ def copy_method(obj, mimic=True, drop_examples=False):
881
+
882
+ """
883
+ Decorator to copy aggregation function as method
884
+
885
+ We assume that this decorator will be used only with aggregations.
886
+
887
+ Updates (same way as for dict) `obj` docstring with decorated function docstring
888
+ Updates decorated function signature: [self] + `obj` signature
889
+ if mimic is True - won't execute decorated function, will execute `obj` and apply self instead
890
+ if mimic is False - will execute decorated function as is
891
+
892
+ Parameters
893
+ ----------
894
+ obj:
895
+ donor aggregation function
896
+ mimic: bool, default=True
897
+ flag to execute decorated function or not
898
+ drop_examples: bool
899
+ Can be used to drop examples from ``obj`` docstring.
900
+ """
901
+
902
+ doc = obj.__doc__ or ''
903
+ params = [Parameter(name='self',
904
+ kind=Parameter.POSITIONAL_OR_KEYWORD)] + list(Signature.from_callable(obj).parameters.values())
905
+ doc = Docstring(doc)
906
+ if drop_examples and 'Examples' in doc.docstring:
907
+ doc.docstring.pop('Examples')
908
+
909
+ def _decorator(fun):
910
+ @wraps(fun)
911
+ def _inner(self, *args, **kwargs):
912
+ if mimic:
913
+ agg = obj(*args, **kwargs)
914
+ return agg.apply(self)
915
+ else:
916
+ return fun(self, *args, **kwargs)
917
+ fun_doc = fun.__doc__ or ''
918
+ fun_doc = Docstring(fun_doc)
919
+ doc.update(fun_doc)
920
+ _inner.__signature__ = Signature(parameters=params, return_annotation='Source')
921
+ _inner.__doc__ = doc.build()
922
+ return _inner
923
+ return _decorator
924
+
925
+
926
+ def copy_signature(obj, add_self=False, drop_parameters=None, return_annotation='Source'):
927
+ """
928
+ Decorator that copies signature of the callable ``obj`` to the decorated function.
929
+ """
930
+ drop_parameters = drop_parameters or []
931
+ obj_parameters = list(
932
+ param for param_name, param in Signature.from_callable(obj).parameters.items()
933
+ if param_name not in drop_parameters
934
+ )
935
+ params = []
936
+ if add_self:
937
+ params.append(
938
+ Parameter(name='self', kind=Parameter.POSITIONAL_ONLY)
939
+ )
940
+ params.extend(obj_parameters)
941
+
942
+ def _decorator(fun):
943
+ @wraps(fun)
944
+ def _inner(*args, **kwargs):
945
+ return fun(*args, **kwargs)
946
+ _inner.__signature__ = Signature(parameters=params, return_annotation=return_annotation)
947
+ return _inner
948
+ return _decorator