数字货币量化之仓位管理的实现 (上)

交易周期操作更新

handle_data

  • handle_data() 函数在每个bar数据交易周期的结束时刻运行
  • 可以使用当前交易周期的close数据,之前我们都是用的前三天的数据,现在只需要两天,因为可以拿到当天的收盘价
  • 此时交易的价格为 close 数据

file

基准策略

  • 投资组合:BTC,ETH,LTC,EOS
  • 复利/不复利方式
  • 头寸规模确定:等额资金分配
  • 结果:
    • 策略收益: 119.238%
    • 策略年化收益:70.949%
    • 策略波动率:37.756%
    • 夏普比率:1.622
    • 最大回撤:25.636%

代码实战

dma_baisc_alg.py

"""
    双均线基准策略
    - 等额资金分配
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from catalyst import run_algorithm
from catalyst.api import record, symbol, order_target, order
from logbook import Logger

# 需要先加载数据
# catalyst ingest-exchange -x binance -i btc_usdt -f daily
# catalyst ingest-exchange -x binance -i eth_usdt -f daily
# catalyst ingest-exchange -x binance -i ltc_usdt -f daily
# catalyst ingest-exchange -x binance -i eos_usdt -f daily

NAMESPACE = 'dma_basic'
log = Logger(NAMESPACE)

SHORT_WIN = 5               # 短周期窗口
LONG_WIN = 25               # 长周期窗口

def get_available_cash(context, use_compound_interest=False):
    """
        获取当前可用资金
        use_compound_interest: 是否使用复利
    """
    if use_compound_interest:
        # 使用复利
        available_cash = context.portfolio.cash
    else:
        available_cash = min(context.portfolio.starting_cash, context.portfolio.cash)
    return available_cash

def get_risk_indices(perf):
    """
        计算风险指标,包括:
        1. 策略收益
        2. 策略年化收益
        3. 策略波动率
        4. 夏普比率
        5. 最大回撤
    """
    # 策略执行天数
    n = len(perf)

    # 1. 策略收益
    total_returns = perf.iloc[-1]['algorithm_period_return']

    # 2. 策略年化收益
    total_ann_returns = (1 + total_returns) ** (250 / n) - 1

    # 3. 策略波动率(catalyst框架已经帮我们计算出来了)
    algo_volatility = perf.iloc[-1]['algo_volatility']

    # 4. 夏普比率
    sharpe = perf.iloc[-1]['sharpe']

    # 5. 最大回撤
    max_drawdown = np.abs(perf.iloc[-1]['max_drawdown'])

    return total_returns, total_ann_returns, algo_volatility, sharpe, max_drawdown

def initialize(context):
    """
        初始化
    """
    log.info('策略初始化')
    context.i = 0                       # 经历过的交易周期
    # 设置加密货币池
    context.asset_pool = [symbol('btc_usdt'),
                          symbol('eth_usdt'),
                          symbol('ltc_usdt'),
                          symbol('eos_usdt')]
    context.set_commission(maker=0.001, taker=0.001)    # 设置手续费
    context.set_slippage(slippage=0.001)                # 设置滑点

def handle_data(context, data):
    """
        在每个交易周期上运行的策略
    """
    context.i += 1  # 记录交易周期,因为可以拿到当天的收盘价,所以,这里加1,而不是之前的加2了
    if context.i < LONG_WIN + 1:
        # 如果交易周期过短,无法计算均线,则跳过循环
        log.warning('交易周期过短,无法计算指标')
        return

    # 获取当前周期内有效的加密货币
    context.available_asset_pool = [asset
                                    for asset in context.asset_pool
                                    if asset.start_date <= data.current_dt]

    context.up_cross_signaled = set()   # 初始化金叉的交易对集合
    context.down_cross_signaled = set()  # 初始化死叉的交易对集合

    for asset in context.available_asset_pool:
        # 遍历每一个加密货币对
        # 获得历史价格
        hitory_data = data.history(asset,
                                   'close',
                                   bar_count=LONG_WIN + 1,
                                   frequency='1D',
                                   )
        if len(hitory_data) >= LONG_WIN + 1:
            # 保证新的货币有足够的时间计算均线
            # 计算双均线
            short_avgs = hitory_data.rolling(window=SHORT_WIN).mean()
            long_avgs = hitory_data.rolling(window=LONG_WIN).mean()

            # 双均线策略
            # 短期均线上穿长期均线,短期前一天小于长期,并且 当天短期大于长期,则为金叉
            if (short_avgs[-2] < long_avgs[-2]) and (short_avgs[-1] >= long_avgs[-1]):
                # 形成金叉
                context.up_cross_signaled.add(asset)

            # 短期均线下穿长期均线
            if (short_avgs[-2] > long_avgs[-2]) and (short_avgs[-1] <= long_avgs[-1]):
                # 形成死叉
                context.down_cross_signaled.add(asset)

    # 卖出均线死叉信号的持仓交易对
    for asset in context.portfolio.positions:
        if asset in context.down_cross_signaled:
            order_target(asset, 0)

    # 买入均线金叉信号的持仓股
    for asset in context.up_cross_signaled:
        if asset not in context.portfolio.positions:
            close_price = data.current(asset, 'close')

            available_cash = get_available_cash(context)
            if available_cash > 0:
                # 如果有可用现金
                # 每个交易对平均分配现金
                cash_for_each_asset = available_cash / len(context.available_asset_pool)

                amount_to_buy = cash_for_each_asset / close_price    # 计算购买的数量
                if amount_to_buy >= asset.min_trade_size:
                    # 购买的数量大于最小购买数量
                    order(asset, amount_to_buy)

    # 持仓比例
    pos_level = context.portfolio.positions_value / context.portfolio.portfolio_value

    # 记录每个交易周期的现金
    record(cash=context.portfolio.cash, pos_level=pos_level)

    # 输出信息
    log.info('日期:{},资产:{:.2f},持仓比例:{:.6f}%,持仓产品:{}'.format(
        data.current_dt, context.portfolio.portfolio_value, pos_level * 100,
        ', '.join([asset.asset_name for asset in context.portfolio.positions]))
    )

def analyze(context, perf):
    # 保存交易记录
    perf.to_csv('./perf_results/dma_basic_performance.csv')

    # 获取交易所的计价货币
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()

    # 图1:可视化资产值
    ax1 = plt.subplot(311)
    perf['portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio Value\n({})'.format(quote_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # 图2:可视化仓位
    ax2 = plt.subplot(312)
    perf['pos_level'].plot(ax=ax2)
    ax2.set_ylabel('Position Level')
    start, end = 0, 1
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # 图3:可视化现金数量
    ax3 = plt.subplot(313, sharex=ax1)
    perf['cash'].plot(ax=ax3)
    ax3.set_ylabel('Cash\n({})'.format(quote_currency))
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.tight_layout()
    plt.show()

    # 评价策略
    total_returns, total_ann_returns, algo_volatility, sharpe, max_drawdown = get_risk_indices(perf)
    log.info('策略收益: {:.3f}%, 策略年化收益: {:.3f}%, 策略波动率: {:.3f}%, 夏普比率: {:.3f}, 最大回撤: {:.3f}%'.format(
        total_returns * 100, total_ann_returns * 100, algo_volatility * 100, sharpe, max_drawdown * 100
    ))

if __name__ == '__main__':
    run_algorithm(
        capital_base=100000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='binance',
        algo_namespace=NAMESPACE,
        quote_currency='usdt',
        start=pd.to_datetime('2019-02-01', utc=True),
        end=pd.to_datetime('2019-12-22', utc=True)
    )

file

结果打印:

[2019-12-23 15:13:58.068289] INFO: dma_basic: 日期:2019-05-11 23:59:00+00:00,资产:110325.41,持仓比例:24.913164%,持仓产品:ETH / USDT
[2019-12-23 15:13:58.085725] INFO: dma_basic: 日期:2019-05-12 23:59:00+00:00,资产:109982.83,持仓比例:43.141850%,持仓产品:ETH / USDT, LTC / USDT
[2019-12-23 15:13:58.108327] INFO: dma_basic: 日期:2019-05-13 23:59:00+00:00,资产:111648.70,持仓比例:58.511697%,持仓产品:ETH / USDT, LTC / USDT, EOS / USDT
[2019-12-23 15:13:58.128956] INFO: dma_basic: 日期:2019-05-14 23:59:00+00:00,资产:116988.33,持仓比例:60.405324%,持仓产品:ETH / USDT, LTC / USDT, EOS / USDT
[2019-12-23 15:13:58.150533] INFO: dma_basic: 日期:2019-05-15 23:59:00+00:00,资产:125528.28,持仓比例:63.099033%,持仓产品:ETH / USDT, LTC / USDT, EOS / USDT
.
.
.
[2019-12-23 15:13:58.933136] INFO: dma_basic: 日期:2019-06-22 23:59:00+00:00,资产:143255.38,持仓比例:71.138528%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:58.955364] INFO: dma_basic: 日期:2019-06-23 23:59:00+00:00,资产:141999.41,持仓比例:70.883250%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:58.976089] INFO: dma_basic: 日期:2019-06-24 23:59:00+00:00,资产:142209.20,持仓比例:70.926205%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:58.998289] INFO: dma_basic: 日期:2019-06-25 23:59:00+00:00,资产:144850.17,持仓比例:71.456289%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:59.021467] INFO: dma_basic: 日期:2019-06-26 23:59:00+00:00,资产:148310.38,持仓比例:72.122239%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:59.043160] INFO: dma_basic: 日期:2019-06-27 23:59:00+00:00,资产:134755.19,持仓比例:69.317981%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:59.066632] INFO: dma_basic: 日期:2019-06-28 23:59:00+00:00,资产:140203.28,持仓比例:70.510239%,持仓产品:LTC / USDT, BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:59.089773] INFO: dma_basic: 日期:2019-06-29 23:59:00+00:00,资产:142700.00,持仓比例:48.635408%,持仓产品:BTC / USDT, ETH / USDT, EOS / USDT
[2019-12-23 15:13:59.110369] INFO: dma_basic: 日期:2019-06-30 23:59:00+00:00,资产:136816.77,持仓比例:37.958767%,持仓产品:BTC / USDT, ETH / USDT
[2019-12-23 15:13:59.135115] INFO: dma_basic: 日期:2019-07-01 23:59:00+00:00,资产:136320.93,持仓比例:37.733107%,持仓产品:BTC / USDT, ETH / USDT

...

[2019-12-23 15:14:01.913691] INFO: dma_basic: 日期:2019-11-15 23:59:00+00:00,资产:108507.63,持仓比例:47.196208%,持仓产品:EOS / USDT, LTC / USDT, ETH / USDT
[2019-12-23 15:14:01.932070] INFO: dma_basic: 日期:2019-11-16 23:59:00+00:00,资产:109138.60,持仓比例:47.501485%,持仓产品:EOS / USDT, LTC / USDT, ETH / USDT
[2019-12-23 15:14:01.952659] INFO: dma_basic: 日期:2019-11-17 23:59:00+00:00,资产:109637.98,持仓比例:47.740609%,持仓产品:EOS / USDT, LTC / USDT, ETH / USDT
[2019-12-23 15:14:01.979233] INFO: dma_basic: 日期:2019-11-18 23:59:00+00:00,资产:106747.06,持仓比例:32.388759%,持仓产品:EOS / USDT, ETH / USDT
[2019-12-23 15:14:02.003355] INFO: dma_basic: 日期:2019-11-19 23:59:00+00:00,资产:106085.48,持仓比例:0.000000%,持仓产品:

风险指标:

[2019-12-23 15:14:02.614208] INFO: Performance: last close: 2019-12-22 23:59:00+00:00
[2019-12-23 15:38:27.865038] INFO: dma_basic: 策略收益: 6.085%, 策略年化收益: 4.649%, 策略波动率: 25.757%, 夏普比率: 0.307, 最大回撤: 28.471%

为者常成,行者常至