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
onetick/py/db/db.py ADDED
@@ -0,0 +1,1327 @@
1
+ # pylama:ignore=W0237
2
+ import logging
3
+ import os
4
+ import datetime as dt
5
+ import subprocess
6
+ import warnings
7
+
8
+ from datetime import timedelta
9
+ from collections import defaultdict
10
+ from dateutil.relativedelta import relativedelta
11
+ from typing import List, Union, Optional
12
+ from uuid import uuid4
13
+
14
+ from onetick import py as otp
15
+ from onetick.py.core import db_constants as constants
16
+ from onetick.py.compatibility import is_native_plus_zstd_supported
17
+ from onetick.py import utils, sources, session, configuration
18
+
19
+ import pandas
20
+
21
+
22
+ def _tick_type_detector(tick_type, obj):
23
+ if tick_type is not None:
24
+ return tick_type
25
+
26
+ type2traits = {
27
+ "ORDER": ["ID", "BUY_FLAG", "SIDE", "QTY", "QTY_FILLED", "QTY", "ORDTYPE", "PRICE", "PRICE_FILLED"],
28
+ "QTE": ["ASK_PRICE", "BID_PRICE", "ASK_SIZE", "BID_SIZE"],
29
+ "NBBO": ["ASK_PRICE", "BID_PRICE", "ASK_SIZE", "BID_SIZE", "BID_EXCHANGE", "ASK_EXCHANGE"],
30
+ "TRD": ["PRICE", "SIZE"],
31
+ }
32
+
33
+ type2count = defaultdict(lambda: 0)
34
+ max_tt = "TRD"
35
+ max_count = 0
36
+
37
+ for column in obj.columns():
38
+ for tt, traits in type2traits.items():
39
+ if column in traits:
40
+ type2count[tt] += 1
41
+
42
+ if type2count[tt] > max_count:
43
+ max_count = type2count[tt]
44
+ max_tt = tt
45
+
46
+ return max_tt
47
+
48
+
49
+ def write_to_db(src: 'otp.Source',
50
+ dest: Union[str, 'otp.DB'],
51
+ date: dt.date,
52
+ symbol: Union[str, 'otp.Column'],
53
+ tick_type: Union[str, 'otp.Column'],
54
+ timezone: Optional[str] = None,
55
+ execute: bool = True,
56
+ start: Optional[dt.date] = None,
57
+ end: Optional[dt.date] = None,
58
+ propagate: bool = False,
59
+ append: bool = True,
60
+ **kwargs):
61
+ """
62
+ Writes source to the database.
63
+ The main differences from otp.Source.write() function are
64
+ appending ticks by default, automatic tick_type detection and executing the query right here.
65
+
66
+ Parameters
67
+ ----------
68
+ src: :class:`otp.Source`
69
+ source that will be written to the database.
70
+ dest: str or :py:class:`otp.DB <onetick.py.DB>`
71
+ database name or object.
72
+ date: datetime or None
73
+ date where to save data.
74
+ Cannot be used together with `start` and `end` parameters.
75
+ start: datetime or None
76
+ start date of period where to save data.
77
+ Cannot be used together with `date` parameters.
78
+ Default is None.
79
+ end: datetime or None
80
+ end date of period where to save data.
81
+ Cannot be used together with `date` parameters.
82
+ Default is None.
83
+ symbol: str or Column
84
+ resulting symbol name string or column to get symbol name from.
85
+ tick_type: str or Column
86
+ resulting tick type string or column to get tick type from.
87
+ If tick type is None then an attempt will be taken to get
88
+ tick type name automatically based on the ``src`` source's schema.
89
+ (ORDER, QTE, TRD and NBBO tick types are supported).
90
+ timezone: str
91
+ If ``execute`` parameter is set then this timezone
92
+ will be used for running the query.
93
+ By default, it is set to `otp.config.tz`.
94
+ execute: bool
95
+ execute the query right here or not.
96
+ If True, `date` or `start`+`end` parameters are required,
97
+ and then dataframe will be returned.
98
+ (Probably empty, unless 'propagate' parameter is specified).
99
+ If False, modified copy of the source ``src`` will be returned.
100
+ propagate: bool
101
+ Propagate ticks after writing or not.
102
+ append: bool
103
+ Write the data in append mode or not.
104
+ kwargs:
105
+ other arguments that will be passed to :py:meth:`onetick.py.Source.write` function.
106
+ """
107
+
108
+ tick_type = _tick_type_detector(tick_type, src)
109
+
110
+ if timezone is None:
111
+ timezone = configuration.config.tz
112
+ if date is None or date is otp.adaptive:
113
+ kwargs['start_date'] = start
114
+ kwargs['end_date'] = end
115
+ else:
116
+ kwargs['date'] = date
117
+
118
+ writer = src.write(db=dest,
119
+ symbol=symbol,
120
+ tick_type=tick_type,
121
+ propagate=propagate,
122
+ append=append,
123
+ **kwargs)
124
+
125
+ if execute:
126
+ if not start or not end:
127
+ start = getattr(date, 'ts', date)
128
+ end = start + relativedelta(days=1)
129
+ return otp.run(writer, start=start, end=end, timezone=timezone)
130
+ return writer
131
+
132
+
133
+ class _DB:
134
+
135
+ _LOCAL = False
136
+ # this flag means that db section should be added to locator and acl (True)
137
+ # or db locates on some ts (False)
138
+
139
+ def __init__(
140
+ self,
141
+ name,
142
+ src=None,
143
+ date=None,
144
+ symbol=None,
145
+ tick_type=None,
146
+ db_properties: Optional[dict] = None,
147
+ db_locations: Optional[list] = None,
148
+ db_raw_data: Optional[dict] = None,
149
+ db_feed: Optional[dict] = None,
150
+ write=True,
151
+ minimum_start_date: Optional[Union[str, dt.date, 'otp.date']] = None,
152
+ maximum_end_date: Optional[Union[str, dt.date, 'otp.date']] = None,
153
+ ):
154
+ # we assume here that db_properties and db_locations fully prepared here or None (in case of remote db)
155
+ self.name = name
156
+ self.id, _, _ = name.partition("//")
157
+ self._db_properties = db_properties
158
+ self._db_locations = db_locations
159
+ self._db_raw_data = db_raw_data
160
+ self._db_feed = db_feed
161
+ self._write = write
162
+ self._minimum_start_date = (
163
+ dt.datetime.strptime(minimum_start_date, '%Y%m%d').date()
164
+ if isinstance(minimum_start_date, str)
165
+ else minimum_start_date
166
+ )
167
+ self._maximum_end_date = (
168
+ dt.datetime.strptime(maximum_end_date, '%Y%m%d').date()
169
+ if isinstance(maximum_end_date, str)
170
+ else maximum_end_date
171
+ )
172
+ if src is not None:
173
+ self.add(src=src, date=date, symbol=symbol, tick_type=tick_type)
174
+ elif any(x is not None for x in (date, symbol, tick_type)):
175
+ warnings.warn(
176
+ "Parameters 'date', 'symbol' and 'tick_type' can only be set when parameter 'src' is specified.",
177
+ FutureWarning,
178
+ stacklevel=3,
179
+ )
180
+
181
+ @staticmethod
182
+ def _format_params(params):
183
+ res = {}
184
+ for key, value in params.items():
185
+ if hasattr(value, 'strftime'):
186
+ res[key] = value.strftime("%Y%m%d%H%M%S")
187
+ else:
188
+ res[key] = str(value)
189
+ return res
190
+
191
+ # TODO: move this method to DB
192
+ def add(self,
193
+ src,
194
+ date=None,
195
+ start=None,
196
+ end=None,
197
+ symbol=None,
198
+ tick_type=None,
199
+ timezone=None,
200
+ **kwargs):
201
+ """
202
+ Add data to a database.
203
+ If ticks with the same timestamp are already presented in database old values won't be updated.
204
+
205
+ Parameters
206
+ ----------
207
+ src: :class:`otp.Source`
208
+ source that will be written to the database.
209
+ date: datetime or None
210
+ date of the day in which the data will be saved.
211
+ The timestamps of the ticks should be between the start and the end of the day.
212
+ Be default, it is set to `otp.config.default_date`.
213
+ start: datetime or None
214
+ start day of period in which the data will be saved.
215
+ The timestamps of the ticks should be between `start` and `end` dates.
216
+ Cannot be used with `date` parameter.
217
+ Be default, None.
218
+ end: datetime or None
219
+ end day of period in which the data will be saved.
220
+ The timestamps of the ticks should be between `start` and `end` dates.
221
+ Cannot be used with `date` parameter.
222
+ Be default, None.
223
+ symbol: str or Column
224
+ resulting symbol name string or column to get symbol name from.
225
+ Be default, it is set to `otp.config.default_db_symbol`.
226
+ tick_type: str or Column
227
+ resulting tick type string or column to get tick type from.
228
+ If tick type is None then an attempt will be taken to get
229
+ tick type name automatically based on the ``src`` source's schema.
230
+ (ORDER, QTE, TRD and NBBO tick types are supported).
231
+ timezone: str
232
+ This timezone will be used for running the query.
233
+ By default, it is set to `otp.config.tz`.
234
+ kwargs:
235
+ other arguments that will be passed to :py:meth:`onetick.py.Source.write` function.
236
+
237
+ Examples
238
+ --------
239
+
240
+ Data is saved to the specified date, symbol and tick type:
241
+ (note that ``session`` is created before this example)
242
+
243
+ >>> db = otp.DB('MYDB2')
244
+ >>> db.add(otp.Ticks(A=[4, 5, 6]), date=otp.dt(2003, 1, 1), symbol='SMB', tick_type='TT')
245
+ >>> session.use(db)
246
+
247
+ We can get the same data by specifying the same parameters:
248
+
249
+ >>> data = otp.DataSource(db, date=otp.dt(2003, 1, 1), symbols='SMB', tick_type='TT')
250
+ >>> otp.run(data)
251
+ Time A
252
+ 0 2003-01-01 00:00:00.000 4
253
+ 1 2003-01-01 00:00:00.001 5
254
+ 2 2003-01-01 00:00:00.002 6
255
+ """
256
+ if timezone is None:
257
+ timezone = configuration.config.tz
258
+ if start and end and date:
259
+ raise ValueError("You can't specify both start/end and date parameters")
260
+
261
+ if start and end:
262
+ kwargs['start'] = start
263
+ kwargs['end'] = end
264
+ kwargs['date'] = otp.adaptive
265
+ else:
266
+ kwargs['date'] = date if date is not None else configuration.config.default_start_time
267
+
268
+ _symbol = symbol if symbol is not None else configuration.config.default_db_symbol
269
+ kwargs.setdefault('propagate', kwargs.get('propagate_ticks', False))
270
+
271
+ res = self._session_handler(write_to_db,
272
+ src=src,
273
+ dest=self.name,
274
+ symbol=_symbol,
275
+ tick_type=tick_type,
276
+ timezone=timezone,
277
+ **kwargs)
278
+
279
+ # We need to keep backward-compatibility,
280
+ # because before there was no ability to get written ticks
281
+ if kwargs.get('propagate'):
282
+ return res
283
+ else:
284
+ return None
285
+
286
+ @property
287
+ def properties(self):
288
+ """
289
+ Get dict of database properties.
290
+
291
+ Returns
292
+ -------
293
+ dict
294
+
295
+ Examples
296
+ --------
297
+ >>> otp.DB('X').properties # doctest: +SKIP
298
+ {'symbology': 'BZX',
299
+ 'archive_compression_type': 'NATIVE_PLUS_GZIP',
300
+ 'tick_timestamp_type': 'NANOS'}
301
+ """
302
+ return self._db_properties
303
+
304
+ @property
305
+ def locations(self):
306
+ """
307
+ Get list of database locations.
308
+
309
+ Returns
310
+ -------
311
+ list of dict
312
+
313
+ Examples
314
+ --------
315
+ >>> otp.DB('X').locations # doctest:+ELLIPSIS
316
+ [{'access_method': 'file',
317
+ 'start_time': '20021230000000',
318
+ 'end_time': '21000101000000',
319
+ ...}]
320
+ """
321
+ return self._db_locations
322
+
323
+ @property
324
+ def raw_data(self):
325
+ """
326
+ Get dict of database raw configurations.
327
+
328
+ Returns
329
+ -------
330
+ dict of dict
331
+
332
+ Examples
333
+ --------
334
+ >>> db = otp.DB('RAW_EXAMPLE',
335
+ ... db_raw_data=[{
336
+ ... 'id': 'PRIMARY_A',
337
+ ... 'prefix': 'DATA.',
338
+ ... 'locations': [
339
+ ... {'mount': 'mount1'}
340
+ ... ]
341
+ ... }]
342
+ ... )
343
+ >>> db.raw_data # doctest:+ELLIPSIS
344
+ [{'id': 'PRIMARY_A', 'prefix': 'DATA.', 'locations': [{'mount': 'mount1', 'access_method': 'file', ...}]}]
345
+ """
346
+ return self._db_raw_data
347
+
348
+ @property
349
+ def feed(self):
350
+ """
351
+ Get dict of database feed configuration.
352
+
353
+ Returns
354
+ -------
355
+ dict
356
+
357
+ Examples
358
+ --------
359
+ >>> db = otp.DB('RAW_EXAMPLE',
360
+ ... db_raw_data=[{
361
+ ... 'id': 'PRIMARY_A',
362
+ ... 'prefix': 'DATA.',
363
+ ... 'locations': [
364
+ ... {'mount': 'mount1'}
365
+ ... ]
366
+ ... }],
367
+ ... db_feed={'type': 'rawdb', 'raw_source': 'PRIMARY_A'},
368
+ ... )
369
+ >>> db.feed
370
+ {'type': 'rawdb', 'raw_source': 'PRIMARY_A', 'format': 'native'}
371
+ """
372
+ return self._db_feed
373
+
374
+ @property
375
+ def symbols(self):
376
+ result = self._session_handler(self._symbols)
377
+ return result if result else []
378
+
379
+ def _session_handler(self, func, *args, **kwargs):
380
+ """
381
+ Handler to check if database is already in locator and
382
+ run function with separate session or using current
383
+
384
+ :param func: function to run
385
+ """
386
+ __result = None
387
+
388
+ _session = session.Session._instance
389
+ close_session = False
390
+ _remove_from_locator = False
391
+ _remove_from_acl = False
392
+ if _session is None:
393
+ close_session = True
394
+ _session = session.Session()
395
+
396
+ try:
397
+ if self._LOCAL:
398
+ if self.id not in _session.locator.databases:
399
+ if self.id != self.name and not otp.compatibility.is_supported_reload_locator_with_derived_db():
400
+ # Derived DB
401
+ raise ValueError(
402
+ "You need include derived DB into the session use the .use method before adding "
403
+ " data there."
404
+ )
405
+
406
+ _remove_from_locator = True
407
+ _session.locator.add(self)
408
+ if self.id not in _session.acl.databases:
409
+ _remove_from_acl = True
410
+ _session.acl.add(self)
411
+ __result = func(*args, **kwargs)
412
+ finally:
413
+ if close_session:
414
+ _session.close()
415
+ else:
416
+ if self._LOCAL:
417
+ if _remove_from_locator:
418
+ _session.locator.remove(self)
419
+ if _remove_from_acl:
420
+ _session.acl.remove(self)
421
+
422
+ return __result
423
+
424
+ def _symbols(self):
425
+ src = sources.Symbols(self)
426
+ symbols = otp.run(src)
427
+ result = []
428
+ if symbols.empty:
429
+ return []
430
+ for s in list(symbols["SYMBOL_NAME"]):
431
+ result.append(s.split(":")[-1])
432
+ return result
433
+
434
+ def __repr__(self):
435
+ return "DB: " + self.name
436
+
437
+ def __str__(self):
438
+ return self.name
439
+
440
+
441
+ class DB(_DB):
442
+ """
443
+ A class representing OneTick databases when configuring
444
+ :py:class:`locators <onetick.py.session.Locator>` and :py:class:`ACL <onetick.py.session.ACL>`.
445
+
446
+ A database can point to an existing OneTick archive
447
+ or the temporary directory can be created with the data provided.
448
+
449
+ This class object can then be :py:meth:`used <onetick.py.Session.use>`
450
+ in :py:class:`onetick.py.Session`.
451
+
452
+ The data to add to the database can be passed into the
453
+ constructor with parameter ``src`` or later with the :py:meth:`add` method.
454
+
455
+ Note that after ticks were written to a particular timestamps in the database,
456
+ they can't be updated for the same timestamps.
457
+
458
+ Note
459
+ ----
460
+ This class can only be used to create database on the local machine.
461
+ Database is created by using/creating a directory in the local filesystem
462
+ and adding entries to the OneTick locator and ACL local files.
463
+ This class can't be used to manage remote databases.
464
+
465
+ Parameters
466
+ ----------
467
+ name : str
468
+ Database name.
469
+ Derived databases are specified in "parent//derived" format.
470
+ A derived database inherits the parent database properties.
471
+ src : :py:class:`~onetick.py.Source`, optional
472
+ Data to add to the database.
473
+ date : :py:class:`onetick.py.date` or :py:class:`datetime.date`, optional
474
+ ``src`` data will be added to this date.
475
+ Can be set only if ``src`` is set.
476
+ Default value is the same as in :py:meth:`add` method.
477
+ symbol : str, optional
478
+ Symbol name to add ``src`` data for.
479
+ Can be set only if ``src`` is set.
480
+ Default value is the same as in :py:meth:`add` method.
481
+ tick_type : str, optional
482
+ Tick type to add ``src`` data for.
483
+ Can be set only if ``src`` is set.
484
+ Default value is the same as in :py:meth:`add` method.
485
+ db_properties : :obj:`dict`, optional
486
+ Properties of the database to add to the locator
487
+ db_locations : :obj:`list` of :obj:`dict`, optional
488
+ A list of locations for the database to add to the locator.
489
+ This parameter is a list, because databases in a locator can have several location sections.
490
+ If not specified, a temporary directory is used as the database location.
491
+ db_raw_data: :obj:`list` of :obj:`dict`, optional
492
+ Raw database configuration.
493
+ db_feed: dict, optional
494
+ Feed configuration.
495
+ write : bool, optional
496
+ Flag that controls access to write to database.
497
+ clean_up : bool, optional
498
+ Flag that controls temporary database cleanup
499
+ destroy_access : bool, optional
500
+ Flag that controls access to destroy the database.
501
+ minimum_start_date: str or :py:class:`datetime.date` or :py:class:`onetick.py.date`
502
+ Specifies the minimum date of the tick that can be served to a user.
503
+ The format for the value is *YYYYMMDD*.
504
+ The OneTick server enforces this permission by verifying that
505
+ the query start time is not less than time of 00:00:00, in GMT timezone, for the specified minimum start date.
506
+ maximum_end_date: str or :py:class:`datetime.date` or :py:class:`onetick.py.date`
507
+ Specifies the date of the tick, starting from which ticks are not allowed to be returned to a user.
508
+ The format for the value is *YYYYMMDD*.
509
+ The OneTick server enforces this permission by verifying that
510
+ the query end time is less than time of 00:00:00, in GMT timezone, for the specified maximum end date.
511
+
512
+ Examples
513
+ --------
514
+
515
+ A database can be initialized along with data:
516
+
517
+ >>> data = otp.Ticks(X=['hello', 'world!'])
518
+ >>> db = otp.DB('MYDB', data)
519
+
520
+ Database symbol name, tick type and date to which the data will be written can be changed like this:
521
+
522
+ >>> db = otp.DB('MYDB', data, symbol='S_S', tick_type='T_T', date=otp.dt(2003, 12, 1))
523
+
524
+ You can specify a derived db by using ``//`` as a separator:
525
+
526
+ >>> data = otp.Ticks(X=['parent1', 'parent2'])
527
+ >>> db = otp.DB('DB_A', data)
528
+ >>> db.add(data)
529
+
530
+ >>> data_derived = otp.Ticks(X=['derived1', 'derived2'])
531
+ >>> db_derived = otp.DB('DB_A//DB_D')
532
+ >>> session.use(db_derived)
533
+ >>> db_derived.add(data_derived)
534
+
535
+ You can add an existing OneTick database to the locator or create a new one:
536
+
537
+ >>> existing_db = otp.DB('MY_US_COMP', # doctest: +SKIP
538
+ ... db_locations=[{'location': '/home/user/data/US_COMP',
539
+ ... 'start_time': datetime(2003, 1, 1),
540
+ ... 'end_time': datetime(2010, 1, 1),
541
+ ... 'day_boundary_tz': 'EST5EDT'}])
542
+ >>> session.use(existing_db) # doctest: +SKIP
543
+ """
544
+
545
+ _LOCAL = True
546
+
547
+ def __init__(
548
+ self,
549
+ name=None,
550
+ src=None,
551
+ date=None,
552
+ symbol=None,
553
+ tick_type=None,
554
+ kind='archive',
555
+ db_properties=None,
556
+ db_locations=None,
557
+ db_raw_data=None,
558
+ db_feed=None,
559
+ write=True,
560
+ clean_up=utils.default,
561
+ destroy_access=False,
562
+ minimum_start_date=None,
563
+ maximum_end_date=None,
564
+ ):
565
+ if name is not None and not isinstance(name, str):
566
+ message = f"Database name expected to be string got {type(name)}"
567
+ logging.error(message)
568
+ raise TypeError(message)
569
+
570
+ self._clean_up = clean_up
571
+ self._destroy_access = destroy_access
572
+ self._path = None
573
+ self._db_suffix = ""
574
+
575
+ if name:
576
+ self._db_suffix = name
577
+ else:
578
+ # Mostly for temporary databases
579
+ name = uuid4().hex.upper()
580
+ self._db_suffix = "db_" + name
581
+
582
+ db_properties = self._prepare_db_properties(db_properties)
583
+ db_day_boundary_tz_set = 'day_boundary_tz' in db_properties.keys()
584
+ db_locations = self._prepare_db_locations(db_locations,
585
+ db_day_boundary_tz_set=db_day_boundary_tz_set,
586
+ kind=kind)
587
+ db_raw_data = self._prepare_db_raw_data(db_raw_data, db_properties)
588
+ db_feed = self._prepare_db_feed(db_feed)
589
+
590
+ if isinstance(src, pandas.DataFrame):
591
+ csv_path = os.path.join(self._tmp_dir.path, uuid4().hex.upper() + ".csv")
592
+ src.to_csv(csv_path, index=False)
593
+ if otp.__webapi__:
594
+ src = sources.CSV(utils.FileBuffer(csv_path))
595
+ else:
596
+ src = sources.CSV(csv_path)
597
+
598
+ super().__init__(
599
+ name=name,
600
+ src=src,
601
+ date=date,
602
+ symbol=symbol,
603
+ tick_type=tick_type,
604
+ db_properties=db_properties,
605
+ db_locations=db_locations,
606
+ db_raw_data=db_raw_data,
607
+ db_feed=db_feed,
608
+ write=write,
609
+ minimum_start_date=minimum_start_date,
610
+ maximum_end_date=maximum_end_date,
611
+ )
612
+
613
+ def _prepare_db_properties(self, properties):
614
+ if properties is None:
615
+ properties = {}
616
+
617
+ # convert all property keys to lowercase
618
+ properties = {k.lower(): v for k, v in properties.items()}
619
+
620
+ # set default properties if they are not specified
621
+ properties.setdefault("symbology", configuration.config.default_symbology)
622
+ properties.setdefault("tick_timestamp_type", "NANOS")
623
+
624
+ if is_native_plus_zstd_supported():
625
+ properties.setdefault("archive_compression_type", constants.compression_type.NATIVE_PLUS_ZSTD)
626
+ else:
627
+ properties.setdefault("archive_compression_type", constants.compression_type.NATIVE_PLUS_GZIP)
628
+
629
+ return self._format_params(properties)
630
+
631
+ def _create_db(self):
632
+ logging.debug(f'Creating temporary directory for db "{self._db_suffix}"')
633
+
634
+ dirs_list = self._db_suffix.replace("//", " DERIVED ").split()
635
+ dir_name = ''
636
+ base_dir = ""
637
+ if os.getenv('OTP_WEBAPI_TEST_MODE'):
638
+ # copied from onetick.test.fixtures _keep_generated_dir()
639
+ base_dir = os.path.join(otp.utils.TMP_CONFIGS_DIR(), os.environ.get("ONE_TICK_TMP_DIR", "dbs"))
640
+ for cur_dir in dirs_list:
641
+ dir_name = os.path.join(dir_name, cur_dir)
642
+ self._tmp_dir = utils.TmpDir(dir_name, clean_up=self._clean_up, base_dir=base_dir)
643
+ if not self._path:
644
+ self._path = self._tmp_dir.path
645
+
646
+ def _prepare_db_locations(self, locations, db_day_boundary_tz_set=None, kind=None, default_location=None):
647
+ if not locations:
648
+ locations = [{}]
649
+ result = []
650
+ # set default properties if they are not specified
651
+ for location in locations:
652
+ location.setdefault("access_method", constants.access_method.FILE)
653
+ location.setdefault("start_time", constants.DEFAULT_START_DATE - timedelta(days=2))
654
+ location.setdefault("end_time", constants.DEFAULT_END_DATE + timedelta(days=1))
655
+ if not db_day_boundary_tz_set and db_day_boundary_tz_set is not None:
656
+ # If the day_boundary_tz is not set database-wide, then we want it to have
657
+ # a default value for each location
658
+ day_boundary_tz = utils.default_day_boundary_tz(self._db_suffix)
659
+ if day_boundary_tz:
660
+ location.setdefault("day_boundary_tz", day_boundary_tz)
661
+
662
+ if 'location' not in location:
663
+ methods = {constants.access_method.SOCKET, constants.access_method.MEMORY}
664
+ if location['access_method'] in methods:
665
+ raise ValueError("Parameter 'location' must be specified when parameter"
666
+ f" 'access_method' is set to {methods}")
667
+ if not default_location:
668
+ self._create_db()
669
+ location['location'] = self._path
670
+ else:
671
+ location['location'] = default_location
672
+
673
+ if kind == 'accelerator':
674
+ location.setdefault("archive_duration", "continuous")
675
+ location.setdefault("growable_archive", "true")
676
+ # TODO: think what to do if there will be several locations
677
+
678
+ result.append(location)
679
+
680
+ return list(map(self._format_params, result))
681
+
682
+ def _prepare_db_raw_data(self, raw_data, db_properties):
683
+ if not raw_data:
684
+ return []
685
+
686
+ raw_ids = set()
687
+ auto_discover_mounts = db_properties.get('auto_discover_mounts', '').lower() == 'yes'
688
+ default_location = None
689
+
690
+ for raw_db in raw_data:
691
+ raw_db.setdefault('id', 'PRIMARY')
692
+ if raw_db['id'] in raw_ids:
693
+ raise ValueError("Parameter 'id' must be set and must be unique for raw databases")
694
+ raw_ids.add(raw_db['id'])
695
+
696
+ if 'prefix' not in raw_db:
697
+ raise ValueError("Parameter 'prefix' must be specified for raw database")
698
+
699
+ if self._path is not None and default_location is None:
700
+ default_location = utils.TmpDir(rel_path='raw', base_dir=self._path, clean_up=self._clean_up).path
701
+ raw_db['locations'] = self._prepare_db_locations(raw_db.get('locations'),
702
+ db_day_boundary_tz_set=None,
703
+ default_location=default_location)
704
+ if auto_discover_mounts and len(raw_db['locations']) > 1:
705
+ raise ValueError("Only one location must be specified for raw database"
706
+ " when parameter 'auto_discover_mounts' is specified for database")
707
+ for location in raw_db['locations']:
708
+ if 'mount' not in location and not auto_discover_mounts:
709
+ raise ValueError("Parameter 'mount' must be specified for raw database location")
710
+ if 'mount' in location and auto_discover_mounts:
711
+ raise ValueError("Parameter 'mount' must not be specified for raw database location"
712
+ " when parameter 'auto_discover_mounts' is specified for database")
713
+ return raw_data
714
+
715
+ def _prepare_db_feed(self, feed):
716
+ if not feed:
717
+ return {}
718
+ if 'type' not in feed:
719
+ raise ValueError("Parameter 'type' must be specified for database feed")
720
+ if feed['type'] == 'rawdb':
721
+ feed.setdefault('format', 'native')
722
+ formats = ('native', 'rt', 'ascii', 'xml')
723
+ if feed['format'] not in formats:
724
+ raise ValueError(f"Parameter 'format' must be one of {formats}")
725
+ feed.setdefault('raw_source', 'PRIMARY')
726
+ return self._format_params(feed)
727
+
728
+
729
+ class RefDB(DB):
730
+ """ Creates reference database object.
731
+
732
+ Parameters
733
+ ----------
734
+ name : str
735
+ Database name
736
+ clean_up : bool, optional
737
+ Flag that controls temporary database cleanup
738
+ db_properties : :obj:`dict`, optional
739
+ Properties of database to add to locator
740
+ db_location : :obj:`dict`, optional
741
+ Location of database to add to locator. Reference database must have a single location,
742
+ pointing to a continuous archive database.
743
+ write : bool, optional
744
+ Flag that controls access to write to database
745
+ destroy_access : bool, optional
746
+ Flag that controls access to destroy to database
747
+
748
+ Examples
749
+ --------
750
+
751
+ >>> properties = {'symbology': 'TICKER'}
752
+ >>> location = {'archive_duration': 'continuous'}
753
+ >>> ref_db = otp.RefDB('REF_DATA_MYDB', db_properties=properties, db_location=location)
754
+ >>> session.use(ref_db)
755
+ >>>
756
+ >>> data = 'A||20100102000000|20100103000000|B||20100103000000|20100104000000|'
757
+ >>> out, err = ref_db.put([otp.RefDB.SymbolNameHistory(data, 'TICKER')])
758
+ >>> b'Total ticks 8' in err and b'Total symbols 6' in err
759
+ True
760
+ >>>
761
+ >>> properties = {'ref_data_db': ref_db.name, 'symbology': 'TICKER'}
762
+ >>> db = otp.DB('MYDB', db_properties=properties)
763
+ >>> session.use(db)
764
+ >>>
765
+ >>> data = otp.Ticks(X=['hello'], start=otp.dt(2010, 1, 2), end=otp.dt(2010, 1, 3))
766
+ >>> data = otp.run(data.write(db.name, 'A', 'MSG', date=otp.dt(2010, 1, 2)))
767
+ >>> data = otp.Ticks(X=['world!'], start=otp.dt(2010, 1, 3), end=otp.dt(2010, 1, 4))
768
+ >>> data = otp.run(data.write(db.name, 'B', 'MSG', date=otp.dt(2010, 1, 3)))
769
+ >>>
770
+ >>> data = otp.DataSource(db.name, tick_type='MSG')
771
+ >>> s_dt, e_dt, symbol_date = otp.dt(2010, 1, 1), otp.dt(2010, 1, 4), otp.dt(2010, 1, 2)
772
+ >>> otp.run(data, symbols='A', start=s_dt, end=e_dt, symbol_date=symbol_date)
773
+ Time X
774
+ 0 2010-01-02 hello
775
+ 1 2010-01-03 world!
776
+ """
777
+
778
+ def __init__(
779
+ self,
780
+ name=None,
781
+ kind='archive',
782
+ db_properties=None,
783
+ db_location=None,
784
+ write=True,
785
+ clean_up=utils.default,
786
+ destroy_access=False,
787
+ ):
788
+ # ref db must have a single location, pointing to a continuous archive database
789
+ # (its location in the locator file must have archive_duration=continuous set)
790
+ if db_location is None:
791
+ db_location = {}
792
+ db_location.setdefault('archive_duration', 'continuous')
793
+ super().__init__(
794
+ name=name,
795
+ kind=kind,
796
+ db_properties=db_properties,
797
+ db_locations=[db_location],
798
+ write=write,
799
+ clean_up=clean_up,
800
+ destroy_access=destroy_access,
801
+ )
802
+
803
+ class Section():
804
+ """ Specification of a reference database section. Section content can be specified as a string or source.
805
+ The format of string and output columns of source must correspond with the section documentation.
806
+
807
+ Parameters
808
+ ----------
809
+ name : str
810
+ Section name
811
+ data : str or :class:`otp.Source`
812
+ Content of the section
813
+ attrs : :obj:`dict`, optional
814
+ Attributes of the section
815
+
816
+ Examples
817
+ --------
818
+
819
+ Data provided as a string:
820
+
821
+ >>> data = 'SYM1|20100101093000|20100101110000' + os.linesep
822
+ >>> data += 'SYM2|20100101110000|20100103140000'
823
+ >>> section = otp.RefDB.Section('SECTION_NAME', data, {'ATTR1': 'VAL1', 'ATTR2': 'VAL2'})
824
+ >>> print(section)
825
+ <SECTION_NAME ATTR1="VAL1" ATTR2="VAL2">
826
+ SYM1|20100101093000|20100101110000
827
+ SYM2|20100101110000|20100103140000
828
+ </SECTION_NAME>
829
+
830
+ Data provided as a :class:`otp.Source`:
831
+
832
+ >>> data = dict()
833
+ >>> data['SYMBOL_NAME'] = ['SYM1', 'SYM2']
834
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
835
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
836
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
837
+ >>> section = otp.RefDB.Section('SECTION_NAME', ticks, {'ATTR1': 'VAL1', 'ATTR2': 'VAL2'})
838
+ >>> print(section) # doctest:+ELLIPSIS
839
+ <SECTION_NAME ATTR1="VAL1" ATTR2="VAL2" OTQ_QUERY=...>
840
+ </SECTION_NAME>
841
+
842
+ where OTQ_QUERY is path to :class:`otp.Source`, dumped to disk as temporary .otq file.
843
+ """
844
+ # Read ref db guide for details on input format of sections
845
+ # http://solutions.pages.soltest.onetick.com/iac/onetick-server/ReferenceDatabaseGuide.html
846
+ def __init__(self, name: str, data: Union[str, 'otp.Source'], attrs: Optional[dict] = None):
847
+ self._name = name
848
+ self._data = data
849
+ self._attrs = ' '.join([f'{name}="{value}"' for name, value in attrs.items()]) if attrs else ''
850
+
851
+ def __str__(self):
852
+ if isinstance(self._data, str):
853
+ return f'<{self._name} {self._attrs}>{os.linesep}{self._data}{os.linesep}</{self._name}>'
854
+ otq = self._data.to_otq()
855
+ return f'<{self._name} {self._attrs} OTQ_QUERY={otq}>{os.linesep}</{self._name}>'
856
+
857
+ class SymbolNameHistory(Section):
858
+ """ Describes symbol changes for the same security. The continuity can be expressed in terms of any symbol type
859
+ and can be specified on the security level or the security+exchange level (more explicit).
860
+
861
+ Examples
862
+ --------
863
+
864
+ >>> data = 'CORE_A||20100101093000|20100101110000|CORE_B||20100101110000|20100103140000|'
865
+ >>> section = otp.RefDB.SymbolNameHistory(data, symbology='CORE')
866
+ >>> print(section)
867
+ <SYMBOL_NAME_HISTORY SYMBOLOGY="CORE">
868
+ CORE_A||20100101093000|20100101110000|CORE_B||20100101110000|20100103140000|
869
+ </SYMBOL_NAME_HISTORY>
870
+
871
+ Equivalent :class:`otp.Source`:
872
+
873
+ >>> data = dict()
874
+ >>> data['SYMBOL_NAME'] = ['CORE_A'] * 2
875
+ >>> data['SYMBOL_NAME_IN_HISTORY'] = ['CORE_A', 'CORE_B']
876
+ >>> data['SYMBOL_START_DATETIME'] = [otp.dt(2010, 1, 2, tz='EST5EDT')] * 2
877
+ >>> data['SYMBOL_END_DATETIME'] = [otp.dt(2010, 1, 5, tz='EST5EDT')] * 2
878
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 2, tz='EST5EDT'), otp.dt(2010, 1, 3, tz='EST5EDT')]
879
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 3, tz='EST5EDT'), otp.dt(2010, 1, 4, tz='EST5EDT')]
880
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
881
+ >>> section = otp.RefDB.SymbolNameHistory(ticks, symbology='CORE')
882
+ >>> print(section) # doctest:+ELLIPSIS
883
+ <SYMBOL_NAME_HISTORY SYMBOLOGY="CORE" OTQ_QUERY=...>
884
+ </SYMBOL_NAME_HISTORY>
885
+ """
886
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
887
+ super().__init__('SYMBOL_NAME_HISTORY', data, {'SYMBOLOGY': symbology})
888
+
889
+ class SymbologyMapping(Section):
890
+ """ Describes a history of mapping of symbols of one symbology to the symbols of another symbology.
891
+
892
+ Examples
893
+ --------
894
+
895
+ >>> data = 'A||20100101093000|20100101110000|CORE_A|' + os.linesep
896
+ >>> data += 'B||20100101110000|20100103140000|CORE_B|'
897
+ >>> section = otp.RefDB.SymbologyMapping(data, source_symbology='TICKER', dest_symbology='CORE')
898
+ >>> print(section)
899
+ <SYMBOLOGY_MAPPING SOURCE_SYMBOLOGY="TICKER" DEST_SYMBOLOGY="CORE">
900
+ A||20100101093000|20100101110000|CORE_A|
901
+ B||20100101110000|20100103140000|CORE_B|
902
+ </SYMBOLOGY_MAPPING>
903
+
904
+ Equivalent :class:`otp.Source`:
905
+
906
+ >>> data = dict()
907
+ >>> data['SYMBOL_NAME'] = ['A', 'B']
908
+ >>> data['MAPPED_SYMBOL_NAME'] = ['CORE_A', 'CORE_B']
909
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 2, tz='EST5EDT'), otp.dt(2010, 1, 3, tz='EST5EDT')]
910
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 3, tz='EST5EDT'), otp.dt(2010, 1, 4, tz='EST5EDT')]
911
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
912
+ >>> section = otp.RefDB.SymbologyMapping(ticks, source_symbology='TICKER', dest_symbology='CORE')
913
+ >>> print(section) # doctest:+ELLIPSIS
914
+ <SYMBOLOGY_MAPPING SOURCE_SYMBOLOGY="TICKER" DEST_SYMBOLOGY="CORE" OTQ_QUERY=...>
915
+ </SYMBOLOGY_MAPPING>
916
+ """
917
+ def __init__(self, data: Union[str, 'otp.Source'], source_symbology: str, dest_symbology: str):
918
+ super().__init__('SYMBOLOGY_MAPPING', data, {'SOURCE_SYMBOLOGY': source_symbology,
919
+ 'DEST_SYMBOLOGY': dest_symbology})
920
+
921
+ class CorpActions(Section):
922
+ """ Describes corporate actions. Used by OneTick to compute prices adjusted for various types of
923
+ corporate actions. Supports both built-in and custom (user-defined) types of corporate actions.
924
+
925
+ Examples
926
+ --------
927
+
928
+ >>> data = 'CORE_C||20100103180000|0.25|0.0|SPLIT'
929
+ >>> section = otp.RefDB.CorpActions(data, symbology='CORE')
930
+ >>> print(section)
931
+ <CORP_ACTIONS SYMBOLOGY="CORE">
932
+ CORE_C||20100103180000|0.25|0.0|SPLIT
933
+ </CORP_ACTIONS>
934
+
935
+ Equivalent :class:`otp.Source`:
936
+
937
+ >>> data = dict()
938
+ >>> data['SYMBOL_NAME'] = ['CORE_C']
939
+ >>> data['EFFECTIVE_DATETIME'] = [otp.dt(2010, 1, 3, 18, tz='EST5EDT')]
940
+ >>> data['MULTIPLICATIVE_ADJUSTMENT'] = [0.25]
941
+ >>> data['ADDITIVE_ADJUSTMENT'] = [0.0]
942
+ >>> data['ADJUSTMENT_TYPE_NAME'] = ['SPLIT']
943
+ >>> ticks = otp.Ticks(**data, offset=[0], db='LOCAL')
944
+ >>> section = otp.RefDB.CorpActions(ticks, symbology='CORE')
945
+ >>> print(section) # doctest:+ELLIPSIS
946
+ <CORP_ACTIONS SYMBOLOGY="CORE" OTQ_QUERY=...>
947
+ </CORP_ACTIONS>
948
+ """
949
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
950
+ super().__init__('CORP_ACTIONS', data, {'SYMBOLOGY': symbology})
951
+
952
+ class ContinuousContracts(Section):
953
+ """ Describes continuous contracts. Continuity is expressed in terms of stitched history
954
+ of real contracts and rollover adjustments in between them and can be specified
955
+ on the continuous contract level or continuous contract+exchange level (more explicit).
956
+
957
+ Examples
958
+ --------
959
+
960
+ >>> data = 'CC||CORE_A||20100101093000|20100101110000|0.5|0|CORE_B||20100101110000|20100103140000'
961
+ >>> section = otp.RefDB.ContinuousContracts(data, symbology='CORE')
962
+ >>> print(section)
963
+ <CONTINUOUS_CONTRACTS SYMBOLOGY="CORE">
964
+ CC||CORE_A||20100101093000|20100101110000|0.5|0|CORE_B||20100101110000|20100103140000
965
+ </CONTINUOUS_CONTRACTS>
966
+
967
+ Equivalent :class:`otp.Source`:
968
+
969
+ >>> data = dict()
970
+ >>> data['CONTINUOUS_CONTRACT_NAME'] = ['CC'] * 2
971
+ >>> data['SYMBOL_NAME'] = ['CORE_A', 'CORE_B']
972
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 2, tz='EST5EDT'), otp.dt(2010, 1, 3, tz='EST5EDT')]
973
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 3, tz='EST5EDT'), otp.dt(2010, 1, 4, tz='EST5EDT')]
974
+ >>> data['MULTIPLICATIVE_ADJUSTMENT'] = [0.5, None]
975
+ >>> data['ADDITIVE_ADJUSTMENT'] = [3, None]
976
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
977
+ >>> section = otp.RefDB.ContinuousContracts(ticks, symbology='CORE')
978
+ >>> print(section) # doctest:+ELLIPSIS
979
+ <CONTINUOUS_CONTRACTS SYMBOLOGY="CORE" OTQ_QUERY=...>
980
+ </CONTINUOUS_CONTRACTS>
981
+ """
982
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
983
+ super().__init__('CONTINUOUS_CONTRACTS', data, {'SYMBOLOGY': symbology})
984
+
985
+ class SymbolCurrency(Section):
986
+ """ Specifies symbols' currencies in 3-letter ISO codes for currencies. These are used for currency conversion
987
+ (e.g., when calculating portfolio price for a list of securities with different currencies).
988
+
989
+ Examples
990
+ --------
991
+
992
+ >>> data = 'CORE_A||20100101093000|20100101110000|USD|1.0' + os.linesep
993
+ >>> data += 'CORE_B||20100101110000|20100103140000|RUB|1.8'
994
+ >>> section = otp.RefDB.SymbolCurrency(data, symbology='CORE')
995
+ >>> print(section)
996
+ <SYMBOL_CURRENCY SYMBOLOGY="CORE">
997
+ CORE_A||20100101093000|20100101110000|USD|1.0
998
+ CORE_B||20100101110000|20100103140000|RUB|1.8
999
+ </SYMBOL_CURRENCY>
1000
+
1001
+ Equivalent :class:`otp.Source`:
1002
+
1003
+ >>> data = dict()
1004
+ >>> data['SYMBOL_NAME'] = ['CORE_A', 'CORE_B',]
1005
+ >>> data['CURRENCY'] = ['USD', 'RUB']
1006
+ >>> data['MULTIPLIER'] = [1., 1.8]
1007
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
1008
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
1009
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
1010
+ >>> section = otp.RefDB.SymbolCurrency(ticks, symbology='CORE')
1011
+ >>> print(section) # doctest:+ELLIPSIS
1012
+ <SYMBOL_CURRENCY SYMBOLOGY="CORE" OTQ_QUERY=...>
1013
+ </SYMBOL_CURRENCY>
1014
+ """
1015
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
1016
+ super().__init__('SYMBOL_CURRENCY', data, {'SYMBOLOGY': symbology})
1017
+
1018
+ class Calendar(Section):
1019
+ """ Specifies a named calendar. Needed to analyze tick data during specific market time intervals (i.e., during
1020
+ normal trading hours). Can either be used directly in queries as described below, or referred to
1021
+ from the SYMBOL_CALENDAR and EXCH_CALENDAR sections.
1022
+
1023
+ Examples
1024
+ --------
1025
+
1026
+ >>> data = 'CAL1|20100101093000|20100101110000|Regular|R|0.0.12345|093000|160000|GMT|1|DESCRIPTION1'
1027
+ >>> data += os.linesep
1028
+ >>> data += 'CAL2|20100101110000|20100103140000|Holiday|F|0.0.12345|094000|170000|GMT|0|DESCRIPTION2'
1029
+ >>> section = otp.RefDB.Calendar(data)
1030
+ >>> print(section)
1031
+ <CALENDAR >
1032
+ CAL1|20100101093000|20100101110000|Regular|R|0.0.12345|093000|160000|GMT|1|DESCRIPTION1
1033
+ CAL2|20100101110000|20100103140000|Holiday|F|0.0.12345|094000|170000|GMT|0|DESCRIPTION2
1034
+ </CALENDAR>
1035
+
1036
+ Equivalent :class:`otp.Source`:
1037
+
1038
+ >>> data = dict()
1039
+ >>> data['CALENDAR_NAME'] = ['CAL1', 'CAL2']
1040
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
1041
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
1042
+ >>> data['SESSION_NAME'] = ['Regular', 'Holiday']
1043
+ >>> data['SESSION_FLAGS'] = ['R', 'H']
1044
+ >>> data['DAY_PATTERN'] = ['0.0.12345', '0.0.12345']
1045
+ >>> data['START_HHMMSS'] = ['093000', '094000']
1046
+ >>> data['END_HHMMSS'] = ['160000', '170000']
1047
+ >>> data['TIMEZONE'] = ['GMT', 'GMT']
1048
+ >>> data['PRIORITY'] = [1, 0]
1049
+ >>> data['DESCRIPTION'] = ['DESCRIPTION1', 'DESCRIPTION2']
1050
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
1051
+ >>> section = otp.RefDB.Calendar(ticks)
1052
+ >>> print(section) # doctest:+ELLIPSIS
1053
+ <CALENDAR OTQ_QUERY=...>
1054
+ </CALENDAR>
1055
+ """
1056
+ def __init__(self, data: Union[str, 'otp.Source']):
1057
+ super().__init__('CALENDAR', data)
1058
+
1059
+ class SymbolCalendar(Section):
1060
+ """ Specifies a calendar for a symbol. Needed to analyze tick data during specific market time intervals
1061
+ (i.e., during normal trading hours). Can either be specified directly or refer to a named calendar by its name
1062
+ (see the CALENDAR section).
1063
+
1064
+ Examples
1065
+ --------
1066
+
1067
+ Symbol calendar section, referring to named calendar section:
1068
+
1069
+ >>> data = 'CORE_A|20100101093000|20100101110000|CAL1' + os.linesep
1070
+ >>> data += 'CORE_B|20100101110000|20100103140000|CAL2'
1071
+ >>> section = otp.RefDB.SymbolCalendar(data, symbology='CORE')
1072
+ >>> print(section)
1073
+ <SYMBOL_CALENDAR SYMBOLOGY="CORE">
1074
+ CORE_A|20100101093000|20100101110000|CAL1
1075
+ CORE_B|20100101110000|20100103140000|CAL2
1076
+ </SYMBOL_CALENDAR>
1077
+
1078
+ Equivalent :class:`otp.Source`:
1079
+
1080
+ >>> data = dict()
1081
+ >>> data['SYMBOL_NAME'] = ['CORE_A', 'CORE_B']
1082
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
1083
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
1084
+ >>> data['CALENDAR_NAME'] = ['CAL1', 'CAL2']
1085
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
1086
+ >>> section = otp.RefDB.SymbolCalendar(ticks, symbology='CORE')
1087
+ >>> print(section) # doctest:+ELLIPSIS
1088
+ <SYMBOL_CALENDAR SYMBOLOGY="CORE" OTQ_QUERY=...>
1089
+ </SYMBOL_CALENDAR>
1090
+
1091
+ Symbol calendar section without using named calendar section:
1092
+
1093
+ >>> data = 'CORE_A|20100101093000|20100101110000|Regular|R|0.0.12345|093000|160000|EST5EDT|1|' + os.linesep
1094
+ >>> data += 'CORE_B|20100101110000|20100103140000|Regular|F|0.0.12345|093000|160000|EST5EDT|1|'
1095
+ >>> section = otp.RefDB.SymbolCalendar(data, symbology='CORE')
1096
+ >>> print(section)
1097
+ <SYMBOL_CALENDAR SYMBOLOGY="CORE">
1098
+ CORE_A|20100101093000|20100101110000|Regular|R|0.0.12345|093000|160000|EST5EDT|1|
1099
+ CORE_B|20100101110000|20100103140000|Regular|F|0.0.12345|093000|160000|EST5EDT|1|
1100
+ </SYMBOL_CALENDAR>
1101
+
1102
+ Equivalent :class:`otp.Source`:
1103
+
1104
+ >>> data = dict()
1105
+ >>> data['SYMBOL_NAME'] = ['CORE_A', 'CORE_B']
1106
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
1107
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
1108
+ >>> data['SESSION_NAME'] = ['Regular', 'Regular']
1109
+ >>> data['SESSION_FLAGS'] = ['R', 'F']
1110
+ >>> data['DAY_PATTERN'] = ['0.0.12345', '0.0.12345']
1111
+ >>> data['START_HHMMSS'] = ['093000', '160000']
1112
+ >>> data['END_HHMMSS'] = ['CAL1', 'CAL2']
1113
+ >>> data['TIMEZONE'] = ['EST5EDT', 'EST5EDT']
1114
+ >>> data['PRIORITY'] = [1, 1]
1115
+ >>> data['DESCRIPTION'] = ['', '']
1116
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
1117
+ >>> section = otp.RefDB.SymbolCalendar(ticks, symbology='CORE')
1118
+ >>> print(section) # doctest:+ELLIPSIS
1119
+ <SYMBOL_CALENDAR SYMBOLOGY="CORE" OTQ_QUERY=...>
1120
+ </SYMBOL_CALENDAR>
1121
+ """
1122
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
1123
+ super().__init__('SYMBOL_CALENDAR', data, {'SYMBOLOGY': symbology})
1124
+
1125
+ class SectionStr(Section):
1126
+ """ Specification of a reference database section that can be specified only as a string.
1127
+ Section content still can be provided as a :class:`otp.Source`, but the :class:`otp.Source` is executed and
1128
+ result data is used as string in section. It's up to user to provide :class:`otp.Source` with correct number
1129
+ and order of columns.
1130
+
1131
+ Examples
1132
+ --------
1133
+
1134
+ Data provided as a string returns the same result as :class:`otp.RefDB.Section`.
1135
+
1136
+ Data provided as a :class:`otp.Source`:
1137
+
1138
+ >>> data = dict()
1139
+ >>> data['SYMBOL_NAME'] = ['SYM1', 'SYM2']
1140
+ >>> data['START_DATETIME'] = [otp.dt(2010, 1, 1, 9, 30, tz='EST5EDT'), otp.dt(2010, 1, 1, 11, tz='EST5EDT')]
1141
+ >>> data['END_DATETIME'] = [otp.dt(2010, 1, 1, 11, tz='EST5EDT'), otp.dt(2010, 1, 3, 14, tz='EST5EDT')]
1142
+ >>> ticks = otp.Ticks(**data, offset=[0] * 2, db='LOCAL')
1143
+ >>> ticks = ticks.table(SYMBOL_NAME=otp.string[128], START_DATETIME=otp.msectime, END_DATETIME=otp.msectime)
1144
+ >>> section = otp.RefDB.SectionStr('SECTION_NAME', ticks, {'ATTR1': 'VAL1', 'ATTR2': 'VAL2'})
1145
+ >>> print(section) # doctest:+ELLIPSIS
1146
+ <SECTION_NAME ATTR1="VAL1" ATTR2="VAL2">
1147
+ SYM1|20100101093000|20100101110000
1148
+ SYM2|20100101110000|20100103140000
1149
+ </SECTION_NAME>
1150
+
1151
+ where OTQ_QUERY is path to :class:`otp.Source`, dumped to disk as temporary .otq file.
1152
+ """
1153
+ def __init__(self, name: str, data: Union[str, 'otp.Source'], attrs: Optional[dict] = None):
1154
+ data_str = data if isinstance(data, str) else self._source_to_str(data)
1155
+ super().__init__(name, data_str, attrs)
1156
+
1157
+ def _source_to_str(self, data: 'otp.Source'):
1158
+ df = otp.run(data)
1159
+ df.drop(columns=['Time'], inplace=True)
1160
+ df = df.to_csv(sep='|', header=False, index=False, date_format='%Y%m%d%H%M%S')
1161
+ return df
1162
+
1163
+ class PrimaryExchange(SectionStr):
1164
+ """ Specifies symbols' primary exchanges. Used to extract and analyze tick data for a security on
1165
+ its primary exchange, without having to explicitly specify the name of the primary exchange.
1166
+
1167
+ Examples
1168
+ --------
1169
+
1170
+ >>> data = 'A||19991118000000|99999999000000|N|'
1171
+ >>> data += os.linesep
1172
+ >>> data += 'AA||19991118000000|99999999000000|N|AA.N'
1173
+ >>> section = otp.RefDB.PrimaryExchange(data, symbology='TICKER')
1174
+ >>> print(section)
1175
+ <PRIMARY_EXCHANGE SYMBOLOGY="TICKER">
1176
+ A||19991118000000|99999999000000|N|
1177
+ AA||19991118000000|99999999000000|N|AA.N
1178
+ </PRIMARY_EXCHANGE>
1179
+
1180
+ Equivalent query should return the same data values in the same order. Column names does not matter.
1181
+ """
1182
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
1183
+ super().__init__('PRIMARY_EXCHANGE', data, {'SYMBOLOGY': symbology})
1184
+
1185
+ class ExchCalendar(SectionStr):
1186
+ """ Specifies symbols' primary exchanges. Used to extract and analyze tick data for a security on
1187
+ its primary exchange, without having to explicitly specify the name of the primary exchange.
1188
+
1189
+ Examples
1190
+ --------
1191
+
1192
+ >>> data = 'NYSE||19600101000000|20501231235959|Regular|R|0.0.12345|093000|160000|EST5EDT|'
1193
+ >>> data += os.linesep
1194
+ >>> data += 'NYSE||19600101000000|20501231235959|Half-day|RL|12/31|093000|130000|EST5EDT|'
1195
+ >>> data += os.linesep
1196
+ >>> data += 'NYSE||19600101000000|20501231235959|Holiday|H|01/01|000000|240000|EST5EDT|'
1197
+ >>> section = otp.RefDB.ExchCalendar(data, symbology='MIC')
1198
+ >>> print(section)
1199
+ <EXCH_CALENDAR SYMBOLOGY="MIC">
1200
+ NYSE||19600101000000|20501231235959|Regular|R|0.0.12345|093000|160000|EST5EDT|
1201
+ NYSE||19600101000000|20501231235959|Half-day|RL|12/31|093000|130000|EST5EDT|
1202
+ NYSE||19600101000000|20501231235959|Holiday|H|01/01|000000|240000|EST5EDT|
1203
+ </EXCH_CALENDAR>
1204
+
1205
+ If a CALENDAR section is used:
1206
+
1207
+ >>> data = 'LSE||19600101000000|20501231235959|WNY'
1208
+ >>> section = otp.RefDB.ExchCalendar(data, symbology='MIC')
1209
+ >>> print(section)
1210
+ <EXCH_CALENDAR SYMBOLOGY="MIC">
1211
+ LSE||19600101000000|20501231235959|WNY
1212
+ </EXCH_CALENDAR>
1213
+
1214
+ Equivalent query should return the same data values in the same order. Column names does not matter.
1215
+ """
1216
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str):
1217
+ super().__init__('EXCH_CALENDAR', data, {'SYMBOLOGY': symbology})
1218
+
1219
+ class SymbolExchange(SectionStr):
1220
+ """ Specifies the exchange where a security is traded. Needs to be provided for the symbologies where
1221
+ the symbol name is unique across all exchanges.
1222
+
1223
+ Examples
1224
+ --------
1225
+
1226
+ >>> data = 'IBM.N|19980825000000|20501231235959|NYSE||'
1227
+ >>> section = otp.RefDB.SymbolExchange(data, symbology='RIC', exchange_symbology='MIC')
1228
+ >>> print(section)
1229
+ <SYMBOL_EXCHANGE SYMBOLOGY="RIC" EXCHANGE_SYMBOLOGY="MIC">
1230
+ IBM.N|19980825000000|20501231235959|NYSE||
1231
+ </SYMBOL_EXCHANGE>
1232
+
1233
+ Equivalent query should return the same data values in the same order. Column names does not matter.
1234
+ """
1235
+ def __init__(self, data: Union[str, 'otp.Source'], symbology: str, exchange_symbology: str):
1236
+ super().__init__('SYMBOL_EXCHANGE', data, {'SYMBOLOGY': symbology,
1237
+ 'EXCHANGE_SYMBOLOGY': exchange_symbology})
1238
+
1239
+ def put(
1240
+ self,
1241
+ src: Union[str, List[Section]],
1242
+ tickdb_symbology: Optional[List[str]] = None,
1243
+ delta_mode: bool = False,
1244
+ full_integrity_check: bool = False,
1245
+ load_by_sections: bool = True,
1246
+ ):
1247
+ """
1248
+ Loads data in database with reference_data_loader.exe.
1249
+ If db properties contain SUPPORT_DELTAS=YES, delta_mode set to True, and proper delta file is used
1250
+ then data is loaded in incremental mode (in other words, replace or modification mode).
1251
+ If the above conditions are not met, reference database content is entirely rewritten with the new data.
1252
+
1253
+ Parameters
1254
+ ----------
1255
+ src : str, list of str or otp.RefDB.Section
1256
+ Path to data file, or list of data per section in specified format
1257
+ tickdb_symbology : list of str, optional
1258
+ All symbologies for which the reference data needs to be generated
1259
+ delta_mode : bool, default is False
1260
+ If set to True loader will perform incremental load. Cannot be used if ``tickdb_symbology`` is specified
1261
+ full_integrity_check : bool, default is False
1262
+ If set to True loader checks all mappings to symbologies with symbol name history section
1263
+ and gives warning if mapped securities do not have symbol name history
1264
+ load_by_sections : bool, default is True
1265
+ If set to True loader will perform input data file splitting by data types and symbologies
1266
+ to load each part separately instead loading the entire file at once
1267
+ """
1268
+ # More info:
1269
+ # http://solutions.pages.soltest.onetick.com/iac/onetick-server/reference_data_loader.html - loader doc
1270
+ # https://onemarketdata.atlassian.net/browse/KB-286 - details on delta mode
1271
+ return self._session_handler(
1272
+ self._put,
1273
+ src=src,
1274
+ delta_mode=delta_mode,
1275
+ full_integrity_check=full_integrity_check,
1276
+ load_by_sections=load_by_sections,
1277
+ tickdb_symbology=tickdb_symbology,
1278
+ )
1279
+
1280
+ def _prepare_data_file(self, src):
1281
+ if isinstance(src, str):
1282
+ return src
1283
+
1284
+ data = f'<VERSION_INFO VERSION="1">{os.linesep}</VERSION_INFO>'
1285
+ for section in src:
1286
+ data += f'{os.linesep}{os.linesep}{section}'
1287
+
1288
+ data_file = utils.TmpFile(suffix='.txt')
1289
+ with open(data_file.path, 'w') as f:
1290
+ f.writelines(data)
1291
+ return data_file.path
1292
+
1293
+ def _prepare_loader_args(self, data_file, tickdb_symbology, delta_mode, full_integrity_check, load_by_sections):
1294
+ loader_args = ['-dbname', self.name]
1295
+ loader_args += ['-data_file', data_file]
1296
+ if tickdb_symbology:
1297
+ for symbology in tickdb_symbology:
1298
+ loader_args += ['-tickdb_symbology', symbology]
1299
+ loader_args += ['-delta_mode', 'yes' if delta_mode else 'no']
1300
+ loader_args += ['-full_integrity_check', 'yes' if full_integrity_check else 'no']
1301
+ loader_args += ['-load_by_sections', 'yes' if load_by_sections else 'no']
1302
+ return loader_args
1303
+
1304
+ def _put(self, src, tickdb_symbology, delta_mode, full_integrity_check, load_by_sections):
1305
+ if otp.__webapi__:
1306
+ raise NotImplementedError("Reference database loader is not supported in WebAPI mode.")
1307
+ data_file = self._prepare_data_file(src)
1308
+ loader_args = self._prepare_loader_args(
1309
+ data_file, tickdb_symbology, delta_mode, full_integrity_check, load_by_sections
1310
+ )
1311
+ loader_path = os.path.join(utils.omd_dist_path(), 'one_tick', 'bin', 'reference_data_loader.exe')
1312
+ p = subprocess.run(
1313
+ [loader_path] + loader_args,
1314
+ env={
1315
+ 'ONE_TICK_CONFIG': session.Session._instance.config.path,
1316
+ 'TZ': os.environ.get('TZ', otp.config['tz']),
1317
+ },
1318
+ stdout=subprocess.PIPE,
1319
+ stderr=subprocess.PIPE,
1320
+ check=False,
1321
+ )
1322
+ return p.stdout, p.stderr
1323
+
1324
+ def add(self, *args, **kwargs):
1325
+ # this method is not implemented because
1326
+ # reference database loader can only rewrite the data, not add new entries
1327
+ raise NotImplementedError("Method is not supported for reference databases. Use put instead.")