Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def intersecting_ranges(ranges): ranges = sorted(ranges, key=op.attrgetter('start')) return sorted_diff(ranges, group_ranges(ranges))
[ "Return any ranges that intersect.\n\n Parameters\n ----------\n ranges : iterable[ranges]\n A sequence of ranges to check for intersections.\n\n Returns\n -------\n intersections : iterable[ranges]\n A sequence of all of the ranges that intersected in ``ranges``.\n\n Examples\n ...
Please provide a description of the function:def get_data_filepath(name, environ=None): dr = data_root(environ) if not os.path.exists(dr): os.makedirs(dr) return os.path.join(dr, name)
[ "\n Returns a handle to data file.\n\n Creates containing directory, if needed.\n " ]
Please provide a description of the function:def has_data_for_dates(series_or_df, first_date, last_date): dts = series_or_df.index if not isinstance(dts, pd.DatetimeIndex): raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts)) first, last = dts[[0, -1]] return (first <= first...
[ "\n Does `series_or_df` have data on or before first_date and on or after\n last_date?\n " ]
Please provide a description of the function:def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY', environ=None): if trading_day is None: trading_day = get_calendar('XNYS').day if trading_days is None: trading_days = get_calendar('XNYS').all_session...
[ "\n Load benchmark returns and treasury yield curves for the given calendar and\n benchmark symbol.\n\n Benchmarks are downloaded as a Series from IEX Trading. Treasury curves\n are US Treasury Bond rates and are downloaded from 'www.federalreserve.gov'\n by default. For Canadian exchanges, a loade...
Please provide a description of the function:def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): filename = get_benchmark_filename(symbol) data = _load_cached_data(filename, first_date, last_date, now, 'benchmark', ...
[ "\n Ensure we have benchmark data for `symbol` from `first_date` to `last_date`\n\n Parameters\n ----------\n symbol : str\n The symbol for the benchmark to load.\n first_date : pd.Timestamp\n First required date for the cache.\n last_date : pd.Timestamp\n Last required date f...
Please provide a description of the function:def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): loader_module, filename, source = INDEX_MAPPING.get( symbol, INDEX_MAPPING['SPY'], ) first_date = max(first_date, loader_module.earliest_possible_date()) data = _load_ca...
[ "\n Ensure we have treasury data from treasury module associated with\n `symbol`.\n\n Parameters\n ----------\n symbol : str\n Benchmark symbol for which we're loading associated treasury curves.\n first_date : pd.Timestamp\n First date required to be in the cache.\n last_date : p...
Please provide a description of the function:def maybe_specialize(term, domain): if isinstance(term, LoadableTerm): return term.specialize(domain) return term
[ "Specialize a term if it's loadable.\n " ]
Please provide a description of the function:def _add_to_graph(self, term, parents): if self._frozen: raise ValueError( "Can't mutate %s after construction." % type(self).__name__ ) # If we've seen this node already as a parent of the current traversal, ...
[ "\n Add a term and all its children to ``graph``.\n\n ``parents`` is the set of all the parents of ``term` that we've added\n so far. It is only used to detect dependency cycles.\n " ]
Please provide a description of the function:def execution_order(self, refcounts): return iter(nx.topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount > 0}, ), ))
[ "\n Return a topologically-sorted iterator over the terms in ``self`` which\n need to be computed.\n " ]
Please provide a description of the function:def initial_refcounts(self, initial_terms): refcounts = self.graph.out_degree() for t in self.outputs.values(): refcounts[t] += 1 for t in initial_terms: self._decref_dependencies_recursive(t, refcounts, set()) ...
[ "\n Calculate initial refcounts for execution of this graph.\n\n Parameters\n ----------\n initial_terms : iterable[Term]\n An iterable of terms that were pre-computed before graph execution.\n\n Each node starts with a refcount equal to its outdegree, and output\n ...
Please provide a description of the function:def _decref_dependencies_recursive(self, term, refcounts, garbage): # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from the ...
[ "\n Decrement terms recursively.\n\n Notes\n -----\n This should only be used to build the initial workspace, after that we\n should use:\n :meth:`~zipline.pipeline.graph.TermGraph.decref_dependencies`\n " ]
Please provide a description of the function:def decref_dependencies(self, term, refcounts): garbage = set() # Edges are tuple of (from, to). for parent, _ in self.graph.in_edges([term]): refcounts[parent] -= 1 # No one else depends on this term. Remove it from t...
[ "\n Decrement in-edges for ``term`` after computation.\n\n Parameters\n ----------\n term : zipline.pipeline.Term\n The term whose parents should be decref'ed.\n refcounts : dict[Term -> int]\n Dictionary of refcounts.\n\n Return\n ------\n ...
Please provide a description of the function:def extra_rows(self): return { term: attrs['extra_rows'] for term, attrs in iteritems(self.graph.node) }
[ "\n A dict mapping `term` -> `# of extra rows to load/compute of `term`.\n\n Notes\n ----\n This value depends on the other terms in the graph that require `term`\n **as an input**. This is not to be confused with `term.dependencies`,\n which describes how many additional ...
Please provide a description of the function:def _ensure_extra_rows(self, term, N): attrs = self.graph.node[term] attrs['extra_rows'] = max(N, attrs.get('extra_rows', 0))
[ "\n Ensure that we're going to compute at least N extra rows of `term`.\n " ]
Please provide a description of the function:def mask_and_dates_for_term(self, term, root_mask_term, workspace, all_dates): mask = term.mask mask_offset = self.extra_r...
[ "\n Load mask and mask row labels for term.\n\n Parameters\n ----------\n term : Term\n The term to load the mask and labels for.\n root_mask_term : Term\n The term that represents the root asset exists mask.\n workspace : dict[Term, any]\n ...
Please provide a description of the function:def _assert_all_loadable_terms_specialized_to(self, domain): for term in self.graph.node: if isinstance(term, LoadableTerm): assert term.domain is domain
[ "Make sure that we've specialized all loadable terms in the graph.\n " ]
Please provide a description of the function:def window_specialization(typename): return Extension( 'zipline.lib._{name}window'.format(name=typename), ['zipline/lib/_{name}window.pyx'.format(name=typename)], depends=['zipline/lib/_windowtemplate.pxi'], )
[ "Make an extension for an AdjustedArrayWindow specialization." ]
Please provide a description of the function:def read_requirements(path, strict_bounds, conda_format=False, filter_names=None): real_path = join(dirname(abspath(__file__)), path) with open(real_path) as f: reqs = _filter_requirements...
[ "\n Read a requirements.txt file, expressed as a path relative to Zipline root.\n\n Returns requirements with the pinned versions as lower bounds\n if `strict_bounds` is falsey.\n " ]
Please provide a description of the function:def ensure_utc(time, tz='UTC'): if not time.tzinfo: time = time.replace(tzinfo=pytz.timezone(tz)) return time.replace(tzinfo=pytz.utc)
[ "\n Normalize a time. If the time is tz-naive, assume it is UTC.\n " ]
Please provide a description of the function:def _build_offset(offset, kwargs, default): if offset is None: if not kwargs: return default # use the default. else: return _td_check(datetime.timedelta(**kwargs)) elif kwargs: raise ValueError('Cannot pass kwarg...
[ "\n Builds the offset argument for event rules.\n " ]
Please provide a description of the function:def _build_date(date, kwargs): 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 a date') ...
[ "\n Builds the date argument for event rules.\n " ]
Please provide a description of the function:def _build_time(time, kwargs): 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('Must pass a...
[ "\n Builds the time argument for event rules.\n " ]
Please provide a description of the function:def lossless_float_to_int(funcname, func, argname, arg): if not isinstance(arg, float): return arg arg_as_int = int(arg) if arg == arg_as_int: warnings.warn( "{f} expected an int for argument {name!r}, but got float {arg}." ...
[ "\n A preprocessor that coerces integral floats to ints.\n\n Receipt of non-integral floats raises a TypeError.\n " ]
Please provide a description of the function:def make_eventrule(date_rule, time_rule, cal, half_days=True): _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 & NotHalfDay() ...
[ "\n Constructs an event rule from the factory api.\n " ]
Please provide a description of the function:def add_event(self, event, prepend=False): if prepend: self._events.insert(0, event) else: self._events.append(event)
[ "\n Adds an event to the manager.\n " ]
Please provide a description of the function:def handle_data(self, context, data, dt): if self.rule.should_trigger(dt): self.callback(context, data)
[ "\n Calls the callable only when the rule is triggered.\n " ]
Please provide a description of the function:def should_trigger(self, dt): return self.composer( self.first.should_trigger, self.second.should_trigger, dt )
[ "\n Composes the two rules with a lazy composer.\n " ]
Please provide a description of the function:def calculate_dates(self, dt): 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 with the execution times # used by the ...
[ "\n Given a date, find that day's open and period end (open + offset).\n " ]
Please provide a description of the function:def calculate_dates(self, dt): 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 used by the # simulation clock. This e...
[ "\n Given a dt, find that day's close and period start (close - offset).\n " ]
Please provide a description of the function:def winsorise_uint32(df, invalid_data_behavior, column, *columns): columns = list((column,) + columns) mask = df[columns] > UINT32_MAX if invalid_data_behavior != 'ignore': mask |= df[columns].isnull() else: # we are not going to generat...
[ "Drops any record where a value would not fit into a uint32.\n\n Parameters\n ----------\n df : pd.DataFrame\n The dataframe to winsorise.\n invalid_data_behavior : {'warn', 'raise', 'ignore'}\n What to do when data is outside the bounds of a uint32.\n *columns : iterable[str]\n ...
Please provide a description of the function:def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): ctx = maybe_show_progress( ( (sid, self.to_ctable(df, invalid_data_behavior)) ...
[ "\n Parameters\n ----------\n data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]]\n The data chunks to write. Each chunk should be a tuple of sid\n and the data for that asset.\n assets : set[int], optional\n The assets that should be in ``data`...
Please provide a description of the function:def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): read = partial( read_csv, parse_dates=['day'], index_col='day', dtype...
[ "Read CSVs as DataFrames from our asset map.\n\n Parameters\n ----------\n asset_map : dict[int -> str]\n A mapping from asset id to file path with the CSV data for that\n asset\n show_progress : bool\n Whether or not to show a progress bar while writing....
Please provide a description of the function:def _write_internal(self, iterator, assets): total_rows = 0 first_row = {} last_row = {} calendar_offset = {} # Maps column name -> output carray. columns = { k: carray(array([], dtype=uint32_dtype)) ...
[ "\n Internal implementation of write.\n\n `iterator` should be an iterator yielding pairs of (asset, ctable).\n " ]
Please provide a description of the function:def _compute_slices(self, start_idx, end_idx, assets): # The core implementation of the logic here is implemented in Cython # for efficiency. return _compute_row_slices( self._first_rows, self._last_rows, s...
[ "\n Compute the raw row indices to load for each asset on a query for the\n given dates after applying a shift.\n\n Parameters\n ----------\n start_idx : int\n Index of first date for which we want data.\n end_idx : int\n Index of last date for which w...
Please provide a description of the function:def _spot_col(self, colname): try: col = self._spot_cols[colname] except KeyError: col = self._spot_cols[colname] = self._table[colname] return col
[ "\n Get the colname from daily_bar_table and read all of it into memory,\n caching the result.\n\n Parameters\n ----------\n colname : string\n A name of a OHLCV carray in the daily_bar_table\n\n Returns\n -------\n array (uint32)\n Full ...
Please provide a description of the function:def sid_day_index(self, sid, day): try: day_loc = self.sessions.get_loc(day) except Exception: raise NoDataOnDate("day={0} is outside of calendar={1}".format( day, self.sessions)) offset = day_loc - sel...
[ "\n Parameters\n ----------\n sid : int\n The asset identifier.\n day : datetime64-like\n Midnight of the day for which data is requested.\n\n Returns\n -------\n int\n Index into the data tape for the given sid and day.\n ...
Please provide a description of the function:def get_value(self, sid, dt, field): ix = self.sid_day_index(sid, dt) price = self._spot_col(field)[ix] if field != 'volume': if price == 0: return nan else: return price * 0.001 ...
[ "\n Parameters\n ----------\n sid : int\n The asset identifier.\n day : datetime64-like\n Midnight of the day for which data is requested.\n colname : string\n The price field. e.g. ('open', 'high', 'low', 'close', 'volume')\n\n Returns\n ...
Please provide a description of the function:def init_engine(self, get_loader): if get_loader is not None: self.engine = SimplePipelineEngine( get_loader, self.asset_finder, self.default_pipeline_domain(self.trading_calendar), ) ...
[ "\n Construct and store a PipelineEngine from loader.\n\n If get_loader is None, constructs an ExplodingPipelineEngine\n " ]
Please provide a description of the function:def initialize(self, *args, **kwargs): with ZiplineAPI(self): self._initialize(self, *args, **kwargs)
[ "\n Call self._initialize with `self` made available to Zipline API\n functions.\n " ]
Please provide a description of the function:def _create_clock(self): trading_o_and_c = self.trading_calendar.schedule.ix[ self.sim_params.sessions] market_closes = trading_o_and_c['market_close'] minutely_emission = False if self.sim_params.data_frequency == 'minut...
[ "\n If the clock property is not set, then create one based on frequency.\n " ]
Please provide a description of the function:def compute_eager_pipelines(self): for name, pipe in self._pipelines.items(): if pipe.eager: self.pipeline_output(name)
[ "\n Compute any pipelines attached with eager=True.\n " ]
Please provide a description of the function:def run(self, data_portal=None): # 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: ...
[ "Run the algorithm.\n " ]
Please provide a description of the function:def calculate_capital_changes(self, dt, emission_rate, is_interday, portfolio_value_adjustment=0.0): try: capital_change = self.capital_changes[dt] except KeyError: return self._sync_...
[ "\n If there is a capital change for a given dt, this means the the change\n occurs before `handle_data` on the given dt. In the case of the\n change being a target value, the change will be computed on the\n portfolio value according to prices at the given dt\n\n `portfolio_value...
Please provide a description of the function:def get_environment(self, field='platform'): env = { 'arena': self.sim_params.arena, 'data_frequency': self.sim_params.data_frequency, 'start': self.sim_params.first_open, 'end': self.sim_params.last_close, ...
[ "Query the execution environment.\n\n Parameters\n ----------\n field : {'platform', 'arena', 'data_frequency',\n 'start', 'end', 'capital_base', 'platform', '*'}\n The field to query. The options have the following meanings:\n arena : str\n ...
Please provide a description of the function:def fetch_csv(self, url, pre_func=None, post_func=None, date_column='date', date_format=None, timezone=pytz.utc.zone, symbol=None, ...
[ "Fetch a csv from a remote url and register the data so that it is\n queryable from the ``data`` object.\n\n Parameters\n ----------\n url : str\n The url of the csv file to load.\n pre_func : callable[pd.DataFrame -> pd.DataFrame], optional\n A callback to a...
Please provide a description of the function:def add_event(self, rule, callback): self.event_manager.add_event( zipline.utils.events.Event(rule, callback), )
[ "Adds an event to the algorithm's EventManager.\n\n Parameters\n ----------\n rule : EventRule\n The rule for when the callback should be triggered.\n callback : callable[(context, data) -> None]\n The function to execute when the rule is triggered.\n " ]
Please provide a description of the function:def schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None): # When the user calls schedul...
[ "Schedules a function to be called according to some timed rules.\n\n Parameters\n ----------\n func : callable[(context, data) -> None]\n The function to execute when the rule is triggered.\n date_rule : EventRule, optional\n The rule for the dates to execute this ...
Please provide a description of the function:def continuous_future(self, root_symbol_str, offset=0, roll='volume', adjustment='mul'): return self.asset_finder.create_continuous_future( ro...
[ "Create a specifier for a continuous contract.\n\n Parameters\n ----------\n root_symbol_str : str\n The root symbol for the future chain.\n\n offset : int, optional\n The distance from the primary contract. Default is 0.\n\n roll_style : str, optional\n ...
Please provide a description of the function:def symbol(self, symbol_str, country_code=None): # If the user has not set the symbol lookup date, # use the end_session as the date for symbol->sid resolution. _lookup_date = self._symbol_lookup_date \ if self._symbol_lookup_date...
[ "Lookup an Equity by its ticker symbol.\n\n Parameters\n ----------\n symbol_str : str\n The ticker symbol for the equity to lookup.\n country_code : str or None, optional\n A country to limit symbol searches to.\n\n Returns\n -------\n equity :...
Please provide a description of the function:def symbols(self, *args, **kwargs): return [self.symbol(identifier, **kwargs) for identifier in args]
[ "Lookup multuple Equities as a list.\n\n Parameters\n ----------\n *args : iterable[str]\n The ticker symbols to lookup.\n country_code : str or None, optional\n A country to limit symbol searches to.\n\n\n\n Returns\n -------\n equities : list[...
Please provide a description of the function:def _calculate_order_value_amount(self, asset, value): # Make sure the asset exists, and that there is a last price for it. # FIXME: we should use BarData's can_trade logic here, but I haven't # yet found a good way to do that. normal...
[ "\n Calculates how many shares/contracts to order based on the type of\n asset being ordered.\n " ]
Please provide a description of the function:def order(self, asset, amount, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None amount, style = self._calculate_order(a...
[ "Place an order.\n\n Parameters\n ----------\n asset : Asset\n The asset that this order is for.\n amount : int\n The amount of shares to order. If ``amount`` is positive, this is\n the number of shares to buy or cover. If ``amount`` is negative,\n ...
Please provide a description of the function:def validate_order_params(self, asset, amount, limit_price, stop_price, style): if not self.initialized: ...
[ "\n Helper method for validating parameters to the order API function.\n\n Raises an UnsupportedOrderParameters if invalid arguments are found.\n " ]
Please provide a description of the function:def __convert_order_params_for_blotter(asset, limit_price, stop_price, style): if style: assert (limit_price, stop_pr...
[ "\n Helper method for converting deprecated limit_price and stop_price\n arguments into ExecutionStyle instances.\n\n This function assumes that either style == None or (limit_price,\n stop_price) == (None, None).\n " ]
Please provide a description of the function:def order_value(self, asset, value, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None amou...
[ "Place an order by desired value rather than desired number of\n shares.\n\n Parameters\n ----------\n asset : Asset\n The asset that this order is for.\n value : float\n If the requested asset exists, the requested value is\n divided by its price ...
Please provide a description of the function:def _sync_last_sale_prices(self, dt=None): if dt is None: dt = self.datetime if dt != self._last_sync_time: self.metrics_tracker.sync_last_sale_prices( dt, self.data_portal, ) ...
[ "Sync the last sale prices on the metrics tracker to a given\n datetime.\n\n Parameters\n ----------\n dt : datetime\n The time to sync the prices to.\n\n Notes\n -----\n This call is cached by the datetime. Repeated calls in the same bar\n are chea...
Please provide a description of the function:def on_dt_changed(self, dt): self.datetime = dt self.blotter.set_date(dt)
[ "\n Callback triggered by the simulation loop whenever the current dt\n changes.\n\n Any logic that should happen exactly once at the start of each datetime\n group should happen here.\n " ]
Please provide a description of the function:def get_datetime(self, tz=None): dt = self.datetime assert dt.tzinfo == pytz.utc, "Algorithm should have a utc datetime" if tz is not None: dt = dt.astimezone(tz) return dt
[ "\n Returns the current simulation datetime.\n\n Parameters\n ----------\n tz : tzinfo or str, optional\n The timezone to return the datetime in. This defaults to utc.\n\n Returns\n -------\n dt : datetime\n The current simulation datetime conve...
Please provide a description of the function:def set_slippage(self, us_equities=None, us_futures=None): if self.initialized: raise SetSlippagePostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleSlipp...
[ "Set the slippage models for the simulation.\n\n Parameters\n ----------\n us_equities : EquitySlippageModel\n The slippage model to use for trading US equities.\n us_futures : FutureSlippageModel\n The slippage model to use for trading US futures.\n\n See Al...
Please provide a description of the function:def set_commission(self, us_equities=None, us_futures=None): if self.initialized: raise SetCommissionPostInit() if us_equities is not None: if Equity not in us_equities.allowed_asset_types: raise IncompatibleC...
[ "Sets the commission models for the simulation.\n\n Parameters\n ----------\n us_equities : EquityCommissionModel\n The commission model to use for trading US equities.\n us_futures : FutureCommissionModel\n The commission model to use for trading US futures.\n\n ...
Please provide a description of the function:def set_cancel_policy(self, cancel_policy): if not isinstance(cancel_policy, CancelPolicy): raise UnsupportedCancelPolicy() if self.initialized: raise SetCancelPolicyPostInit() self.blotter.cancel_policy = cancel_pol...
[ "Sets the order cancellation policy for the simulation.\n\n Parameters\n ----------\n cancel_policy : CancelPolicy\n The cancellation policy to use.\n\n See Also\n --------\n :class:`zipline.api.EODCancel`\n :class:`zipline.api.NeverCancel`\n " ]
Please provide a description of the function:def set_symbol_lookup_date(self, dt): try: self._symbol_lookup_date = pd.Timestamp(dt, tz='UTC') except ValueError: raise UnsupportedDatetimeFormat(input=dt, method='set_symbol_looku...
[ "Set the date for which symbols will be resolved to their assets\n (symbols may map to different firms or underlying assets at\n different times)\n\n Parameters\n ----------\n dt : datetime\n The new symbol lookup date.\n " ]
Please provide a description of the function:def order_percent(self, asset, percent, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None...
[ "Place an order in the specified asset corresponding to the given\n percent of the current portfolio value.\n\n Parameters\n ----------\n asset : Asset\n The asset that this order is for.\n percent : float\n The percentage of the portfolio value to allocate t...
Please provide a description of the function:def order_target(self, asset, target, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None ...
[ "Place an order to adjust a position to a target number of shares. If\n the position doesn't already exist, this is equivalent to placing a new\n order. If the position does exist, this is equivalent to placing an\n order for the difference between the target number of shares and the\n c...
Please provide a description of the function:def order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(as...
[ "Place an order to adjust a position to a target value. If\n the position doesn't already exist, this is equivalent to placing a new\n order. If the position does exist, this is equivalent to placing an\n order for the difference between the target value and the\n current value.\n ...
Please provide a description of the function:def order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None): if not self._can_order_asset(asset): return None amount = self._calculate_order_target_percent_amount(asset, targe...
[ "Place an order to adjust a position to a target percent of the\n current portfolio value. If the position doesn't already exist, this is\n equivalent to placing a new order. If the position does exist, this is\n equivalent to placing an order for the difference between the target\n perc...
Please provide a description of the function:def batch_market_order(self, share_counts): style = MarketOrder() order_args = [ (asset, amount, style) for (asset, amount) in iteritems(share_counts) if amount ] return self.blotter.batch_order(ord...
[ "Place a batch market order for multiple assets.\n\n Parameters\n ----------\n share_counts : pd.Series[Asset -> int]\n Map from asset to number of shares to order for that asset.\n\n Returns\n -------\n order_ids : pd.Index[str]\n Index of ids for new...
Please provide a description of the function:def get_open_orders(self, asset=None): if asset is None: return { key: [order.to_api_obj() for order in orders] for key, orders in iteritems(self.blotter.open_orders) if orders } ...
[ "Retrieve all of the current open orders.\n\n Parameters\n ----------\n asset : Asset\n If passed and not None, return only the open orders for the given\n asset instead of all open orders.\n\n Returns\n -------\n open_orders : dict[list[Order]] or lis...
Please provide a description of the function:def get_order(self, order_id): if order_id in self.blotter.orders: return self.blotter.orders[order_id].to_api_obj()
[ "Lookup an order based on the order id returned from one of the\n order functions.\n\n Parameters\n ----------\n order_id : str\n The unique identifier for the order.\n\n Returns\n -------\n order : Order\n The order object.\n " ]
Please provide a description of the function:def cancel_order(self, order_param): order_id = order_param if isinstance(order_param, zipline.protocol.Order): order_id = order_param.id self.blotter.cancel(order_id)
[ "Cancel an open order.\n\n Parameters\n ----------\n order_param : str or Order\n The order_id or order object to cancel.\n " ]
Please provide a description of the function:def history(self, bar_count, frequency, field, ffill=True): warnings.warn( "The `history` method is deprecated. Use `data.history` instead.", category=ZiplineDeprecationWarning, stacklevel=4 ) return self...
[ "DEPRECATED: use ``data.history`` instead.\n " ]
Please provide a description of the function:def register_account_control(self, control): if self.initialized: raise RegisterAccountControlPostInit() self.account_controls.append(control)
[ "\n Register a new AccountControl to be checked on each bar.\n " ]
Please provide a description of the function:def set_min_leverage(self, min_leverage, grace_period): deadline = self.sim_params.start_session + grace_period control = MinLeverage(min_leverage, deadline) self.register_account_control(control)
[ "Set a limit on the minimum leverage of the algorithm.\n\n Parameters\n ----------\n min_leverage : float\n The minimum leverage for the algorithm.\n grace_period : pd.Timedelta\n The offset from the start date used to enforce a minimum leverage.\n " ]
Please provide a description of the function:def register_trading_control(self, control): if self.initialized: raise RegisterTradingControlPostInit() self.trading_controls.append(control)
[ "\n Register a new TradingControl to be checked prior to order calls.\n " ]
Please provide a description of the function:def set_max_position_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): control = MaxPositionSize(asset=asset, ...
[ "Set a limit on the number of shares and/or dollar value held for the\n given sid. Limits are treated as absolute values and are enforced at\n the time that the algo attempts to place an order for sid. This means\n that it's possible to end up with more than the max number of shares\n du...
Please provide a description of the function:def set_max_order_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): control = MaxOrderSize(asset=asset, ...
[ "Set a limit on the number of shares and/or dollar value of any single\n order placed for sid. Limits are treated as absolute values and are\n enforced at the time that the algo attempts to place an order for sid.\n\n If an algorithm attempts to place an order that would result in\n exc...
Please provide a description of the function:def set_max_order_count(self, max_count, on_error='fail'): control = MaxOrderCount(on_error, max_count) self.register_trading_control(control)
[ "Set a limit on the number of orders that can be placed in a single\n day.\n\n Parameters\n ----------\n max_count : int\n The maximum number of orders that can be placed on any single day.\n " ]
Please provide a description of the function:def set_asset_restrictions(self, restrictions, on_error='fail'): control = RestrictedListOrder(on_error, restrictions) self.register_trading_control(control) self.restrictions |= restrictions
[ "Set a restriction on which assets can be ordered.\n\n Parameters\n ----------\n restricted_list : Restrictions\n An object providing information about restricted assets.\n\n See Also\n --------\n zipline.finance.asset_restrictions.Restrictions\n " ]
Please provide a description of the function:def attach_pipeline(self, pipeline, name, chunks=None, eager=True): if chunks is None: # Make the first chunk smaller to get more immediate results: # (one week, then every half year) chunks = chain([5], repeat(126)) ...
[ "Register a pipeline to be computed at the start of each day.\n\n Parameters\n ----------\n pipeline : Pipeline\n The pipeline to have computed.\n name : str\n The name of the pipeline.\n chunks : int or iterator, optional\n The number of days to c...
Please provide a description of the function:def pipeline_output(self, name): try: pipe, chunks, _ = self._pipelines[name] except KeyError: raise NoSuchPipeline( name=name, valid=list(self._pipelines.keys()), ) return s...
[ "Get the results of the pipeline that was attached with the name:\n ``name``.\n\n Parameters\n ----------\n name : str\n Name of the pipeline for which results are requested.\n\n Returns\n -------\n results : pd.DataFrame\n DataFrame containing ...
Please provide a description of the function:def _pipeline_output(self, pipeline, chunks, name): today = normalize_date(self.get_datetime()) try: data = self._pipeline_cache.get(name, today) except KeyError: # Calculate the next block. data, valid_unt...
[ "\n Internal implementation of `pipeline_output`.\n " ]
Please provide a description of the function:def run_pipeline(self, pipeline, start_session, chunksize): sessions = self.trading_calendar.all_sessions # Load data starting from the previous trading day... start_date_loc = sessions.get_loc(start_session) # ...continuing until e...
[ "\n Compute `pipeline`, providing values for at least `start_date`.\n\n Produces a DataFrame containing data for days between `start_date` and\n `end_date`, where `end_date` is defined by:\n\n `end_date = min(start_date + chunksize trading days,\n simulatio...
Please provide a description of the function:def all_api_methods(cls): return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
[ "\n Return a list of all the TradingAlgorithm API methods.\n " ]
Please provide a description of the function:def bulleted_list(items, max_count=None, indent=2): 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 = ("...
[ "Format a bulleted list of values.\n " ]
Please provide a description of the function:def _expect_extra(expected, present, exc_unexpected, exc_missing, exc_args): if present: if not expected: raise exc_unexpected(*exc_args) elif expected and expected is not Argument.ignore: raise exc_missing(*exc_args)
[ "\n Checks for the presence of an extra to the argument list. Raises expections\n if this is unexpected or if it is missing and expected.\n " ]
Please provide a description of the function:def verify_callable_argspec(callable_, expected_args=Argument.ignore, expect_starargs=Argument.ignore, expect_kwargs=Argument.ignore): if not callable(callable_): raise NotCa...
[ "\n Checks the callable_ to make sure that it satisfies the given\n expectations.\n expected_args should be an iterable of Arguments in the order you expect to\n receive them.\n expect_starargs means that the function should or should not take a *args\n param. expect_kwargs says the callable shoul...
Please provide a description of the function:def parse_argspec(callable_): args, varargs, keywords, defaults = getargspec(callable_) defaults = list(defaults or []) if getattr(callable_, '__self__', None) is not None: # This is a bound method, drop the self param. ...
[ "\n Takes a callable and returns a tuple with the list of Argument objects,\n the name of *args, and the name of **kwargs.\n If *args or **kwargs is not present, it will be None.\n This returns a namedtuple called Argspec that has three fields named:\n args, starargs, and kwargs.\...
Please provide a description of the function:def is_restricted(self, assets, dt): if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_element(assets, self._restricted_set) )
[ "\n An asset is restricted for all dts if it is in the static list.\n " ]
Please provide a description of the function:def is_restricted(self, assets, dt): if isinstance(assets, Asset): return self._is_restricted_for_asset(assets, dt) is_restricted = partial(self._is_restricted_for_asset, dt=dt) return pd.Series( index=pd.Index(assets...
[ "\n Returns whether or not an asset or iterable of assets is restricted\n on a dt.\n " ]
Please provide a description of the function:def handle_splits(self, splits): total_leftover_cash = 0 for asset, ratio in splits: if asset in self.positions: self._dirty_stats = True # Make the position object handle the split. It returns the ...
[ "Processes a list of splits by modifying any positions as needed.\n\n Parameters\n ----------\n splits: list\n A list of splits. Each split is a tuple of (asset, ratio).\n\n Returns\n -------\n int: The leftover cash from fractional shares after modifying each\n...
Please provide a description of the function:def earn_dividends(self, cash_dividends, stock_dividends): for cash_dividend in cash_dividends: self._dirty_stats = True # only mark dirty if we pay a dividend # Store the earned dividends so that they can be paid on the ...
[ "Given a list of dividends whose ex_dates are all the next trading\n day, calculate and store the cash and/or stock payments to be paid on\n each dividend's pay date.\n\n Parameters\n ----------\n cash_dividends : iterable of (asset, amount, pay_date) namedtuples\n\n stock_...
Please provide a description of the function:def pay_dividends(self, next_trading_day): net_cash_payment = 0.0 try: payments = self._unpaid_dividends[next_trading_day] # Mark these dividends as paid by dropping them from our unpaid del self._unpaid_dividends...
[ "\n Returns a cash payment based on the dividends that should be paid out\n according to the accumulated bookkeeping of earned, unpaid, and stock\n dividends.\n " ]
Please provide a description of the function:def stats(self): if self._dirty_stats: calculate_position_tracker_stats(self.positions, self._stats) self._dirty_stats = False return self._stats
[ "The current status of the positions.\n\n Returns\n -------\n stats : PositionStats\n The current stats position stats.\n\n Notes\n -----\n This is cached, repeated access will not recompute the stats until\n the stats may have changed.\n " ]
Please provide a description of the function:def process_transaction(self, transaction): asset = transaction.asset if isinstance(asset, Future): try: old_price = self._payout_last_sale_prices[asset] except KeyError: self._payout_last_sale_...
[ "Add a transaction to ledger, updating the current state as needed.\n\n Parameters\n ----------\n transaction : zp.Transaction\n The transaction to execute.\n " ]
Please provide a description of the function:def process_splits(self, splits): leftover_cash = self.position_tracker.handle_splits(splits) if leftover_cash > 0: self._cash_flow(leftover_cash)
[ "Processes a list of splits by modifying any positions as needed.\n\n Parameters\n ----------\n splits: list[(Asset, float)]\n A list of splits. Each split is a tuple of (asset, ratio).\n " ]
Please provide a description of the function:def process_order(self, order): try: dt_orders = self._orders_by_modified[order.dt] except KeyError: self._orders_by_modified[order.dt] = OrderedDict([ (order.id, order), ]) self._orders...
[ "Keep track of an order that was placed.\n\n Parameters\n ----------\n order : zp.Order\n The order to record.\n " ]
Please provide a description of the function:def process_commission(self, commission): asset = commission['asset'] cost = commission['cost'] self.position_tracker.handle_commission(asset, cost) self._cash_flow(-cost)
[ "Process the commission.\n\n Parameters\n ----------\n commission : zp.Event\n The commission being paid.\n " ]
Please provide a description of the function:def process_dividends(self, next_session, asset_finder, adjustment_reader): position_tracker = self.position_tracker # Earn dividends whose ex_date is the next trading day. We need to # check if we own any of these stocks so we know to pay t...
[ "Process dividends for the next session.\n\n This will earn us any dividends whose ex-date is the next session as\n well as paying out any dividends whose pay-date is the next session\n " ]
Please provide a description of the function:def transactions(self, dt=None): if dt is None: # flatten the by-day transactions return [ txn for by_day in itervalues(self._processed_transactions) for txn in by_day ] ...
[ "Retrieve the dict-form of all of the transactions in a given bar or\n for the whole simulation.\n\n Parameters\n ----------\n dt : pd.Timestamp or None, optional\n The particular datetime to look up transactions for. If not passed,\n or None is explicitly passed, a...
Please provide a description of the function:def orders(self, dt=None): if dt is None: # orders by id is already flattened return [o.to_dict() for o in itervalues(self._orders_by_id)] return [ o.to_dict() for o in itervalues(self._orders_by_modif...
[ "Retrieve the dict-form of all of the orders in a given bar or for\n the whole simulation.\n\n Parameters\n ----------\n dt : pd.Timestamp or None, optional\n The particular datetime to look up order for. If not passed, or\n None is explicitly passed, all of the ord...