INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 date_range : `date.DateRange` Returns ticks in the specified DateRange ...
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. Parameters ---------- symbol : `str` symbol name for the item data : list of dicts or a pandas.DataFrame List of ticks to store to the tick-store. if a list of dicts, each dict must contain a 'index' datetime ...
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 Parameters ---------- symbol : `str` symbol name for the item
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 Parameters ---------- symbol : `str` symbol name for the item
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 returns ------- ('NA', 'NA', 'NA', 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. PyMongo 2.6 changed the auth API to raise on Auth failure.
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 Parameters --------- connection_string: `str` Format must be one of the following: library@trading for known mongo servers library@hostname:port Returns: -------- Arctic library
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. 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 authentication succeeded.
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. Parameters ---------- df: ``DataFrame`` Pandas dataframe with a MultiIndex grouping_level: ``int`` or ``str`` or ``list`` of ``str`` Index level to group by. Defaults to 0. aggregate_level: ``i...
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. Parameters ---------- df: ``pd.DataFrame`` Dataframe with a MultiIndex index as_of: ``datetime`` Return a timeseries with values observed <= this as-of date. By default, the latest observed ...
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. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' Returns ------- `bool` True if the library with the given name already exists, False otherwise
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. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library' lib_type : `str` The type of the library. e.g. arctic.VERSION_STORE or arctic.TICK_STORE Or any type regis...
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. Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.library'
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] Parameters ---------- library : `str` The name of the library. e.g. 'library' or 'user.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 Parameters ---------- from_lib: str The name of the library to be renamed to_lib: str The new name of the 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. A quota of 0 is 'unlimited'
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 Parameters ---------- symbol : str symbol name for the item chunk_range: range object a date range to delete audit: dict dict to store in the audit log
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 Parameters ---------- partial: None or str if not none, use this string to do a partial match on symbol names Returns ------- list of str
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 Parameters ---------- from_symbol: str the existing symbol that will be renamed to_symbol: str the new symbol name audit: dict audit information
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. Parameters ---------- symbol: str, or list of str the symbol(s) to retrieve chunk_range: object corresponding range object for the specified chunker (for DateChunker it is a DateRange object or a Dateti...
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 Parameters ---------- symbol: str optionally only retrieve specific symbol's audit information Returns ------- list of dicts
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 Parameters ---------- symbol: str the symbol that will be used to reference the written data item: Dataframe or Series the data to write the database metadata: ? optional per symbol metadata ...
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. Is not idempotent Parameters ---------- symbol: str the symbol for the given item in the DB item: DataFrame or Series the data to append upsert: write data if symbol does not ex...
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. Is idempotent Parameters ---------- symbol: str the symbol for the given item in the DB item: DataFrame or Series the data to update metadata: ? optional per symbol metadat...
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 Parameters ---------- symbol: str the symbol for the given item in the DB Returns ------- 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 Parameters ---------- symbol: str symbol for the given item in the DB Returns ------- ?
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 Parameters ---------- symbol: str symbol for the given item in the DB metadata: ? metadata to write
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 Parameters ---------- 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 reverse: boolean re...
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 Parameters ---------- 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 ------- genera...
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 Parameters ---------- 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 ------- gener...
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. 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...
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 creatio...
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. Arguments: date_range: A date range provid...
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. 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...
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. 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 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. string_max_len: integer - enforces a string...
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. Previousl...
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 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, 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. 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...
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` 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 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` 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): """ 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` 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...
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` 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()
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...
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
def prepend(self, symbol, metadata, start_time=None): """ Prepend a metadata entry for `symbol` Parameters ---------- symbol : `str` symbol name for the item metadata : `dict` to be persisted start_time : `datetime.datetime` wh...
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 ---------- symbol : `str` symbol name to delete Returns ------- Deleted metadata """ last_metadata = self.find_one({'symbol': symbol}, sort=[('start_tim...
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 """ logger.warning("Deleting entire metadata history for %r from %r" % (symbol, self._arctic_lib.get_name())) self.delete_m...
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): """ 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 ...
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['totals'] = {'count': res['data']['count'], ...
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-quota on write - raises if sta...
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 ...
def read(self, symbol, as_of=None, raw=False, **kwargs): # TODO: shall we block from_version from getting into super.read? """Read data for the named symbol. Returns a BitemporalItem object with a data and metdata element (as passed into write). Parameters ---------- sym...
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...
def update(self, symbol, data, metadata=None, upsert=True, as_of=None, **kwargs): """ Append 'data' under the specified 'symbol' name to this library. Parameters ---------- symbol : `str` symbol name for the item data : `pd.DataFrame` to be persisted ...
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...
def to_dt(date, default_tz=None): """ 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, ...
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...
def string_to_daterange(str_range, delimiter='-', as_dates=False, interval=CLOSED_CLOSED): """ 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...
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 ---...
def to_pandas_closed_closed(date_range, add_tz=True): """ 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 ...
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 None: tzinfo = mktz() return datetime.datetime.fromtimestamp(ms...
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 except AttributeError: raise TypeError('expect Python datetime obj...
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" % ( dtm.tzinfo ) ) ...
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.startopen if other.start is None \ else other.startopen if self.start < othe...
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, datetime.datetime) else self.start new_end = self.end.date() if self.end and isinstance(s...
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 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). """ com...
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...
def get_date_bounds(self): """ 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...
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...
def to_chunks(self, df, chunk_size='D', func=None, **kwargs): """ 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 appli...
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 converts it into a string that can be use for a mongo query that filters by the range returns ------- dict """ if isinstance(range_obj, (pd.DatetimeIndex, tup...
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...
def filter(self, data, range_obj): """ 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-...
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 """ if isinstance(range_obj, (pd.DatetimeIndex, tuple)): range_obj = DateRange(range_obj[0], 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...
def enable_sharding(arctic, library_name, hashed=True, key='symbol'): """ 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 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_lib.check_quota() return self._collection.insert_one(document, **kwargs)
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._arctic_lib.check_quota() return self._collection.insert_many(documents, **kwargs)
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._arctic_lib.check_quota() return self._collection.update_one(filter, update, **kwargs)
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._arctic_lib.check_quota() return self._collection.update_many(filter, update, **kwargs)
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 """ self._arctic_lib.check_quota() return self._collection.replace_one(filter, replacement, **kwargs)
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_replace """ self._arctic_lib.check_quota() return self._collection.find_one_and_replace(filter, repl...
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 """ self._arctic_lib.check_quota() return self._collection.find_one_and_update(filter, update, **kw...
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): """ 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. ...
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._collection, filter=filter, **kwargs)
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...
def mktz(zone=None): """ 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...
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, symbol=None): """ 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...