INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Checks for a version value in the version table.
def check_version_info(conn, version_table, expected_version): """ 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 expecte...
Inserts the version value in to the version table.
def write_version_info(conn, version_table, version_value): """ 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...
Write asset metadata to a sqlite database in the format that it is stored in the assets db.
def write_direct(self, equities=None, equity_symbol_mappings=None, equity_supplementary_mappings=None, futures=None, exchanges=None, root_symbols=None, chunk_size=DEFAULT_CH...
Write asset metadata to a sqlite database.
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ------...
Checks if any tables are present in the current assets database.
def _all_tables_present(self, txn): """ 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 table...
Connect to database and create tables.
def init_db(self, txn=None): """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 ...
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 standard set of pandas.DataFrames: equities, futures, exchanges, root_symbols """ ...
Given an expression representing data to load perform normalization and forward - filling and return the data materialized. Only accepts data with a sid field.
def load_raw_data(assets, data_query_cutoff_times, expr, odo_kwargs, checkpoints=None): """ Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data wi...
Convert a tuple into a range with error handling.
def from_tuple(tup): """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 tup...
Convert a tuple into a range but pass ranges through silently.
def maybe_from_tuple(tup_or_range): """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...
Check that the steps of a and b are both 1.
def _check_steps(a, b): """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. """ if a.step != 1: ...
Check if two ranges overlap.
def overlap(a, b): """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 != ...
Merge two ranges with step == 1.
def merge(a, b): """Merge two ranges with step == 1. Parameters ---------- a : range The first range. b : range The second range. """ _check_steps(a, b) return range(min(a.start, b.start), max(a.stop, b.stop))
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 for r in rs: ...
Return any ranges that intersect.
def intersecting_ranges(ranges): """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 ``rang...
Returns a handle to data file.
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.path.join(dr, name)
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.DatetimeIndex): raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts)) ...
Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol.
def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY', environ=None): """ 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 B...
Ensure we have benchmark data for symbol from first_date to last_date
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ 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.Ti...
Ensure we have treasury data from treasury module associated with symbol.
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): """ 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.Timesta...
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.
def _add_to_graph(self, term, parents): """ 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. """ if self._frozen: raise ValueError( ...
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( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount >...
Calculate initial refcounts for execution of this graph.
def initial_refcounts(self, initial_terms): """ 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...
Decrement terms recursively.
def _decref_dependencies_recursive(self, term, refcounts, garbage): """ 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` ...
Decrement in - edges for term after computation.
def decref_dependencies(self, term, refcounts): """ 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 refco...
For all pairs ( term input ) such that input is an input to term compute a mapping::
def offset(self): """ 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 ``inp...
A dict mapping term - > # of extra rows to load/ compute of term.
def extra_rows(self): """ 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...
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.
def mask_and_dates_for_term(self, term, root_mask_term, workspace, all_dates): """ Load mask and mask row labels for term. Parameters ---------- term :...
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): assert term.domain is domain
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)], depends=['zipline/lib/_windowtemplate.pxi'], )
Read a requirements. txt file expressed as a path relative to Zipline root.
def read_requirements(path, strict_bounds, conda_format=False, filter_names=None): """ Read a requirements.txt file, expressed as a path relative to Zipline root. Returns requirements with the pinned versions as lower bounds if `strict_b...
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)) elif kwargs: raise ValueError('Can...
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: raise ValueError('Cannot pass kwargs and ...
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) elif not kwargs: raise ValueError(...
A preprocessor that coerces integral floats to ints.
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(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( ...
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: inner_rule = date_rule & time_rule & N...
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), ) # Align the market open and close times here wi...
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), )[1] # Align the market close time here with the execution time...
Drops any record where a value would not fit into a uint32.
def winsorise_uint32(df, invalid_data_behavior, column, *columns): """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 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 provided we will check data against the assets and provide better...
def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): """ Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should b...
Read CSVs as DataFrames from our asset map.
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path...
Internal implementation of write.
def _write_internal(self, iterator, assets): """ Internal implementation of write. `iterator` should be an iterator yielding pairs of (asset, ctable). """ total_rows = 0 first_row = {} last_row = {} calendar_offset = {} # Maps column name -> outp...
Compute the raw row indices to load for each asset on a query for the given dates after applying a shift.
def _compute_slices(self, start_idx, end_idx, assets): """ 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_...
Get the colname from daily_bar_table and read all of it into memory caching the result.
def _spot_col(self, colname): """ 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 (u...
Parameters ---------- sid: int The asset identifier. day: datetime64 - like Midnight of the day for which data is requested.
def sid_day_index(self, sid, day): """ 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 gi...
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 )
def get_value(self, sid, dt, field): """ 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'...
Construct and store a PipelineEngine from loader.
def init_engine(self, get_loader): """ Construct and store a PipelineEngine from loader. If get_loader is None, constructs an ExplodingPipelineEngine """ if get_loader is not None: self.engine = SimplePipelineEngine( get_loader, self.a...
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 = trading_o_and_c['market_close'] minutely_emission = False ...
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: self.data_p...
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
def calculate_capital_changes(self, dt, emission_rate, is_interday, portfolio_value_adjustment=0.0): """ 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...
Query the execution environment.
def get_environment(self, field='platform'): """Query the execution environment. Parameters ---------- field : {'platform', 'arena', 'data_frequency', 'start', 'end', 'capital_base', 'platform', '*'} The field to query. The options have the following meaning...
Fetch a csv from a remote url and register the data so that it is queryable from the data object.
def fetch_csv(self, url, pre_func=None, post_func=None, date_column='date', date_format=None, timezone=pytz.utc.zone, symbol=None, mask=True, symbol_column=No...
Adds an event to the algorithm s EventManager.
def add_event(self, rule, callback): """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...
Schedules a function to be called according to some timed rules.
def schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None): """Schedules a function to be called according to some timed rules. Paramet...
Create a specifier for a continuous contract.
def continuous_future(self, root_symbol_str, offset=0, roll='volume', adjustment='mul'): """Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str ...
Lookup an Equity by its ticker symbol.
def symbol(self, symbol_str, country_code=None): """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. ...
Lookup multuple Equities as a list.
def symbols(self, *args, **kwargs): """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 ---...
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, and that there is a last price for it. # FIXME: we should use BarData's can_trade logic her...
Place an order.
def order(self, asset, amount, limit_price=None, stop_price=None, style=None): """Place an order. Parameters ---------- asset : Asset The asset that this order is for. amount : int The ...
Helper method for validating parameters to the order API function.
def validate_order_params(self, asset, amount, limit_price, stop_price, style): """ Helper method for validating parameters to the order API function. ...
Helper method for converting deprecated limit_price and stop_price arguments into ExecutionStyle instances.
def __convert_order_params_for_blotter(asset, limit_price, stop_price, style): """ Helper method for converting deprecated limit_price and stop_price arguments into Ex...
Place an order by desired value rather than desired number of shares.
def order_value(self, asset, value, limit_price=None, stop_price=None, style=None): """Place an order by desired value rather than desired number of shares. Parameters ---------- ...
Sync the last sale prices on the metrics tracker to a given datetime.
def _sync_last_sale_prices(self, dt=None): """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 ...
Callback triggered by the simulation loop whenever the current dt changes.
def on_dt_changed(self, dt): """ 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. """ self.datetime = dt self.blotter.set_date(dt)
Returns the current simulation datetime.
def get_datetime(self, tz=None): """ 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 curre...
Set the slippage models for the simulation.
def set_slippage(self, us_equities=None, us_futures=None): """Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slipp...
Sets the commission models for the simulation.
def set_commission(self, us_equities=None, us_futures=None): """Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel ...
Sets the order cancellation policy for the simulation.
def set_cancel_policy(self, cancel_policy): """Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`zipline.api.EODCancel` :class:`...
Set the date for which symbols will be resolved to their assets ( symbols may map to different firms or underlying assets at different times )
def set_symbol_lookup_date(self, dt): """Set the date for which symbols will be resolved to their assets (symbols may map to different firms or underlying assets at different times) Parameters ---------- dt : datetime The new symbol lookup date. """ ...
Place an order in the specified asset corresponding to the given percent of the current portfolio value.
def order_percent(self, asset, percent, limit_price=None, stop_price=None, style=None): """Place an order in the specified asset corresponding to the given percent of the current portfolio value...
Place an order to adjust a position to a target number of shares. If the position doesn t already exist this is equivalent to placing a new order. If the position does exist this is equivalent to placing an order for the difference between the target number of shares and the current number of shares.
def order_target(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target number of shares. If the position doesn't already exist, this ...
Place an order to adjust a position to a target value. If the position doesn t already exist this is equivalent to placing a new order. If the position does exist this is equivalent to placing an order for the difference between the target value and the current value. If the Asset being ordered is a Future the target v...
def order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target value. If the position doe...
Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn t already exist this is equivalent to placing a new order. If the position does exist this is equivalent to placing an order for the difference between the target percent and the current percent.
def order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. ...
Place a batch market order for multiple assets.
def batch_market_order(self, share_counts): """Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from asset to number of shares to order for that asset. Returns ------- order_ids : pd.Ind...
Retrieve all of the current open orders.
def get_open_orders(self, asset=None): """Retrieve all of the current open orders. Parameters ---------- asset : Asset If passed and not None, return only the open orders for the given asset instead of all open orders. Returns ------- ope...
Lookup an order based on the order id returned from one of the order functions.
def get_order(self, order_id): """Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. Returns ------- order : Order The order ob...
Cancel an open order.
def cancel_order(self, order_param): """Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. """ order_id = order_param if isinstance(order_param, zipline.protocol.Order): order_id ...
DEPRECATED: use data. history instead.
def history(self, bar_count, frequency, field, ffill=True): """DEPRECATED: use ``data.history`` instead. """ warnings.warn( "The `history` method is deprecated. Use `data.history` instead.", category=ZiplineDeprecationWarning, stacklevel=4 ) ...
Register a new AccountControl to be checked on each bar.
def register_account_control(self, control): """ Register a new AccountControl to be checked on each bar. """ if self.initialized: raise RegisterAccountControlPostInit() self.account_controls.append(control)
Set a limit on the minimum leverage of the algorithm.
def set_min_leverage(self, min_leverage, grace_period): """Set a limit on the minimum leverage of the algorithm. Parameters ---------- min_leverage : float The minimum leverage for the algorithm. grace_period : pd.Timedelta The offset from the start date ...
Register a new TradingControl to be checked prior to order calls.
def register_trading_control(self, control): """ Register a new TradingControl to be checked prior to order calls. """ if self.initialized: raise RegisterTradingControlPostInit() self.trading_controls.append(control)
Set a limit on the number of shares and/ or dollar value held for the given sid. Limits are treated as absolute values and are enforced at the time that the algo attempts to place an order for sid. This means that it s possible to end up with more than the max number of shares due to splits/ dividends and more than the...
def set_max_position_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value held for the given sid. Lim...
Set a limit on the number of shares and/ or dollar value of any single order placed for sid. Limits are treated as absolute values and are enforced at the time that the algo attempts to place an order for sid.
def set_max_order_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): """Set a limit on the number of shares and/or dollar value of any single order placed for sid. Limit...
Set a limit on the number of orders that can be placed in a single day.
def set_max_order_count(self, max_count, on_error='fail'): """Set a limit on the number of orders that can be placed in a single day. Parameters ---------- max_count : int The maximum number of orders that can be placed on any single day. """ control ...
Set a restriction on which assets can be ordered.
def set_asset_restrictions(self, restrictions, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : Restrictions An object providing information about restricted assets. See Also -------- zipl...
Register a pipeline to be computed at the start of each day.
def attach_pipeline(self, pipeline, name, chunks=None, eager=True): """Register a pipeline to be computed at the start of each day. Parameters ---------- pipeline : Pipeline The pipeline to have computed. name : str The name of the pipeline. chunk...
Get the results of the pipeline that was attached with the name: name.
def pipeline_output(self, name): """Get the results of the pipeline that was attached with the name: ``name``. Parameters ---------- name : str Name of the pipeline for which results are requested. Returns ------- results : pd.DataFrame ...
Internal implementation of pipeline_output.
def _pipeline_output(self, pipeline, chunks, name): """ Internal implementation of `pipeline_output`. """ today = normalize_date(self.get_datetime()) try: data = self._pipeline_cache.get(name, today) except KeyError: # Calculate the next block. ...
Compute pipeline providing values for at least start_date.
def run_pipeline(self, pipeline, start_session, chunksize): """ Compute `pipeline`, providing values for at least `start_date`. Produces a DataFrame containing data for days between `start_date` and `end_date`, where `end_date` is defined by: `end_date = min(start_date + ch...
Return a list of all the TradingAlgorithm API methods.
def all_api_methods(cls): """ Return a list of all the TradingAlgorithm API methods. """ return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
Format a bulleted list of values.
def bulleted_list(items, max_count=None, indent=2): """Format a bulleted list of values. """ if max_count is not None and len(items) > max_count: item_list = list(items) items = item_list[:max_count - 1] items.append('...') items.append(item_list[-1]) line_template = (" ...
Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected.
def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): """ Checks for the presence of an extra to the argument list. Raises expections if this is unexpected or if it is missing and expected. """ if present: if not expected: raise exc_unexpected(*exc_args) ...