text
stringlengths
81
112k
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. def set_symbol_lookup_date(self, dt): """Set the date...
Place an order in the specified asset corresponding to the given percent of the current portfolio value. Parameters ---------- asset : Asset The asset that this order is for. percent : float The percentage of the portfolio value to allocate to ``asset``. ...
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 nu...
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 As...
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 t...
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.Index[str] Index of ids for newly-created orde...
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 ------- open_orders : dict[list[Order]] or list[Order] ...
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 object. def get_order(self, order_id): ...
Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. def cancel_order(self, order_param): """Cancel an open order. Parameters ---------- order_param : str or Order The order_id or...
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, ...
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. Parameters ---------- min_leverage : float The minimum leverage for the algorithm. grace_period : pd.Timedelta The offset from the start date used to enforce a minimum leverage. def set_min_leverage(self, min...
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....
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 spli...
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. If an algorithm attempts to place an order that would result in exceeding one...
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. def set_max_order_count(self, max_count, on_error='fail'): """Set a limit on the number o...
Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : Restrictions An object providing information about restricted assets. See Also -------- zipline.finance.asset_restrictions.Restrictions def set_asset_restrictions(self...
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. chunks : int or iterator, optional The number of days to compute pipelin...
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 DataFrame containing the results of t...
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 KeyErr...
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 + chunksize trading days, simulation_end)` Retu...
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...
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 une...
Checks the callable_ to make sure that it satisfies the given expectations. expected_args should be an iterable of Arguments in the order you expect to receive them. expect_starargs means that the function should or should not take a *args param. expect_kwargs says the callable should or should not ...
Takes a callable and returns a tuple with the list of Argument objects, the name of *args, and the name of **kwargs. If *args or **kwargs is not present, it will be None. This returns a namedtuple called Argspec that has three fields named: args, starargs, and kwargs. def parse_argspec(...
An asset is restricted for all dts if it is in the static list. def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """ if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( ...
Returns whether or not an asset or iterable of assets is restricted on a dt. def is_restricted(self, assets, dt): """ Returns whether or not an asset or iterable of assets is restricted on a dt. """ if isinstance(assets, Asset): return self._is_restricted_for...
Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from fractional shares after modifying each pos...
Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- cash_dividends : iterable of (asset, amount, pay_date) namedtuples stock_dividends: it...
Returns a cash payment based on the dividends that should be paid out according to the accumulated bookkeeping of earned, unpaid, and stock dividends. def pay_dividends(self, next_trading_day): """ Returns a cash payment based on the dividends that should be paid out according t...
The current status of the positions. Returns ------- stats : PositionStats The current stats position stats. Notes ----- This is cached, repeated access will not recompute the stats until the stats may have changed. def stats(self): """The c...
Add a transaction to ledger, updating the current state as needed. Parameters ---------- transaction : zp.Transaction The transaction to execute. def process_transaction(self, transaction): """Add a transaction to ledger, updating the current state as needed. Param...
Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list[(Asset, float)] A list of splits. Each split is a tuple of (asset, ratio). def process_splits(self, splits): """Processes a list of splits by modifying any positions as neede...
Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record. def process_order(self, order): """Keep track of an order that was placed. Parameters ---------- order : zp.Order The order to record. ...
Process the commission. Parameters ---------- commission : zp.Event The commission being paid. def process_commission(self, commission): """Process the commission. Parameters ---------- commission : zp.Event The commission being paid. ...
Process dividends for the next session. This will earn us any dividends whose ex-date is the next session as well as paying out any dividends whose pay-date is the next session def process_dividends(self, next_session, asset_finder, adjustment_reader): """Process dividends for the next session...
Retrieve the dict-form of all of the transactions in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up transactions for. If not passed, or None is explicitly passed, all of the tr...
Retrieve the dict-form of all of the orders in a given bar or for the whole simulation. Parameters ---------- dt : pd.Timestamp or None, optional The particular datetime to look up order for. If not passed, or None is explicitly passed, all of the orders will be ...
Force a computation of the current portfolio state. def update_portfolio(self): """Force a computation of the current portfolio state. """ if not self._dirty_portfolio: return portfolio = self._portfolio pt = self.position_tracker portfolio.positions = pt.g...
Override fields on ``self.account``. def override_account_fields(self, settled_cash=not_overridden, accrued_interest=not_overridden, buying_power=not_overridden, equity_with_loan=not_overridd...
Given a datashape type, return the associated numpy type. Maps datashape's DateTime type to numpy's `datetime64[ns]` dtype, since the numpy datetime returned by datashape isn't supported by pipeline. Parameters ---------- type_: datashape.coretypes.Type The datashape type. Returns ...
Creates or returns a dataset from a blaze expression. Parameters ---------- expr : Expr The blaze expression representing the values. missing_values : frozenset((name, value) pairs Association pairs column name and missing_value for that column. This needs to be a frozenset rat...
Validate that the expression and resources passed match up. Parameters ---------- name : str The name of the argument we are checking. expr : Expr The potentially bound expr. resources The explicitly passed resources to compute expr. Raises ------ ValueError ...
Check that a field is a datetime inside some measure. Parameters ---------- name : str The name of the field to check. measure : Record The record to check the field of. Raises ------ TypeError If the field is not a datetime inside ``measure``. def _check_datetime_...
Find the correct metadata expression for the expression. Parameters ---------- field : {'deltas', 'checkpoints'} The kind of metadata expr to lookup. expr : Expr The baseline expression. metadata_expr : Expr, 'auto', or None The metadata argument. If this is 'auto', then the...
Verify that the baseline and deltas expressions have a timestamp field. If there is not a ``TS_FIELD_NAME`` on either of the expressions, it will be copied from the ``AD_FIELD_NAME``. If one is provided, then we will verify that it is the correct dshape. Parameters ---------- dataset_expr : Ex...
Create a Pipeline API object from a blaze expression. Parameters ---------- expr : Expr The blaze expression to use. deltas : Expr, 'auto' or None, optional The expression to use for the point in time adjustments. If the string 'auto' is passed, a deltas expr will be looked up ...
Bind a Blaze expression to resources. Parameters ---------- expr : bz.Expr The expression to which we want to bind resources. resources : dict[bz.Symbol -> any] Mapping from the loadable terms of ``expr`` to actual data resources. Returns ------- bound_expr : bz.Expr ...
Computes a lower bound and a DataFrame checkpoints. Parameters ---------- checkpoints : Expr Bound blaze expression for a checkpoints table from which to get a computed lower bound. colnames : iterable of str The names of the columns for which checkpoints should be computed. ...
Query a blaze expression in a given time range properly forward filling from values that fall before the lower date. Parameters ---------- expr : Expr Bound blaze expression. lower : datetime The lower date to query for. upper : datetime The upper date to query for. ...
Explicitly map a datset to a collection of blaze expressions. Parameters ---------- dataset : DataSet The pipeline dataset to map to the given expressions. expr : Expr The baseline values. deltas : Expr, optional The deltas for the data. ...
Explicitly map a single bound column to a collection of blaze expressions. The expressions need to have ``timestamp`` and ``as_of`` columns. Parameters ---------- column : BoundColumn The pipeline dataset to map to the given expressions. expr : Expr ...
Given a dict of mappings where the values are lists of OwnershipPeriod objects, returns a dict with the same structure with new OwnershipPeriod objects adjusted so that the periods have no gaps. Orders the periods chronologically, and pushes forward the end date of each period to match the start da...
Builds a dict mapping to lists of OwnershipPeriods, from a db table. def build_ownership_map(table, key_from_row, value_from_row): """ Builds a dict mapping to lists of OwnershipPeriods, from a db table. """ return _build_ownership_map_from_rows( sa.select(table.c).execute().fetchall(), ...
Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table. def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): """ Builds a dict mapping group...
Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the keys intersect with ``names`` and the va...
Takes in a dict of Asset init args and converts dates to pd.Timestamps def _convert_asset_timestamp_fields(dict_): """ Takes in a dict of Asset init args and converts dates to pd.Timestamps """ for key in _asset_timestamp_fields & viewkeys(dict_): value = pd.Timestamp(dict_[key], tz='UTC') ...
Whether or not `asset` was active at the time corresponding to `reference_date_value`. Parameters ---------- reference_date_value : int Date, represented as nanoseconds since EPOCH, for which we want to know if `asset` was alive. This is generally the result of accessing the `v...
Retrieve asset types for a list of sids. Parameters ---------- sids : list[int] Returns ------- types : dict[sid -> str or None] Asset types for the provided sids. def lookup_asset_types(self, sids): """ Retrieve asset types for a list of si...
Retrieve all assets in `sids`. Parameters ---------- sids : iterable of int Assets to retrieve. default_none : bool If True, return None for failed lookups. If False, raise `SidsNotFound`. Returns ------- assets : list[Asset o...
Retrieve the most recent symbol for a set of sids. Parameters ---------- sid_group : iterable[int] The sids to lookup. The length of this sequence must be less than or equal to SQLITE_MAX_VARIABLE_NUMBER because the sids will be passed in as sql bind params. ...
Internal function for loading assets from a table. This should be the only method of `AssetFinder` that writes Assets into self._asset_cache. Parameters --------- sids : iterable of int Asset ids to look up. asset_tbl : sqlalchemy.Table Table fro...
Resolve a symbol to an asset object without fuzzy matching. Parameters ---------- ownership_map : dict[(str, str), list[OwnershipPeriod]] The mapping from split symbols to ownership periods. multi_country : bool Does this mapping span multiple countries? ...
Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_date : datetime or None Look up the last owner of this symbol as of this datetime. If ``as_of_date`` is None, then this can only resolve the equity ...
Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------- symbols : sequence[str] Sequence of ticker symbols to reso...
Lookup a future contract by symbol. Parameters ---------- symbol : str The symbol of the desired contract. Returns ------- future : Future The future contract referenced by ``symbol``. Raises ------ SymbolNotFound ...
Get the value of a supplementary field for an asset. Parameters ---------- sid : int The sid of the asset to query. field_name : str Name of the supplementary field. as_of_date : pd.Timestamp, None The last known value on this date is returned...
Convert asset_convertible to an asset. On success, append to matches. On failure, append to missing. def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, ...
Convert an object into an Asset or sequence of Assets. This method exists primarily as a convenience for implementing user-facing APIs that can handle multiple kinds of input. It should not be used for internal code where we already know the expected types of our inputs. Param...
Compute and cache a recarray of asset lifetimes. def _compute_asset_lifetimes(self, country_codes): """ Compute and cache a recarray of asset lifetimes. """ equities_cols = self.equities.c if country_codes: buf = np.array( tuple( s...
Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_date : bool Whether or not to count the asset as alive on its start_date....
Return all of the sids for a given country. Parameters ---------- country_code : str An ISO 3166 alpha-2 country code. Returns ------- tuple[int] The sids whose exchanges are in this country. def equities_sids_for_country_code(self, country_code...
Parameters ---------- fields : list of str 'sid' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window. Returns ------- ...
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 minute 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 minute. dt : pd.Timestamp Th...
Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window range. sids : list of int The asset identifiers in the window....
Compute each asset's weight in the portfolio by calculating its held value divided by the total value of all positions. Each equity's value is its price times the number of shares held. Each futures contract's value is its unit price times number of shares held times the multiplier. de...
将微信明细中图片托管到云端,同时将html页面中的对应图片替换 Parameters ---------- content_info : dict 微信文章明细字典 { 'content_img_list': [], # 从微信文章解析出的原始图片列表 'content_html': '', # 从微信文章解析出文章的内容 } hosting_callback : callable 托管回调函数,传入单个图片链接,返回托管后的图片链接...
获取公众号微信号 wechatid 的信息 因为wechatid唯一确定,所以第一个就是要搜索的公众号 Parameters ---------- wecgat_id_or_name : str or unicode wechat_id or wechat_name unlock_callback : callable 处理出现验证码页面的函数,参见 unlock_callback_example identify_image_callback : callable ...
搜索 公众号 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Par...
搜索 文章 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_callback 不起作用 Para...
从 公众号的最近10条群发页面 提取公众号信息 和 文章列表信息 对于出现验证码的情况,可以由使用者自己提供: 1、函数 unlock_callback ,这个函数 handle 出现验证码到解决的整个流程 2、也可以 只提供函数 identify_image_callback,这个函数输入验证码二进制数据,输出验证码文字,剩下的由 wechatsogou 包来解决 注意: 函数 unlock_callback 和 identify_image_callback 只需要提供一个,如果都提供了,那么 identify_image_...
获取 首页热门文章 Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公...
获取文章原文,避免临时链接失效 Parameters ---------- url : str or unicode 原文链接,临时链接 raw : bool True: 返回原始html False: 返回处理后的html del_qqmusic: bool True:微信原文中有插入的qq音乐,则删除 False:微信源文中有插入的qq音乐,则保留 del_mpvoice: bool Tru...
获取微信搜狗搜索关键词联想 Parameters ---------- keyword : str or unicode 关键词 Returns ------- list[str] 联想关键词列表 Raises ------ WechatSogouRequestsException def get_sugg(self, keyword): """获取微信搜狗搜索关键词联想 Parameters ...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
手动打码解锁 Parameters ---------- url : str or unicode 验证码页面 之前的 url req : requests.sessions.Session requests.Session() 供调用解锁 resp : requests.models.Response requests 访问页面返回的,已经跳转了 img : bytes 验证码图片二进制数据 identify_image_callback : callable 处理验证码函数,输入验证码二进制数...
拼接搜索 文章 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 timesn : WechatSogouConst.search_article_time 时间 anytime 没有限制 / day 一天 / week 一周 / month 一月 / year 一年 / specific 自定 默认是 anytim...
拼接搜索 公众号 URL Parameters ---------- keyword : str or unicode 搜索文字 page : int, optional 页数 the default is 1 Returns ------- str search_gzh_url def gen_search_gzh_url(keyword, page=1): """拼接搜索 公众号 URL Parameters...
拼接 首页热门文章 URL Parameters ---------- hot_index : WechatSogouConst.hot_index 首页热门文章的分类(常量):WechatSogouConst.hot_index.xxx page : int 页数 Returns ------- str 热门文章分类的url def gen_hot_url(hot_index, page=1): """拼接 首页热门文章 URL...
抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 def get_first_of_element(element, sub, contype=None): """抽取lxml.etree库中elem对象中文字 Args: element: lxml.etree.Element sub: str Returns: elem中文字 """ content = ...
获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 def get_encoding_from_reponse(r): """获取requests库get或post返回的对象编码 Args: r: requests库get或post返回的对象 Returns: 对象编码 """ encoding = requests.utils.get_encodings_from_content(r.text) ret...
替换html‘"’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 def _replace_str_html(s): """替换html‘"’等转义内容为正常内容 Args: s: 文字内容 Returns: s: 处理反转义后的文字 """ html_str_list = [ (''', '\''), ('"', '"'), ('&', '&'), ...
从搜索公众号获得的文本 提取公众号信息 Parameters ---------- text : str or unicode 搜索公众号获得的文本 Returns ------- list[dict] { 'open_id': '', # 微信号唯一ID 'profile_url': '', # 最近10条群发页链接 'headimage': '', # 头像 ...
从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '', # 文章链接 'imgs': '', # ...
从 历史消息页的文本 提取公众号信息 Parameters ---------- text : str or unicode 历史消息页的文本 Returns ------- dict { 'wechat_name': '', # 名称 'wechat_id': '', # 微信id 'introduction': '', # 描述 'authentica...
从 历史消息页的文本 提取文章列表信息 Parameters ---------- text : str or unicode 历史消息页的文本 article_json : dict 历史消息页的文本 提取出来的文章json dict Returns ------- list[dict] { 'send_id': '', # 群发id,注意不唯一,因为同一次群发多个消息,而群发id一致 ...
从 首页热门搜索 提取公众号信息 和 文章列表信息 Parameters ---------- text : str or unicode 首页热门搜索 页 中 某一页 的文本 Returns ------- list[dict] { 'gzh': { 'headimage': str, # 公众号头像 'wechat_name': str, # 公众号名称 ...
根据微信文章的临时链接获取明细 1. 获取文本中所有的图片链接列表 2. 获取微信文章的html内容页面(去除标题等信息) Parameters ---------- text : str or unicode 一篇微信文章的文本 del_qqmusic: bool 删除文章中的qq音乐 del_voice: bool 删除文章中的语音内容 Returns ------- dict ...