【答读者问35】关于pyfolio提示zipline.assets的警告信息
作者:yunjinqi   类别:    日期:2021-12-23 18:15:25    阅读:1393 次   消耗积分:0 分    

首先,必须要说明的是,这个不影响pyfolio的正常使用。可以忽略或者使用忽略

import warnings
warnings.filterwarnings("ignore")

接下来,梳理一下,为啥会出现这样的警告信息。后面的大家不用看了,几乎没啥含金量。

pyfolio的来源

pyfolio和zipline都来自过去著名的量化平台quantopian,zipline是其回测和交易框架,pyfolio是其绩效分析框架,pyfolio是对zipline的支持,所以,虽然zipline和pyfolio都已经开源了,但是pyfolio还是保存着一些从zipline获取的依赖信息。

pyfolio中都哪些函数使用了zipline.assets

pos.py中import zipline.assets中的Equty和Future,用于确定资产的杠杆,如果没有zipline这个,资产的倍数就按照1倍来计算。实际上,我们从backtrader中的analyzer中获取的postions的信息是已经计算过杠杆的了,所以,这里不用考虑杠杆。

try:
    from zipline.assets import Equity, Future
    ZIPLINE = Trueexcept ImportError:
    ZIPLINE = False
    warnings.warn(
        'Module "zipline.assets" not found; mutltipliers will not be applied' +
        ' to position notionals.'
    )
    def extract_pos(positions, cash):
    """
    Extract position values from backtest object as returned by
    get_backtest() on the Quantopian research platform.

    Parameters
    ----------
    positions : pd.DataFrame
        timeseries containing one row per symbol (and potentially
        duplicate datetime indices) and columns for amount and
        last_sale_price.
    cash : pd.Series
        timeseries containing cash in the portfolio.

    Returns
    -------
    pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    """

    positions = positions.copy()
    positions['values'] = positions.amount * positions.last_sale_price

    cash.name = 'cash'

    values = positions.reset_index().pivot_table(index='index',
                                                 columns='sid',
                                                 values='values')

    if ZIPLINE:
        for asset in values.columns:
            if type(asset) in [Equity, Future]:
                values[asset] = values[asset] * asset.price_multiplier

    values = values.join(cash).fillna(0)

    # NOTE: Set name of DataFrame.columns to sid, to match the behavior
    # of DataFrame.join in earlier versions of pandas.
    values.columns.name = 'sid'

    return values

在utils.py中,有下面的几个函数:

第一个用于标准化资产的名字,第二个用于从zipline的回测结果中提收益率、持仓、交易和杠杆信息,在使用pyfolio对接backtrader的时候,我们是直接从backtrader的analyzer中直接获取的,没有用到zipline.

def format_asset(asset):
    """
    If zipline asset objects are used, we want to print them out prettily
    within the tear sheet. This function should only be applied directly
    before displaying.
    """

    try:
        import zipline.assets    except ImportError:
        return asset    if isinstance(asset, zipline.assets.Asset):
        return asset.symbol    else:
        return assetdef extract_rets_pos_txn_from_zipline(backtest):
    """
    Extract returns, positions, transactions and leverage from the
    backtest data structure returned by zipline.TradingAlgorithm.run().

    The returned data structures are in a format compatible with the
    rest of pyfolio and can be directly passed to
    e.g. tears.create_full_tear_sheet().

    Parameters
    ----------
    backtest : pd.DataFrame
        DataFrame returned by zipline.TradingAlgorithm.run()

    Returns
    -------
    returns : pd.Series
        Daily returns of strategy.
         - See full explanation in tears.create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in tears.create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in tears.create_full_tear_sheet.


    Example (on the Quantopian research platform)
    ---------------------------------------------
    >>> backtest = my_algo.run()
    >>> returns, positions, transactions =
    >>>     pyfolio.utils.extract_rets_pos_txn_from_zipline(backtest)
    >>> pyfolio.tears.create_full_tear_sheet(returns,
    >>>     positions, transactions)
    """

    backtest.index = backtest.index.normalize()
    if backtest.index.tzinfo is None:
        backtest.index = backtest.index.tz_localize('UTC')
    returns = backtest.returns
    raw_positions = []
    for dt, pos_row in backtest.positions.iteritems():
        df = pd.DataFrame(pos_row)
        df.index = [dt] * len(df)
        raw_positions.append(df)
    if not raw_positions:
        raise ValueError("The backtest does not have any positions.")
    positions = pd.concat(raw_positions)
    positions = pos.extract_pos(positions, backtest.ending_cash)
    transactions = txn.make_transaction_frame(backtest.transactions)
    if transactions.index.tzinfo is None:
        transactions.index = transactions.index.tz_localize('utc')

    return returns, positions, transactions


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/63
上一篇:【答读者问34】backtrader及其编写的策略可以用在mac等电脑系统上?
下一篇:【答读者问36】使用btplotting或者backtraader_pyqt_ui增强backtrader的画图功能