text
stringlengths
81
112k
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_timezo...
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 start: first (0-based) offset of the new data segments: list of offsets. Eac...
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: ...
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 segm...
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(recar...
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) ...
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...
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 creatio...
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 th...
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 ENABLE...
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_...
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. ...
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. Arguments: date_range: A date range provid...
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 if a list of dicts is given the list must be in tim...
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 def _get_library_metadata(self, date_range): """ Retrieve the libraries for the given date range, the assumption ...
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 pa...
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. string_max_len: integer - enforces a string...
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. Previousl...
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 Returns ------- generator def read_apply(lib, symbol, fu...
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 expression kwargs : kwarg keys are used as fields to query fo...
Return all metadata saved for `symbol` Parameters ---------- symbol : `str` symbol name for the item Returns ------- pandas.DateFrame containing timestamps and metadata entries def read_history(self, symbol): """ Return all metadata saved fo...
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 ------- metadata def read(self, symbol, as_of=None): ""...
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 of read_history) Example: [p...
Update metadata entry for `symbol` Parameters ---------- symbol : `str` symbol name for the item metadata : `dict` to be persisted start_time : `datetime.datetime` when metadata becomes effective Default: datetime.datetime.utcnow()...
Prepend a metadata entry for `symbol` Parameters ---------- symbol : `str` symbol name for the item metadata : `dict` to be persisted start_time : `datetime.datetime` when metadata becomes effective Default: datetime.datetime.min ...
Delete current metadata of `symbol` Parameters ---------- symbol : `str` symbol name to delete Returns ------- Deleted metadata def pop(self, symbol): """ Delete current metadata of `symbol` Parameters ---------- sym...
Delete all metadata of `symbol` Parameters ---------- symbol : `str` symbol name to delete def purge(self, symbol): """ Delete all metadata of `symbol` Parameters ---------- symbol : `str` symbol name to delete """ ...
Generic query method. In reality, your storage class would have its own query methods, Performs a Mongo find on the Marketdata index metadata collection. See: http://api.mongodb.org/python/current/api/pymongo/collection.html def query(self, *args, **kwargs): """ Generi...
Database usage statistics. Used by quota. def stats(self): """ Database usage statistics. Used by quota. """ res = {} db = self._collection.database res['dbstats'] = db.command('dbstats') res['data'] = db.command('collstats', self._collection.name) res['t...
Simple persistence method def store(self, thing): """ Simple persistence method """ to_store = {'field1': thing.field1, 'date_field': thing.date_field, } to_store['stuff'] = Binary(cPickle.dumps(thing.stuff)) # Respect any soft-quo...
Read data for the named symbol. Returns a BitemporalItem object with a data and metdata element (as passed into write). Parameters ---------- symbol : `str` symbol name for the item as_of : `datetime.datetime` Return the data as it was as_of the point in ...
Append 'data' under the specified 'symbol' name to this library. Parameters ---------- symbol : `str` symbol name for the item data : `pd.DataFrame` to be persisted metadata : `dict` An optional dictionary of metadata to persist along with the...
Convert a string to a DateRange type. If you put only one date, it generates the relevant range for just that date or datetime till 24 hours later. You can optionally use mixtures of []/() around the DateRange for OPEN/CLOSED interval behaviour. Parameters ---------- str_range : `String` Th...
Returns a non-naive datetime.datetime. Interprets numbers as ms-since-epoch. Parameters ---------- date : `int` or `datetime.datetime` The datetime to convert default_tz : tzinfo The TimeZone to use if none is found. If not supplied, and the datetime doesn't have a timezo...
Pandas DateRange slicing is CLOSED-CLOSED inclusive at both ends. Parameters ---------- date_range : `DateRange` object converted to CLOSED_CLOSED form for Pandas slicing add_tz : `bool` Adds a TimeZone to the daterange start and end if it doesn't have one. Returns ---...
Convert a millisecond time value to an offset-aware Python datetime object. def ms_to_datetime(ms, tzinfo=None): """Convert a millisecond time value to an offset-aware Python datetime object.""" if not isinstance(ms, (int, long)): raise TypeError('expected integer, not %s' % type(ms)) if tzinfo is...
Convert a Python datetime object to a millisecond epoch (UTC) time value. def datetime_to_ms(d): """Convert a Python datetime object to a millisecond epoch (UTC) time value.""" try: millisecond = d.microsecond // 1000 return calendar.timegm(_add_tzone(d).utctimetuple()) * 1000 + millisecond ...
Convert a UTC datetime to datetime in local timezone def utc_dt_to_local_dt(dtm): """Convert a UTC datetime to datetime in local timezone""" utc_zone = mktz("UTC") if dtm.tzinfo is not None and dtm.tzinfo != utc_zone: raise ValueError( "Expected dtm without tzinfo or with UTC, not %r" %...
Create a new DateRange representing the maximal range enclosed by this range and other def intersection(self, other): """ Create a new DateRange representing the maximal range enclosed by this range and other """ startopen = other.startopen if self.start is None \ else self....
Create a new DateRange with the datetimes converted to dates and changing to CLOSED/CLOSED. def as_dates(self): """ Create a new DateRange with the datetimes converted to dates and changing to CLOSED/CLOSED. """ new_start = self.start.date() if self.start and isinstance(self.start, date...
Convert a DateRange into a MongoDb query string. FIXME: Mongo can only handle datetimes in queries, so we should make this handle the case where start/end are datetime.date and extend accordingly (being careful about the interval logic). def mongo_query(self): """ Convert a DateRange in...
Return the upper and lower bounds along with operators that are needed to do an 'in range' test. Useful for SQL commands. Returns ------- tuple: (`str`, `date`, `str`, `date`) (date_gt, start, date_lt, end) e.g.: ('>=', start_date, '<', en...
chunks the dataframe/series by dates Parameters ---------- df: pandas dataframe or series chunk_size: str any valid Pandas frequency string func: function func will be applied to each `chunk` generated by the chunker. This function CANNOT modi...
takes the range object used for this chunker type and converts it into a string that can be use for a mongo query that filters by the range returns ------- dict def to_mongo(self, range_obj): """ takes the range object used for this chunker type and conv...
ensures data is properly subset to the range in range_obj. (Depending on how the chunking is implemented, it might be possible to specify a chunk range that reads out more than the actual range eg: date range, chunked monthly. read out 2016-01-01 to 2016-01-02. This will read ALL of Janu...
Removes data within the bounds of the range object (inclusive) returns ------- data, filtered by range_obj def exclude(self, data, range_obj): """ Removes data within the bounds of the range object (inclusive) returns ------- data, filtered by range_obj...
Enable sharding on a library Parameters: ----------- arctic: `arctic.Arctic` Arctic class library_name: `basestring` library name hashed: `bool` if True, use hashed sharding, if False, use range sharding See https://docs.mongodb.com/manual/core/hashed-sharding/, as well as...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one def insert_one(self, document, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one """ self._arctic_li...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many def insert_many(self, documents, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many """ self._arcti...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one def update_one(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one """ self._arc...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many def update_many(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many """ self._...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one def replace_one(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.replace_one """ s...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace def find_one_and_replace(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_re...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_update def find_one_and_update(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_update ...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute isn't idempotent. def bulk_write(self, requests, **kwargs): """ S...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.count def count(self, filter, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.count """ return mongo_count(self._collect...
Return a new timezone (tzinfo object) based on the zone using the python-dateutil package. The concise name 'mktz' is for convenient when using it on the console. Parameters ---------- zone : `String` The zone for the timezone. This defaults to local, returning: tzlocal.g...
Ensure that symbol(s) have contiguous segment ids Parameters ---------- library: arctic library symbol: None, str, list of str None: all symbols str: single symbol list: list of symbols Returns ------- list of str - Symbols 'fixed' def segment_id_repair(library, sy...
The database state created by this fixture is equivalent to the following operations using arctic 1.40 or previous: arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month') library = arctic.get_library('arctic_test.TEST') df = pd.DataFrame([[1,2], [3,4]], index=['x','...
The database state created by this fixture is equivalent to the following operations using arctic 1.40 or previous: arctic.initialize_library('arctic_test.TEST', m.VERSION_STORE, segment='month') library = arctic.get_library('arctic_test.TEST') arr = np.arange(2).astype([('abc', 'int64')]) ...
Return the symbols in this library. Parameters ---------- all_symbols : `bool` If True returns all symbols under all snapshots, even if the symbol has been deleted in the current version (i.e. it exists under a snapshot... Default: False snapshot : `str` ...
Return True if the 'symbol' exists in this library AND the symbol isn't deleted in the specified as_of. It's possible for a deleted symbol to exist in older snapshots. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `dat...
Return the audit log associated with a given symbol Parameters ---------- symbol : `str` symbol name for the item def read_audit_log(self, symbol=None, message=None): """ Return the audit log associated with a given symbol Parameters ---------- ...
Return a list of versions filtered by the passed in parameters. Parameters ---------- symbol : `str` Symbol to return versions for. If None returns versions across all symbols in the library. snapshot : `str` Return the versions contained in the name...
Read data for the named symbol. Returns a VersionedItem object with a data and metdata element (as passed into write). Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or `int` or `datetime.datetime` Return the data as it was a...
Reads and returns information about the data stored for symbol Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was as_of the point in time. `int` : specific version number...
Return the numerical representation of the arctic version used to write the last (or as_of) version for the given symbol. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was a...
Return the metadata saved for a symbol. This method is fast as it doesn't actually load the data. Parameters ---------- symbol : `str` symbol name for the item as_of : `str` or int or `datetime.datetime` Return the data as it was as_of the point in time....
Append 'data' under the specified 'symbol' name to this library. The exact meaning of 'append' is left up to the underlying store implementation. Parameters ---------- symbol : `str` symbol name for the item data : to be persisted metadata : `dict...
Write 'data' under the specified 'symbol' name to this library. Parameters ---------- symbol : `str` symbol name for the item data : to be persisted metadata : `dict` an optional dictionary of metadata to persist along with the symbol. ...
Write 'metadata' under the specified 'symbol' name to this library. The data will remain unchanged. A new version will be created. If the symbol is missing, it causes a write with empty data (None, pickled, can't append) and the supplied metadata. Returns a VersionedItem object only with...
Restore the specified 'symbol' data and metadata to the state of a given version/snapshot/date. Returns a VersionedItem object only with a metadata element. Fast operation: Zero data/segment read/write operations. Parameters ---------- symbol : `str` symbol name for ...
Find all non-snapshotted versions of a symbol that are older than a version that's at least keep_mins minutes old. Based on documents available on the secondary. def _find_prunable_version_ids(self, symbol, keep_mins): """ Find all non-snapshotted versions of a symbol that are older th...
Return all base_version_ids for a symbol that are not bases of version_ids def _find_base_version_ids(self, symbol, version_ids): """ Return all base_version_ids for a symbol that are not bases of version_ids """ cursor = self._versions.find({'symbol': symbol, ...
Prune versions, not pointed at by snapshots which are at least keep_mins old. Prune will never remove all versions. def _prune_previous_versions(self, symbol, keep_mins=120, keep_version=None, new_version_shas=None): """ Prune versions, not pointed at by snapshots which are at least keep_mins o...
Delete the n'th version of this symbol from the historical collection. def _delete_version(self, symbol, version_num, do_cleanup=True): """ Delete the n'th version of this symbol from the historical collection. """ version = self._versions.find_one({'symbol': symbol, 'version': version_...
Delete all versions of the item from the current library which aren't currently part of some snapshot. Parameters ---------- symbol : `str` symbol name to delete def delete(self, symbol): """ Delete all versions of the item from the current library which are...
Creates an audit entry, which is much like a snapshot in that it references versions and provides some history of the changes made. def _write_audit(self, user, message, changed_version): """ Creates an audit entry, which is much like a snapshot in that it references versions and provid...
Snapshot versions of symbols in the library. Can be used like: Parameters ---------- snap_name : `str` name of the snapshot metadata : `dict` an optional dictionary of metadata to persist along with the symbol. skip_symbols : `collections.Iterable` ...
Delete a named snapshot Parameters ---------- symbol : `str` The snapshot name to delete def delete_snapshot(self, snap_name): """ Delete a named snapshot Parameters ---------- symbol : `str` The snapshot name to delete "...
Return storage statistics about the library Returns ------- dictionary of storage stats def stats(self): """ Return storage statistics about the library Returns ------- dictionary of storage stats """ res = {} db = self._collect...
Run a consistency check on this VersionStore library. def _fsck(self, dry_run): """ Run a consistency check on this VersionStore library. """ # Cleanup Orphaned Chunks self._cleanup_orphaned_chunks(dry_run) # Cleanup unreachable SHAs (forward pointers) self._clea...
Fixes any chunks who have parent pointers to missing versions. Removes the broken parent pointer and, if there are no other parent pointers for the chunk, removes the chunk. def _cleanup_orphaned_chunks(self, dry_run): """ Fixes any chunks who have parent pointers to missing versions. ...
Fixes any versions who have parent pointers to missing snapshots. Note, doesn't delete the versions, just removes the parent pointer if it no longer exists in snapshots. def _cleanup_orphaned_versions(self, dry_run): """ Fixes any versions who have parent pointers to missing snapshots. ...
Set the global multithread compression mode Parameters ---------- mode: `bool` True: Use parallel compression. False: Use sequential compression def enable_parallel_lz4(mode): """ Set the global multithread compression mode Parameters ---------- mode: `bool` ...
Set the size of the compression workers thread pool. If the pool is already created, it waits until all jobs are finished, and then proceeds with setting the new size. Parameters ---------- pool_size : `int` The size of the pool (must be a positive integer) Returns ------- ...
Compress an array of strings Parameters ---------- str_list: `list[str]` The input list of strings which need to be compressed. withHC: `bool` This flag controls whether lz4HC will be used. Returns ------- `list[str` The list of the compressed strings. ...
Decompress a list of strings def decompress_array(str_list): """ Decompress a list of strings """ global _compress_thread_pool if not str_list: return str_list if not ENABLE_PARALLEL or len(str_list) <= LZ4_N_PARALLEL: return [lz4_decompress(chunk) for chunk in str_list] ...
Equivalent to numpy.split(array_2d, slices), but avoids fancy indexing def _split_arrs(array_2d, slices): """ Equivalent to numpy.split(array_2d, slices), but avoids fancy indexing """ if len(array_2d) == 0: return np.empty(0, dtype=np.object) rtn = np.empty(len(slices) + 1, dtype=...
Checksum the passed in dictionary def checksum(symbol, doc): """ Checksum the passed in dictionary """ sha = hashlib.sha1() sha.update(symbol.encode('ascii')) for k in sorted(iter(doc.keys()), reverse=True): v = doc[k] if isinstance(v, six.binary_type): sha.update(do...
Helper method for cleaning up chunks from a version store def cleanup(arctic_lib, symbol, version_ids, versions_coll, shas_to_delete=None, pointers_cfgs=None): """ Helper method for cleaning up chunks from a version store """ pointers_cfgs = set(pointers_cfgs) if pointers_cfgs else set() collection...
Factory function to initialise the correct Pickle load function based on the Pandas version. def _define_compat_pickle_load(): """Factory function to initialise the correct Pickle load function based on the Pandas version. """ if pd.__version__.startswith("0.14"): return pickle.load ret...
This is a utility function to produce text output with details about the versions of a given symbol. It is useful for debugging corruption issues and to mark corrupted versions. Parameters ---------- l : `arctic.store.version_store.VersionStore` The VersionStore instance against which the analys...
This method hints whether the symbol/version are safe for appending in two ways: 1. It verifies whether the symbol is already corrupted (fast, doesn't read the data) 2. It verififes that the symbol is safe to append, i.e. there are no subsequent appends, or dangling segments from a failed append. Par...
This method can be used to check for a corrupted version. Will continue to a full read (slower) if the internally invoked fast-detection does not locate a corruption. Parameters ---------- l : `arctic.store.version_store.VersionStore` The VersionStore instance against which ...
Converts object arrays of strings to numpy string arrays def _convert_types(self, a): """ Converts object arrays of strings to numpy string arrays """ # No conversion for scalar type if a.dtype != 'object': return a, None # We can't infer the type of an empt...
Convert a Pandas DataFrame to SON. Parameters ---------- df: DataFrame The Pandas DataFrame to encode def docify(self, df): """ Convert a Pandas DataFrame to SON. Parameters ---------- df: DataFrame The Pandas DataFrame to enco...
Decode a Pymongo SON object into an Pandas DataFrame def objify(self, doc, columns=None): """ Decode a Pymongo SON object into an Pandas DataFrame """ cols = columns or doc[METADATA][COLUMNS] data = {} for col in cols: # if there is missing data in a chunk, ...
Deserializes SON to a DataFrame Parameters ---------- data: SON data columns: None, or list of strings optionally you can deserialize a subset of the data in the SON. Index columns are ALWAYS deserialized, and should not be specified Returns ----...
Create and initialize the keybinding manager. :type get_fuzzy_match: callable :param get_fuzzy_match: Gets the fuzzy matching config. :type set_fuzzy_match: callable :param set_fuzzy_match: Sets the fuzzy matching config. :type get_enable_vi_bindings: callable :param g...