INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Initialize a Parties object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a Parties object from a json dictionary.""" args = {} if 'party' in _dict: args['party'] = _dict.get('party') if 'importance' in _dict: args['importance'] = _dict.get('importance') if 'role' in _dict: a...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'party') and self.party is not None: _dict['party'] = self.party if hasattr(self, 'importance') and self.importance is not None: _dict['importance'] = self.impo...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_d...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'hash') and self.hash is not None: _dict['hash'] = self.hash return _d...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.lo...
Initialize a TableReturn object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'mo...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: _dict['document'] = self.document._to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model...
Initialize a Tables object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a Tables object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'section_title' in ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label._to_dict() return _dict
Initialize a UnalignedElement object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('lo...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_label') and self.document_label is not None: _dict['document_label'] = self.document_label if hasattr(self, 'location') and self.location is not None: ...
Sends audio for speech recognition using web sockets.
def recognize_using_websocket(self, audio, content_type, recognize_callback, model=None, language_customization_id=None, ...
Sends the text message Note: The service handles one request per connection
def send_text(self): """ Sends the text message Note: The service handles one request per connection """ def run(*args): """Background process to send the text""" self.ws_client.send(json.dumps(self.options).encode('utf8')) time.sleep(TEN_MILL...
Callback executed when message is received from the server.
def on_data(self, ws, message, message_type, fin): """ Callback executed when message is received from the server. :param ws: Websocket client :param message: utf-8 string which we get from the server. :param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OP...
Send message to server.
def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT): """ Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ self.ws_client.se...
Stream audio to server
def send_audio(self, ws): """ Stream audio to server :param ws: Websocket client """ def run(*args): """Background process to stream the data""" if not self.audio_source.is_buffer: while True: chunk = self.audio_source....
Callback executed when a connection is opened to the server. Handles streaming of audio to the server.
def on_open(self, ws): """ Callback executed when a connection is opened to the server. Handles streaming of audio to the server. :param ws: Websocket client """ self.callback.on_connected() # Send initialization message init_data = self.build_start_mess...
Callback executed when message is received from the server.
def on_data(self, ws, message, message_type, fin): """ Callback executed when message is received from the server. :param ws: Websocket client :param message: utf-8 string which we get from the server. :param message_type: Message type which is either ABNF.OPCODE_TEXT or ABNF.OP...
Get profile.
def profile(self, content, accept, content_language=None, accept_language=None, raw_scores=None, csv_headers=None, consumption_preferences=None, content_type=None, **kwargs): ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'trait_id') and self.trait_id is not None: _dict['trait_id'] = self.trait_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'consumption_preference_id' ) and self.consumption_preference_id is not None: _dict['consumption_preference_id'] = self.consumption_preference_id if hasat...
Initialize a ConsumptionPreferencesCategory object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} if 'consumption_preference_category_id' in _dict: args['consumption_preference_category_id'] = _dict.get( 'consumption_preference_category_id') ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'consumption_preference_category_id' ) and self.consumption_preference_category_id is not None: _dict[ 'consumption_preference_category_id'] = sel...
Initialize a Content object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a Content object from a json dictionary.""" args = {} if 'contentItems' in _dict: args['content_items'] = [ ContentItem._from_dict(x) for x in (_dict.get('contentItems')) ] else: raise ValueErro...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'content_items') and self.content_items is not None: _dict['contentItems'] = [x._to_dict() for x in self.content_items] return _dict
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'content') and self.content is not None: _dict['content'] = self.content if hasattr(self, 'id') and self.id is not None: _dict['id'] = self.id if hasatt...
Initialize a Profile object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a Profile object from a json dictionary.""" args = {} if 'processed_language' in _dict: args['processed_language'] = _dict.get('processed_language') else: raise ValueError( 'Required property \'processed_la...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr( self, 'processed_language') and self.processed_language is not None: _dict['processed_language'] = self.processed_language if hasattr(self, 'word...
Initialize a Trait object from a json dictionary.
def _from_dict(cls, _dict): """Initialize a Trait object from a json dictionary.""" args = {} if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: raise ValueError( 'Required property \'trait_id\' not present in Trait JSON') ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'trait_id') and self.trait_id is not None: _dict['trait_id'] = self.trait_id if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name ...
Return a json dictionary representing this model.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warning_id') and self.warning_id is not None: _dict['warning_id'] = self.warning_id if hasattr(self, 'message') and self.message is not None: _dict['message'] ...
Delete all chunks for a symbol.
def delete(self, symbol, date_range=None): """ Delete all chunks for a symbol. Which are, for the moment, fully contained in the passed in date_range. Parameters ---------- symbol : `str` symbol name for the item date_range : `date.DateRange`...
Return the mongo read preference given an allow_secondary argument
def _read_preference(self, allow_secondary): """ Return the mongo read preference given an 'allow_secondary' argument """ allow_secondary = self._allow_secondary if allow_secondary is None else allow_secondary return ReadPreference.NEAREST if allow_secondary else ReadPreference.PRIMARY
Read data for the named symbol. Returns a VersionedItem object with a data and metdata element ( as passed into write ).
def read(self, symbol, date_range=None, columns=None, include_images=False, allow_secondary=None, _target_tick_count=0): """ Read data for the named symbol. Returns a VersionedItem object with a data and metdata element (as passed into write). Parameters ----------...
Writes a list of market data events.
def write(self, symbol, data, initial_image=None, metadata=None): """ Writes a list of market data events. Parameters ---------- symbol : `str` symbol name for the item data : list of dicts or a pandas.DataFrame List of ticks to store to the tick-...
Represent dtypes without byte order as earlier Java tickstore code doesn t support explicit byte order.
def _str_dtype(dtype): """ Represent dtypes without byte order, as earlier Java tickstore code doesn't support explicit byte order. """ assert dtype.byteorder != '>' if dtype.kind == 'i': assert dtype.itemsize == 8 return 'int64' elif dtype.kind ==...
Return the maximum datetime stored for a particular symbol
def max_date(self, symbol): """ Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item """ res = self._collection.find_one({SYMBOL: symbol}, projection={ID: 0, END: 1}, ...
Return the minimum datetime stored for a particular symbol
def min_date(self, symbol): """ Return the minimum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item """ res = self._collection.find_one({SYMBOL: symbol}, projection={ID: 0, START: 1}, ...
pass thru chunker of the dataframe/ series
def to_chunks(self, df, **kwargs): """ pass thru chunker of the dataframe/series returns ------- ('NA', 'NA', 'NA', dataframe/series) """ if len(df) > 0: yield b'NA', b'NA', b'NA', df
Return True/ False on authentication success.
def authenticate(db, user, password): """ Return True / False on authentication success. PyMongo 2.6 changed the auth API to raise on Auth failure. """ try: logger.debug("Authenticating {} with {}".format(db, user)) return db.authenticate(user, password) except OperationFailure ...
Authentication hook to allow plugging in custom authentication credential providers
def get_auth(host, app_name, database_name): """ Authentication hook to allow plugging in custom authentication credential providers """ from .hooks import _get_auth_hook return _get_auth_hook(host, app_name, database_name)
Returns a mongo library for the given connection string
def get_arctic_lib(connection_string, **kwargs): """ Returns a mongo library for the given connection string Parameters --------- connection_string: `str` Format must be one of the following: library@trading for known mongo servers library@hostname:port Returns:...
Attempts to authenticate against the mongo instance.
def do_db_auth(host, connection, db_name): """ Attempts to authenticate against the mongo instance. Tries: - Auth'ing against admin as 'admin' ; credentials: <host>/arctic/admin/admin - Auth'ing against db_name (which may be None if auth'ing against admin above) returns True if authenticat...
External exception logging hook.
def log_exception(fn_name, exception, retry_count, **kwargs): """ External exception logging hook. """ _log_exception_hook(fn_name, exception, retry_count, **kwargs)
Dataframe group - by operation that supports aggregating by different methods on the index.
def fancy_group_by(df, grouping_level=0, aggregate_level=1, method='last', max_=None, min_=None, within=None): """ Dataframe group-by operation that supports aggregating by different methods on the index. Parameters ---------- df: ``DataFrame`` Pandas dataframe with a MultiIndex grouping_le...
Common use case for selecting the latest rows from a bitemporal dataframe as - of a certain date.
def groupby_asof(df, as_of=None, dt_col='sample_dt', asof_col='observed_dt'): ''' Common use case for selecting the latest rows from a bitemporal dataframe as-of a certain date. Parameters ---------- df: ``pd.DataFrame`` Dataframe with a MultiIndex index as_of: ``datetime`` Return a...
Return a new dataframe with a row inserted for a multi - index dataframe. This will sort the rows according to the ordered multi - index levels.
def multi_index_insert_row(df, index_row, values_row): """ Return a new dataframe with a row inserted for a multi-index dataframe. This will sort the rows according to the ordered multi-index levels. """ row_index = pd.MultiIndex(levels=[[i] for i in index_row], labels=...
Insert some values into a bi - temporal dataframe. This is like what would happen when we get a price correction.
def insert_at(df, sample_date, values): """ Insert some values into a bi-temporal dataframe. This is like what would happen when we get a price correction. """ observed_dt = dt(datetime.now()) return multi_index_insert_row(df, [sample_date, observed_dt], values)
Register a Arctic Library Type handler
def register_library_type(name, type_): """ Register a Arctic Library Type handler """ if name in LIBRARY_TYPES: raise ArcticException("Library %s already registered as %s" % (name, LIBRARY_TYPES[name])) LIBRARY_TYPES[name] = type_
Returns ------- List of Arctic library names from a cached collection ( global per mongo cluster ) in mongo. Long term list_libraries should have a use_cached argument.
def _list_libraries_cached(self, newer_than_secs=-1): """ Returns ------- List of Arctic library names from a cached collection (global per mongo cluster) in mongo. Long term list_libraries should have a use_cached argument. """ _ = self._conn # Ensures the conne...
Check whether a given library exists.
def library_exists(self, library): """ Check whether a given library exists. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' Returns ------- `bool` True if the library with the given...
Create an Arctic Library or a particular type.
def initialize_library(self, library, lib_type=VERSION_STORE, **kwargs): """ Create an Arctic Library or a particular type. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' lib_type : `str` The type ...
Delete an Arctic Library and all associated collections in the MongoDB.
def delete_library(self, library): """ Delete an Arctic Library, and all associated collections in the MongoDB. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' """ lib = ArcticLibraryBinding(self, librar...
Return the library instance. Can generally use slicing to return the library: arctic_store [ library ]
def get_library(self, library): """ Return the library instance. Can generally use slicing to return the library: arctic_store[library] Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' """ if...
Renames a library
def rename_library(self, from_lib, to_lib): """ Renames a library Parameters ---------- from_lib: str The name of the library to be renamed to_lib: str The new name of the library """ to_colname = to_lib if '.' in from_lib ...
Returns the canonical ( database_name library ) for the passed in string library.
def _parse_db_lib(cls, library): """ Returns the canonical (database_name, library) for the passed in string 'library'. """ database_name = library.split('.', 2) if len(database_name) == 2: library = database_name[1] if database_name[0].startswith(...
Set a quota ( in bytes ) on this user library. The quota is best effort and should be set conservatively.
def set_quota(self, quota_bytes): """ Set a quota (in bytes) on this user library. The quota is 'best effort', and should be set conservatively. A quota of 0 is 'unlimited' """ self.set_library_metadata(ArcticLibraryBinding.QUOTA, quota_bytes) self.quota = quota...
Check whether the user is within quota. Should be called before every write. Will raise () if the library has exceeded its allotted quota.
def check_quota(self): """ Check whether the user is within quota. Should be called before every write. Will raise() if the library has exceeded its allotted quota. """ # Don't check on every write, that would be slow if self.quota_countdown > 0: sel...
Checksum the passed in dictionary
def _checksum(self, fields, data): """ Checksum the passed in dictionary """ sha = hashlib.sha1() for field in fields: sha.update(field) sha.update(data) return Binary(sha.digest())
Delete all chunks for a symbol or optionally chunks within a range
def delete(self, symbol, chunk_range=None, audit=None): """ Delete all chunks for a symbol, or optionally, chunks within a range Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete a...
Returns all symbols in the library
def list_symbols(self, partial_match=None): """ Returns all symbols in the library Parameters ---------- partial: None or str if not none, use this string to do a partial match on symbol names Returns ------- list of str """ s...
Rename a symbol
def rename(self, from_symbol, to_symbol, audit=None): """ Rename a symbol Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information ...
Reads data for a given symbol from the database.
def read(self, symbol, chunk_range=None, filter_data=True, **kwargs): """ Reads data for a given symbol from the database. Parameters ---------- symbol: str, or list of str the symbol(s) to retrieve chunk_range: object corresponding range object f...
Reads the audit log
def read_audit_log(self, symbol=None): """ Reads the audit log Parameters ---------- symbol: str optionally only retrieve specific symbol's audit information Returns ------- list of dicts """ if symbol: return [x f...
Writes data from item to symbol in the database
def write(self, symbol, item, metadata=None, chunker=DateChunker(), audit=None, **kwargs): """ Writes data from item to symbol in the database Parameters ---------- symbol: str the symbol that will be used to reference the written data item: Dataframe or Seri...
helper method used by update and append since they very closely resemble eachother. Really differ only by the combine method. append will combine existing date with new data ( within a chunk ) whereas update will replace existing data with new data ( within a chunk ).
def __update(self, sym, item, metadata=None, combine_method=None, chunk_range=None, audit=None): ''' helper method used by update and append since they very closely resemble eachother. Really differ only by the combine method. append will combine existing date with new data (within a chu...
Appends data from item to symbol s data in the database.
def append(self, symbol, item, upsert=False, metadata=None, audit=None, **kwargs): """ Appends data from item to symbol's data in the database. Is not idempotent Parameters ---------- symbol: str the symbol for the given item in the DB item: DataFram...
Overwrites data in DB with data in item for the given symbol.
def update(self, symbol, item, metadata=None, chunk_range=None, upsert=False, audit=None, **kwargs): """ Overwrites data in DB with data in item for the given symbol. Is idempotent Parameters ---------- symbol: str the symbol for the given item in the DB ...
Returns information about the symbol in a dictionary
def get_info(self, symbol): """ Returns information about the symbol, in a dictionary Parameters ---------- symbol: str the symbol for the given item in the DB Returns ------- dictionary """ sym = self._get_symbol_info(symbol)...
Reads user defined metadata out for the given symbol
def read_metadata(self, symbol): ''' Reads user defined metadata out for the given symbol Parameters ---------- symbol: str symbol for the given item in the DB Returns ------- ? ''' sym = self._get_symbol_info(symbol) ...
writes user defined metadata for the given symbol
def write_metadata(self, symbol, metadata): ''' writes user defined metadata for the given symbol Parameters ---------- symbol: str symbol for the given item in the DB metadata: ? metadata to write ''' sym = self._get_symbol_info(s...
Returns a generator of ( Start End ) tuples for each chunk in the symbol
def get_chunk_ranges(self, symbol, chunk_range=None, reverse=False): """ Returns a generator of (Start, End) tuples for each chunk in the symbol Parameters ---------- symbol: str the symbol for the given item in the DB chunk_range: None, or a range object ...
Returns a generator that accesses each chunk in ascending order
def iterator(self, symbol, chunk_range=None): """ Returns a generator that accesses each chunk in ascending order Parameters ---------- symbol: str the symbol for the given item in the DB chunk_range: None, or a range object allows you to subset t...
Returns a generator that accesses each chunk in descending order
def reverse_iterator(self, symbol, chunk_range=None): """ Returns a generator that accesses each chunk in descending order Parameters ---------- symbol: str the symbol for the given item in the DB chunk_range: None, or a range object allows you to...
Catch - all decorator that handles AutoReconnect and OperationFailure errors from PyMongo
def mongo_retry(f): """ Catch-all decorator that handles AutoReconnect and OperationFailure errors from PyMongo """ log_all_exceptions = 'arctic' in f.__module__ if f.__module__ else False @wraps(f) def f_retry(*args, **kwargs): global _retry_count, _in_retry top_level = not...
Return tuple: [ start end ] of np. datetime64 dates that are inclusive of the passed in datetimes.
def _start_end(date_range, dts): """ Return tuple: [start, end] of np.datetime64 dates that are inclusive of the passed in datetimes. """ # FIXME: timezones assert len(dts) _assert_no_timezone(date_range) date_range = to_pandas_closed_closed(date_range, add_tz=False) start = np.datet...
Generate index of datetime64 - > item offset.
def _segment_index(self, recarr, existing_index, start, new_segments): """ Generate index of datetime64 -> item offset. Parameters: ----------- new_data: new data being written (or appended) existing_index: index field from the versions document of the previous version ...
Given a np. recarray find the first datetime64 column
def _datetime64_index(self, recarr): """ Given a np.recarray find the first datetime64 column """ # TODO: Handle multi-indexes names = recarr.dtype.names for name in names: if recarr[name].dtype == DTN64_DTYPE: return name return None
Given a version read the segment_index and return the chunks associated with the date_range. As the segment index is ( id - > last datetime ) we need to take care in choosing the correct chunks.
def _index_range(self, version, symbol, date_range=None, **kwargs): """ Given a version, read the segment_index and return the chunks associated with the date_range. As the segment index is (id -> last datetime) we need to take care in choosing the correct chunks. """ if date_range and '...
Given a recarr slice out the given artic. date. DateRange if a datetime64 index exists
def _daterange(self, recarr, date_range): """ Given a recarr, slice out the given artic.date.DateRange if a datetime64 index exists """ idx = self._datetime64_index(recarr) if idx and len(recarr): dts = recarr[idx] mask = Series(np.zeros(len(dts)), index=dts) ...
parses out the relevant information in version and returns it to the user in a dictionary
def get_info(self, version): """ parses out the relevant information in version and returns it to the user in a dictionary """ ret = super(PandasStore, self).get_info(version) ret['col_names'] = version['dtype_metadata'] ret['handler'] = self.__class__.__name__ ...
This function will transform arr into an array with the same type as dtype. It will do this by filling new columns with zeros ( or NaNs if it is a float column ). Also columns that are not in the new dtype will be dropped.
def _resize_with_dtype(arr, dtype): """ This function will transform arr into an array with the same type as dtype. It will do this by filling new columns with zeros (or NaNs, if it is a float column). Also, columns that are not in the new dtype will be dropped. """ structured_arrays = dtype.nam...
This function will decide whether to update the version document with forward pointers to segments. It detects cases where no prior writes/ appends have been performed with FW pointers and extracts the segment IDs. It also sets the metadata which indicate the mode of operation at the time of the version creation.
def _update_fw_pointers(collection, symbol, version, previous_version, is_append, shas_to_add=None): """ This function will decide whether to update the version document with forward pointers to segments. It detects cases where no prior writes/appends have been performed with FW pointers, and extracts the s...
This method updates the find query filter spec used to read the segment for a version. It chooses whether to query via forward pointers or not based on the version details and current mode of operation.
def _spec_fw_pointers_aware(symbol, version, from_index=None, to_index=None): """ This method updates the find query filter spec used to read the segment for a version. It chooses whether to query via forward pointers or not based on the version details and current mode of operation. """ spec = {'sy...
This method decides whether to convert an append to a full write in order to avoid data integrity errors
def _fw_pointers_convert_append_to_write(previous_version): """ This method decides whether to convert an append to a full write in order to avoid data integrity errors """ # Switching from ENABLED --> DISABLED/HYBRID when appending can cause integrity errors for subsequent reads: # - Assume the ...
Tuple describing range to read from the ndarray - closed: open
def _index_range(self, version, symbol, from_version=None, **kwargs): """ Tuple describing range to read from the ndarray - closed:open """ from_index = None if from_version: from_index = from_version['up_to'] return from_index, None
index_range is a 2 - tuple of integers - a [ from to ) range of segments to be read. Either from or to can be None indicating no bound.
def _do_read(self, collection, version, symbol, index_range=None): """ index_range is a 2-tuple of integers - a [from, to) range of segments to be read. Either from or to can be None, indicating no bound. """ from_index = index_range[0] if index_range else None to_ind...
Adds the library with the given date range to the underlying collection of libraries used by this store. The underlying libraries should not overlap as the date ranges are assumed to be CLOSED_CLOSED by this function and the rest of the class.
def add(self, date_range, library_name): """ Adds the library with the given date range to the underlying collection of libraries used by this store. The underlying libraries should not overlap as the date ranges are assumed to be CLOSED_CLOSED by this function and the rest of the class....
Split the tick data to the underlying collections and write the data to each low level library.
def write(self, symbol, data): """ Split the tick data to the underlying collections and write the data to each low level library. Args: symbol (str): the symbol for the timeseries data data (list of dicts or pandas dataframe): Tick data to write ...
Retrieve the libraries for the given date range the assumption is that the date ranges do not overlap and they are CLOSED_CLOSED.
def _get_library_metadata(self, date_range): """ Retrieve the libraries for the given date range, the assumption is that the date ranges do not overlap and they are CLOSED_CLOSED. At the moment the date range is mandatory """ if date_range is None: raise Exce...
Records a write request to be actioned on context exit. Takes exactly the same parameters as the regular library write call.
def write(self, symbol, data, prune_previous_version=True, metadata=None, **kwargs): """ Records a write request to be actioned on context exit. Takes exactly the same parameters as the regular library write call. """ if data is not None: # We only write data if exist...
Similar to DataFrame. to_records () Differences: Attempt type conversion for pandas columns stored as objects ( e. g. strings ) as we can only store primitives in the ndarray. Use dtype metadata to store column and index names.
def _to_records(self, df, string_max_len=None, forced_dtype=None): """ Similar to DataFrame.to_records() Differences: Attempt type conversion for pandas columns stored as objects (e.g. strings), as we can only store primitives in the ndarray. Use dtype metadat...
Convert efficiently the frame s object - columns/ object - index/ multi - index/ multi - column to records by creating a recarray only for the object fields instead for the whole dataframe. If we have no object dtypes we can safely convert only the first row to recarray to test if serializable. Previously we d serializ...
def fast_check_serializable(self, df): """ Convert efficiently the frame's object-columns/object-index/multi-index/multi-column to records, by creating a recarray only for the object fields instead for the whole dataframe. If we have no object dtypes, we can safely convert only the first...
Apply func to each chunk in lib. symbol
def read_apply(lib, symbol, func, chunk_range=None): """ Apply `func` to each chunk in lib.symbol Parameters ---------- lib: arctic library symbol: str the symbol for the given item in the DB chunk_range: None, or a range object allows you to subset the chunks by range ...
Return the symbols in this library.
def list_symbols(self, regex=None, as_of=None, **kwargs): """ Return the symbols in this library. Parameters ---------- as_of : `datetime.datetime` filter symbols valid at given time regex : `str` filter symbols by the passed in regular expr...
Return all metadata saved for symbol
def read_history(self, symbol): """ Return all metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item Returns ------- pandas.DateFrame containing timestamps and metadata entries """ find = se...
Return current metadata saved for symbol
def read(self, symbol, as_of=None): """ Return current metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item as_of : `datetime.datetime` return entry valid at given time Returns ------- ...
Manually overwrite entire metadata history for symbols in collection
def write_history(self, collection): """ Manually overwrite entire metadata history for symbols in `collection` Parameters ---------- collection : `list of pandas.DataFrame` with symbol names as headers and timestamps as indices (the same format as output...
Update metadata entry for symbol
def append(self, symbol, metadata, start_time=None): """ Update metadata entry for `symbol` Parameters ---------- symbol : `str` symbol name for the item metadata : `dict` to be persisted start_time : `datetime.datetime` when m...