text stringlengths 81 112k |
|---|
Infer the domain from a collection of terms.
The algorithm for inferring domains is as follows:
- If all input terms have a domain of GENERIC, the result is GENERIC.
- If there is exactly one non-generic domain in the input terms, the result
is that domain.
- Otherwise, an AmbiguousDomain erro... |
Given a date, align it to the calendar of the pipeline's domain.
Parameters
----------
dt : pd.Timestamp
Returns
-------
pd.Timestamp
def roll_forward(self, dt):
"""
Given a date, align it to the calendar of the pipeline's domain.
Parameters
... |
Returns the date index and sid columns shared by a list of dataframes,
ensuring they all match.
Parameters
----------
frames : list[pd.DataFrame]
A list of dataframes indexed by day, with a column per sid.
Returns
-------
days : np.array[datetime64[ns]]
The days in these da... |
Parameters
----------
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row for
each date and a column for each sid, as passed to write().
Returns
-------
start_date_ixs : np.array[int64]
The index of the first date with non-nan values, f... |
Write the OHLCV data for one country to the HDF5 file.
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
frames : dict[str, pd.DataFrame]
A dict mapping each OHLCV field to a dataframe with a row
for each dat... |
Parameters
----------
country_code : str
The ISO 3166 alpha-2 country code for this country.
data : iterable[tuple[int, pandas.DataFrame]]
The data chunks to write. Each chunk should be a tuple of
sid and the data for that asset.
scaling_factors : dict... |
Construct from an h5py.File and a country code.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
def from_file(cls, h5_file, country_code):
"""
Con... |
Construct from a file path and a country code.
Parameters
----------
path : str
The path to an HDF5 daily pricing file.
country_code : str
The ISO 3166 alpha-2 country code for the country to read.
def from_path(cls, path, country_code):
"""
Cons... |
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
assets : list of int
The asset identifiers in the ... |
Build an indexer mapping ``self.sids`` to ``assets``.
Parameters
----------
assets : list[int]
List of assets requested by a caller of ``load_raw_arrays``.
Returns
-------
index : np.array[int64]
Index array containing the index in ``self.sids`` ... |
Validate that asset identifiers are contained in the daily bars.
Parameters
----------
assets : array-like[int]
The asset identifiers to validate.
Raises
------
NoDataForSid
If one or more of the provided asset identifiers are not
cont... |
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC name for the desired data point.
Returns
-... |
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the last traded day.
dt : pd.Timestamp
The dt a... |
Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file.
def from_file(cls, h5_file):
"""
Construct from an h5py.File.
Parameters
----------
h5_file : h5py.File
An HDF5 daily pricing file... |
Parameters
----------
columns : list of str
'open', 'high', 'low', 'close', or 'volume'
start_date: Timestamp
Beginning of the window range.
end_date: Timestamp
End of the window range.
assets : list of int
The asset identifiers in the ... |
Returns
-------
sessions : DatetimeIndex
All session labels (unioning the range for all assets) which the
reader can provide.
def sessions(self):
"""
Returns
-------
sessions : DatetimeIndex
All session labels (unioning the range for all ... |
Retrieve the value at the given coordinates.
Parameters
----------
sid : int
The asset identifier.
dt : pd.Timestamp
The timestamp for the desired data point.
field : string
The OHLVC name for the desired data point.
Returns
-... |
Get the latest day on or before ``dt`` in which ``asset`` traded.
If there are no trades on or before ``dt``, returns ``pd.NaT``.
Parameters
----------
asset : zipline.asset.Asset
The asset for which to get the last traded day.
dt : pd.Timestamp
The dt a... |
Update dataframes in place to set indentifier columns as indices.
For each input frame, if the frame has a column with the same name as its
associated index column, set that column as the index.
Otherwise, assume the index already contains identifiers.
If frames are passed as None, they're ignored.
... |
Takes in a symbol that may be delimited and splits it in to a company
symbol and share class symbol. Also returns the fuzzy symbol, which is the
symbol without any fuzzy characters at all.
Parameters
----------
symbol : str
The possibly-delimited symbol to be split
Returns
-------
... |
Generates an output dataframe from the given subset of user-provided
data, the given column names, and the given default values.
Parameters
----------
data_subset : DataFrame
A DataFrame, usually from an AssetData object,
that contains the user's input metadata for the asset type being
... |
Check that there are no cases where multiple symbols resolve to the same
asset at the same time in the same country.
Parameters
----------
df : pd.DataFrame
The equity symbol mappings table.
exchanges : pd.DataFrame
The exchanges table.
asset_exchange : pd.Series
A serie... |
Split out the symbol: sid mappings from the raw data.
Parameters
----------
df : pd.DataFrame
The dataframe with multiple rows for each symbol: sid pair.
exchanges : pd.DataFrame
The exchanges table.
Returns
-------
asset_info : pd.DataFrame
The asset info with one ... |
Convert a timeseries into an Int64Index of nanoseconds since the epoch.
Parameters
----------
dt_series : pd.Series
The timeseries to convert.
Returns
-------
idx : pd.Int64Index
The index converted to nanoseconds since the epoch.
def _dt_to_epoch_ns(dt_series):
"""Convert... |
Checks for a version value in the version table.
Parameters
----------
conn : sa.Connection
The connection to use to perform the check.
version_table : sa.Table
The version table of the asset database
expected_version : int
The expected version of the asset database
Rai... |
Inserts the version value in to the version table.
Parameters
----------
conn : sa.Connection
The connection to use to execute the insert.
version_table : sa.Table
The version table of the asset database
version_value : int
The version to write in to the database
def write_... |
Write asset metadata to a sqlite database in the format that it is
stored in the assets db.
Parameters
----------
equities : pd.DataFrame, optional
The equity metadata. The columns for this dataframe are:
symbol : str
The ticker symbol for th... |
Write asset metadata to a sqlite database.
Parameters
----------
equities : pd.DataFrame, optional
The equity metadata. The columns for this dataframe are:
symbol : str
The ticker symbol for this equity.
asset_name : str
... |
Checks if any tables are present in the current assets database.
Parameters
----------
txn : Transaction
The open transaction to check in.
Returns
-------
has_tables : bool
True if any tables are present, otherwise False.
def _all_tables_present... |
Connect to database and create tables.
Parameters
----------
txn : sa.engine.Connection, optional
The transaction to execute in. If this is not provided, a new
transaction will be started with the engine provided.
Returns
-------
metadata : sa.Me... |
Returns a standard set of pandas.DataFrames:
equities, futures, exchanges, root_symbols
def _load_data(self,
equities,
futures,
exchanges,
root_symbols,
equity_supplementary_mappings):
"""
Returns a s... |
Given an expression representing data to load, perform normalization and
forward-filling and return the data, materialized. Only accepts data with a
`sid` field.
Parameters
----------
assets : pd.int64index
the assets to load data for.
data_query_cutoff_times : pd.DatetimeIndex
... |
Convert a tuple into a range with error handling.
Parameters
----------
tup : tuple (len 2 or 3)
The tuple to turn into a range.
Returns
-------
range : range
The range from the tuple.
Raises
------
ValueError
Raised when the tuple length is not 2 or 3.
de... |
Convert a tuple into a range but pass ranges through silently.
This is useful to ensure that input is a range so that attributes may
be accessed with `.start`, `.stop` or so that containment checks are
constant time.
Parameters
----------
tup_or_range : tuple or range
A tuple to pass t... |
Check that the steps of ``a`` and ``b`` are both 1.
Parameters
----------
a : range
The first range to check.
b : range
The second range to check.
Raises
------
ValueError
Raised when either step is not 1.
def _check_steps(a, b):
"""Check that the steps of ``a`... |
Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != 1.
def overlap(a, b):
... |
Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range.
def merge(a, b):
"""Merge two ranges with step == 1.
Parameters
----------
a : range
The first range.
b : range
The second range.
"""
... |
helper for ``_group_ranges``
def _combine(n, rs):
"""helper for ``_group_ranges``
"""
try:
r, rs = peek(rs)
except StopIteration:
yield n
return
if overlap(n, r):
yield merge(n, r)
next(rs)
for r in rs:
yield r
else:
yield n
... |
Return any ranges that intersect.
Parameters
----------
ranges : iterable[ranges]
A sequence of ranges to check for intersections.
Returns
-------
intersections : iterable[ranges]
A sequence of all of the ranges that intersected in ``ranges``.
Examples
--------
>>>... |
Returns a handle to data file.
Creates containing directory, if needed.
def get_data_filepath(name, environ=None):
"""
Returns a handle to data file.
Creates containing directory, if needed.
"""
dr = data_root(environ)
if not os.path.exists(dr):
os.makedirs(dr)
return os.pat... |
Does `series_or_df` have data on or before first_date and on or after
last_date?
def has_data_for_dates(series_or_df, first_date, last_date):
"""
Does `series_or_df` have data on or before first_date and on or after
last_date?
"""
dts = series_or_df.index
if not isinstance(dts, pd.DatetimeI... |
Load benchmark returns and treasury yield curves for the given calendar and
benchmark symbol.
Benchmarks are downloaded as a Series from IEX Trading. Treasury curves
are US Treasury Bond rates and are downloaded from 'www.federalreserve.gov'
by default. For Canadian exchanges, a loader for Canadian b... |
Ensure we have benchmark data for `symbol` from `first_date` to `last_date`
Parameters
----------
symbol : str
The symbol for the benchmark to load.
first_date : pd.Timestamp
First required date for the cache.
last_date : pd.Timestamp
Last required date for the cache.
no... |
Ensure we have treasury data from treasury module associated with
`symbol`.
Parameters
----------
symbol : str
Benchmark symbol for which we're loading associated treasury curves.
first_date : pd.Timestamp
First date required to be in the cache.
last_date : pd.Timestamp
... |
Specialize a term if it's loadable.
def maybe_specialize(term, domain):
"""Specialize a term if it's loadable.
"""
if isinstance(term, LoadableTerm):
return term.specialize(domain)
return term |
Add a term and all its children to ``graph``.
``parents`` is the set of all the parents of ``term` that we've added
so far. It is only used to detect dependency cycles.
def _add_to_graph(self, term, parents):
"""
Add a term and all its children to ``graph``.
``parents`` is the... |
Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed.
def execution_order(self, refcounts):
"""
Return a topologically-sorted iterator over the terms in ``self`` which
need to be computed.
"""
return iter(nx.topological_sort(
... |
Calculate initial refcounts for execution of this graph.
Parameters
----------
initial_terms : iterable[Term]
An iterable of terms that were pre-computed before graph execution.
Each node starts with a refcount equal to its outdegree, and output
nodes get one extra ... |
Decrement terms recursively.
Notes
-----
This should only be used to build the initial workspace, after that we
should use:
:meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`
def _decref_dependencies_recursive(self, term, refcounts, garbage):
"""
Decr... |
Decrement in-edges for ``term`` after computation.
Parameters
----------
term : zipline.pipeline.Term
The term whose parents should be decref'ed.
refcounts : dict[Term -> int]
Dictionary of refcounts.
Return
------
garbage : set[Term]
... |
For all pairs (term, input) such that `input` is an input to `term`,
compute a mapping::
(term, input) -> offset(term, input)
where ``offset(term, input)`` is the number of rows that ``term``
should truncate off the raw array produced for ``input`` before using
it. We compu... |
A dict mapping `term` -> `# of extra rows to load/compute of `term`.
Notes
----
This value depends on the other terms in the graph that require `term`
**as an input**. This is not to be confused with `term.dependencies`,
which describes how many additional rows of `term`'s inpu... |
Ensure that we're going to compute at least N extra rows of `term`.
def _ensure_extra_rows(self, term, N):
"""
Ensure that we're going to compute at least N extra rows of `term`.
"""
attrs = self.graph.node[term]
attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0)) |
Load mask and mask row labels for term.
Parameters
----------
term : Term
The term to load the mask and labels for.
root_mask_term : Term
The term that represents the root asset exists mask.
workspace : dict[Term, any]
The values that have bee... |
Make sure that we've specialized all loadable terms in the graph.
def _assert_all_loadable_terms_specialized_to(self, domain):
"""Make sure that we've specialized all loadable terms in the graph.
"""
for term in self.graph.node:
if isinstance(term, LoadableTerm):
ass... |
Make an extension for an AdjustedArrayWindow specialization.
def window_specialization(typename):
"""Make an extension for an AdjustedArrayWindow specialization."""
return Extension(
'zipline.lib._{name}window'.format(name=typename),
['zipline/lib/_{name}window.pyx'.format(name=typename)],
... |
Read a requirements.txt file, expressed as a path relative to Zipline root.
Returns requirements with the pinned versions as lower bounds
if `strict_bounds` is falsey.
def read_requirements(path,
strict_bounds,
conda_format=False,
filter_names=... |
Normalize a time. If the time is tz-naive, assume it is UTC.
def ensure_utc(time, tz='UTC'):
"""
Normalize a time. If the time is tz-naive, assume it is UTC.
"""
if not time.tzinfo:
time = time.replace(tzinfo=pytz.timezone(tz))
return time.replace(tzinfo=pytz.utc) |
Builds the offset argument for event rules.
def _build_offset(offset, kwargs, default):
"""
Builds the offset argument for event rules.
"""
if offset is None:
if not kwargs:
return default # use the default.
else:
return _td_check(datetime.timedelta(**kwargs))
... |
Builds the date argument for event rules.
def _build_date(date, kwargs):
"""
Builds the date argument for event rules.
"""
if date is None:
if not kwargs:
raise ValueError('Must pass a date or kwargs')
else:
return datetime.date(**kwargs)
elif kwargs:
... |
Builds the time argument for event rules.
def _build_time(time, kwargs):
"""
Builds the time argument for event rules.
"""
tz = kwargs.pop('tz', 'UTC')
if time:
if kwargs:
raise ValueError('Cannot pass kwargs and a time')
else:
return ensure_utc(time, tz)
... |
A preprocessor that coerces integral floats to ints.
Receipt of non-integral floats raises a TypeError.
def lossless_float_to_int(funcname, func, argname, arg):
"""
A preprocessor that coerces integral floats to ints.
Receipt of non-integral floats raises a TypeError.
"""
if not isinstance(ar... |
Constructs an event rule from the factory api.
def make_eventrule(date_rule, time_rule, cal, half_days=True):
"""
Constructs an event rule from the factory api.
"""
_check_if_not_called(date_rule)
_check_if_not_called(time_rule)
if half_days:
inner_rule = date_rule & time_rule
else... |
Adds an event to the manager.
def add_event(self, event, prepend=False):
"""
Adds an event to the manager.
"""
if prepend:
self._events.insert(0, event)
else:
self._events.append(event) |
Calls the callable only when the rule is triggered.
def handle_data(self, context, data, dt):
"""
Calls the callable only when the rule is triggered.
"""
if self.rule.should_trigger(dt):
self.callback(context, data) |
Composes the two rules with a lazy composer.
def should_trigger(self, dt):
"""
Composes the two rules with a lazy composer.
"""
return self.composer(
self.first.should_trigger,
self.second.should_trigger,
dt
) |
Given a date, find that day's open and period end (open + offset).
def calculate_dates(self, dt):
"""
Given a date, find that day's open and period end (open + offset).
"""
period_start, period_close = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt)... |
Given a dt, find that day's close and period start (close - offset).
def calculate_dates(self, dt):
"""
Given a dt, find that day's close and period start (close - offset).
"""
period_end = self.cal.open_and_close_for_session(
self.cal.minute_to_session_label(dt),
)[... |
Drops any record where a value would not fit into a uint32.
Parameters
----------
df : pd.DataFrame
The dataframe to winsorise.
invalid_data_behavior : {'warn', 'raise', 'ignore'}
What to do when data is outside the bounds of a uint32.
*columns : iterable[str]
The names of t... |
Parameters
----------
data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]]
The data chunks to write. Each chunk should be a tuple of sid
and the data for that asset.
assets : set[int], optional
The assets that should be in ``data``. If this is provide... |
Read CSVs as DataFrames from our asset map.
Parameters
----------
asset_map : dict[int -> str]
A mapping from asset id to file path with the CSV data for that
asset
show_progress : bool
Whether or not to show a progress bar while writing.
inva... |
Internal implementation of write.
`iterator` should be an iterator yielding pairs of (asset, ctable).
def _write_internal(self, iterator, assets):
"""
Internal implementation of write.
`iterator` should be an iterator yielding pairs of (asset, ctable).
"""
total_rows =... |
Compute the raw row indices to load for each asset on a query for the
given dates after applying a shift.
Parameters
----------
start_idx : int
Index of first date for which we want data.
end_idx : int
Index of last date for which we want data.
as... |
Get the colname from daily_bar_table and read all of it into memory,
caching the result.
Parameters
----------
colname : string
A name of a OHLCV carray in the daily_bar_table
Returns
-------
array (uint32)
Full read array of the carray i... |
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
Returns
-------
int
Index into the data tape for the given sid and day.
Raises a NoDataOnDate exce... |
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close', 'volume')
Returns
-------
floa... |
Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine
def init_engine(self, get_loader):
"""
Construct and store a PipelineEngine from loader.
If get_loader is None, constructs an ExplodingPipelineEngine
"""
if g... |
Call self._initialize with `self` made available to Zipline API
functions.
def initialize(self, *args, **kwargs):
"""
Call self._initialize with `self` made available to Zipline API
functions.
"""
with ZiplineAPI(self):
self._initialize(self, *args, **kwargs) |
If the clock property is not set, then create one based on frequency.
def _create_clock(self):
"""
If the clock property is not set, then create one based on frequency.
"""
trading_o_and_c = self.trading_calendar.schedule.ix[
self.sim_params.sessions]
market_closes =... |
Compute any pipelines attached with eager=True.
def compute_eager_pipelines(self):
"""
Compute any pipelines attached with eager=True.
"""
for name, pipe in self._pipelines.items():
if pipe.eager:
self.pipeline_output(name) |
Run the algorithm.
def run(self, data_portal=None):
"""Run the algorithm.
"""
# HACK: I don't think we really want to support passing a data portal
# this late in the long term, but this is needed for now for backwards
# compat downstream.
if data_portal is not None:
... |
If there is a capital change for a given dt, this means the the change
occurs before `handle_data` on the given dt. In the case of the
change being a target value, the change will be computed on the
portfolio value according to prices at the given dt
`portfolio_value_adjustment`, if spe... |
Query the execution environment.
Parameters
----------
field : {'platform', 'arena', 'data_frequency',
'start', 'end', 'capital_base', 'platform', '*'}
The field to query. The options have the following meanings:
arena : str
The arena... |
Fetch a csv from a remote url and register the data so that it is
queryable from the ``data`` object.
Parameters
----------
url : str
The url of the csv file to load.
pre_func : callable[pd.DataFrame -> pd.DataFrame], optional
A callback to allow preproce... |
Adds an event to the algorithm's EventManager.
Parameters
----------
rule : EventRule
The rule for when the callback should be triggered.
callback : callable[(context, data) -> None]
The function to execute when the rule is triggered.
def add_event(self, rule, c... |
Schedules a function to be called according to some timed rules.
Parameters
----------
func : callable[(context, data) -> None]
The function to execute when the rule is triggered.
date_rule : EventRule, optional
The rule for the dates to execute this function.
... |
Create a specifier for a continuous contract.
Parameters
----------
root_symbol_str : str
The root symbol for the future chain.
offset : int, optional
The distance from the primary contract. Default is 0.
roll_style : str, optional
How rolls... |
Lookup an Equity by its ticker symbol.
Parameters
----------
symbol_str : str
The ticker symbol for the equity to lookup.
country_code : str or None, optional
A country to limit symbol searches to.
Returns
-------
equity : Equity
... |
Lookup multuple Equities as a list.
Parameters
----------
*args : iterable[str]
The ticker symbols to lookup.
country_code : str or None, optional
A country to limit symbol searches to.
Returns
-------
equities : list[Equity]
... |
Calculates how many shares/contracts to order based on the type of
asset being ordered.
def _calculate_order_value_amount(self, asset, value):
"""
Calculates how many shares/contracts to order based on the type of
asset being ordered.
"""
# Make sure the asset exists, an... |
Place an order.
Parameters
----------
asset : Asset
The asset that this order is for.
amount : int
The amount of shares to order. If ``amount`` is positive, this is
the number of shares to buy or cover. If ``amount`` is negative,
this is t... |
Helper method for validating parameters to the order API function.
Raises an UnsupportedOrderParameters if invalid arguments are found.
def validate_order_params(self,
asset,
amount,
limit_price,
... |
Helper method for converting deprecated limit_price and stop_price
arguments into ExecutionStyle instances.
This function assumes that either style == None or (limit_price,
stop_price) == (None, None).
def __convert_order_params_for_blotter(asset,
lim... |
Place an order by desired value rather than desired number of
shares.
Parameters
----------
asset : Asset
The asset that this order is for.
value : float
If the requested asset exists, the requested value is
divided by its price to imply the n... |
Sync the last sale prices on the metrics tracker to a given
datetime.
Parameters
----------
dt : datetime
The time to sync the prices to.
Notes
-----
This call is cached by the datetime. Repeated calls in the same bar
are cheap.
def _sync_la... |
Callback triggered by the simulation loop whenever the current dt
changes.
Any logic that should happen exactly once at the start of each datetime
group should happen here.
def on_dt_changed(self, dt):
"""
Callback triggered by the simulation loop whenever the current dt
... |
Returns the current simulation datetime.
Parameters
----------
tz : tzinfo or str, optional
The timezone to return the datetime in. This defaults to utc.
Returns
-------
dt : datetime
The current simulation datetime converted to ``tz``.
def get_... |
Set the slippage models for the simulation.
Parameters
----------
us_equities : EquitySlippageModel
The slippage model to use for trading US equities.
us_futures : FutureSlippageModel
The slippage model to use for trading US futures.
See Also
---... |
Sets the commission models for the simulation.
Parameters
----------
us_equities : EquityCommissionModel
The commission model to use for trading US equities.
us_futures : FutureCommissionModel
The commission model to use for trading US futures.
See Also
... |
Sets the order cancellation policy for the simulation.
Parameters
----------
cancel_policy : CancelPolicy
The cancellation policy to use.
See Also
--------
:class:`zipline.api.EODCancel`
:class:`zipline.api.NeverCancel`
def set_cancel_policy(self, c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.