Skip to content

Latest commit

 

History

History
154 lines (122 loc) · 5.44 KB

File metadata and controls

154 lines (122 loc) · 5.44 KB

【答读者问 35】关于 pyfolio 提示 zipline.assets 的警告信息

原文:https://yunjinqi.blog.csdn.net/article/details/121889059

云子量化免费阅读传送链接

首先,必须要说明的是,这个不影响 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 = True
except 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 asset

def 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