Exemplo n.º 1
0
def take_snapshot(context, trader, name):
    """

    :param context:
    :param trader:
    :param name: str
        平多、平空、开多、开空、快照
    :return:
    """
    symbol = trader.symbol
    now_ = context.now.strftime('%Y%m%d_%H%M')
    price = trader.latest_price
    file_html = os.path.join(context.cache_path, f"{symbol}_{name}_{price}_{now_}.html")
    trader.take_snapshot(file_html, width="1400px", height="580px")
    if context.mode != MODE_BACKTEST:
        push_file(file_html, key=context.wx_key)
Exemplo n.º 2
0
def check_index_status(qywx_key):
    """查看主要指数状态"""
    from czsc.utils.cache import home_path

    end_dt = datetime.now().strftime(dt_fmt)
    wx.push_text(f"{end_dt} 开始获取主要指数行情快照", qywx_key)
    for gm_symbol in indices.values():
        try:
            file_html = os.path.join(
                home_path,
                f"{gm_symbol}_{datetime.now().strftime('%Y%m%d')}.html")
            gm_take_snapshot(gm_symbol, end_dt, file_html=file_html)
            wx.push_file(file_html, qywx_key)
            os.remove(file_html)
        except:
            traceback.print_exc()
    wx.push_text(f"{end_dt} 获取主要指数行情快照获取结束,请仔细观察!!!", qywx_key)
Exemplo n.º 3
0
def monitor(use_cache=True):
    push_text("自选股CZSC笔因子监控启动 @ {}".format(datetime.now().strftime("%Y-%m-%d %H:%M")), qywx_key)
    moni_path = os.path.join(ct_path, "monitor")
    # 首先清空历史快照
    if os.path.exists(moni_path):
        shutil.rmtree(moni_path)
    os.makedirs(moni_path, exist_ok=True)

    for s in symbols:
        print(s)
        try:
            file_ct = os.path.join(ct_path, "{}.ct".format(s))
            if os.path.exists(file_ct) and use_cache:
                ct: CzscTrader = read_pkl(file_ct)
                ct.update_factors()
            else:
                ct = CzscTrader(s, max_count=1000)
            save_pkl(ct, file_ct)

            # 每次执行,会在moni_path下面保存一份快照
            file_html_ = os.path.join(moni_path, f"{ct.symbol}_{ct.kf.end_dt.strftime('%Y%m%d%H%M')}.html")
            ct.take_snapshot(file_html_, width="1400px", height="580px")

            if ct.s['日线笔因子'] != Factors.Other.value:
                msg = "{} - {}\n".format(s, ct.s['日线笔因子'])
                msg += "同花顺F10:http://basic.10jqka.com.cn/{}".format(s[:6])
                push_text(msg, key=qywx_key)
                file_html_new = os.path.join(moni_path, f"{ct.symbol}_{ct.kf.end_dt.strftime('%Y%m%d%H%M')}.html")
                shutil.copyfile(file_html_, file_html_new)
                push_file(file_html_new, key=qywx_key)

        except Exception as e:
            traceback.print_exc()
            print("{} 执行失败 - {}".format(s, e))

    push_text("自选股CZSC笔因子监控结束 @ {}".format(datetime.now().strftime("%Y-%m-%d %H:%M")), qywx_key)
Exemplo n.º 4
0
def on_backtest_finished(context, indicator):
    """回测结束回调函数

    :param context:
    :param indicator:
        https://www.myquant.cn/docs/python/python_object_trade#bd7f5adf22081af5
    :return:
    """
    wx_key = context.wx_key
    symbols = context.symbols
    data_path = context.data_path
    logger = context.logger

    logger.info(str(indicator))
    logger.info("回测结束 ... ")
    cash = context.account().cash

    for k, v in indicator.items():
        if isinstance(v, float):
            indicator[k] = round(v, 4)

    row = OrderedDict({
        "研究标的": ", ".join(list(context.symbols_info.keys())),
        "回测开始时间": context.backtest_start_time,
        "回测结束时间": context.backtest_end_time,
        "累计收益率": indicator['pnl_ratio'],
        "最大回撤": indicator['max_drawdown'],
        "年化收益率": indicator['pnl_ratio_annual'],
        "夏普比率": indicator['sharp_ratio'],
        "盈利次数": indicator['win_count'],
        "亏损次数": indicator['lose_count'],
        "交易胜率": indicator['win_ratio'],
        "累计出入金": int(cash['cum_inout']),
        "累计交易额": int(cash['cum_trade']),
        "累计手续费": int(cash['cum_commission']),
        "累计平仓收益": int(cash['cum_pnl']),
        "净收益": int(cash['pnl']),
    })
    sdt = pd.to_datetime(context.backtest_start_time).strftime('%Y%m%d')
    edt = pd.to_datetime(context.backtest_end_time).strftime('%Y%m%d')
    file_xlsx = os.path.join(data_path, f'{context.name}_{sdt}_{edt}.xlsx')
    file = pd.ExcelWriter(file_xlsx, mode='w')

    dfe = pd.DataFrame({"指标": list(row.keys()), "值": list(row.values())})
    dfe.to_excel(file, sheet_name='回测表现', index=False)

    logger.info("回测结果:{}".format(row))
    content = ""
    for k, v in row.items():
        content += "{}: {}\n".format(k, v)
    wx.push_text(content=content, key=wx_key)

    trades = []
    operates = []
    performances = []
    for symbol in symbols:
        trader: GmCzscTrader = context.symbols_info[symbol]['trader']
        trades.extend(trader.long_pos.pairs)
        operates.extend(trader.long_pos.operates)
        performances.append(trader.long_pos.evaluate_operates())

    df = pd.DataFrame(trades)
    df['开仓时间'] = df['开仓时间'].apply(lambda x: x.strftime("%Y-%m-%d %H:%M"))
    df['平仓时间'] = df['平仓时间'].apply(lambda x: x.strftime("%Y-%m-%d %H:%M"))
    df.to_excel(file, sheet_name='交易汇总', index=False)

    dfo = pd.DataFrame(operates)
    dfo['dt'] = dfo['dt'].apply(lambda x: x.strftime("%Y-%m-%d %H:%M"))
    dfo.to_excel(file, sheet_name='操作汇总', index=False)

    dfp = pd.DataFrame(performances)
    dfp.to_excel(file, sheet_name='表现汇总', index=False)
    file.close()

    wx.push_file(file_xlsx, wx_key)