复制链接
克隆策略

策略名称

双均线股票分钟策略

策略逻辑

计算短周期均线值和长周期均线值,如果出现金叉,买入;如果出现死叉,卖出。

In [14]:
# 导入相应包
from biglearning.api import M
import math 
from bigtrader.sdk import *
import pandas as pd
import warnings
warnings.filterwarnings('ignore')

def initialize(context):
    """策略初始化函数,只触发一次。可以在该函数中初始化一些变量,如读取配置和全局使用数据"""
    #输出关键日志
    msg = "initialize:" 
    context.write_log(msg, stdout=1)
    context.ins = context.instruments #从传入参数中获取需要交易的合约
    context.short_ma = 5 #均线短周期参数
    context.long_ma = 64 #均线长周期参数
    context.set_stock_t1(False)  # False表明可以T0交易

def before_trading_start(context, data):
    """盘前处理,策略盘前交易函数,每日盘前触发一次。可以在该函数中一些启动前的准备,如订阅行情等"""
    #输出关键日志
    msg = "before_trading dt:{}".format(data.current_dt)
    context.write_log(msg, stdout=1) # stdout=1表示在console里打印 
    
    #如果需要处理tick数据,需要添加tick处理函数:handle_tick(context, tick):
    #如果需要使用handle_data,需要添加处理函数:handle_data(context, data):
def handle_data(context, data):
    """行情通知函数"""
    #获取当前时间
    cur_date =  data.current_dt # 当前分钟k线时间
    cur_hm = cur_date.strftime('%H:%M')
    
    # 获取账户可用资金
    total_portfolio = context.portfolio.cash

    for instr in context.ins:
        #获取持仓情况
        position = context.get_position(instr)
        #最新价格
        price = data.current(instr, "close")
            
        #获取1m历史数据数据
        hist = context.history_data(instr, ["open","high","low","close"], context.long_ma+5, "1m")
        # 计算均值
        short_ma = pd.Series(hist['close']).rolling(context.short_ma).mean()
        long_ma = pd.Series(hist['close']).rolling(context.long_ma).mean()  
        
        # 数据 条数不够就返回
        if len(long_ma) < context.long_ma:
            return 

        # 等权重
        weight = 1/len(context.ins)
        #短周期均线上穿越长周期均线买入(这里的判断是当前的k线上上穿,上一根k线没有达到上穿条件)
        if short_ma.iloc[-2]< long_ma.iloc[-2] and short_ma.iloc[-1]> long_ma.iloc[-1]:
            #当前没有持仓则市价买入
            if (position.current_qty == 0):
                #计算买入此股票的数量,不要超过总资金的某个比例
                order_num = math.floor(total_portfolio*weight/price/100)*100
                rv = context.order(instr, order_num, price, order_type=OrderType.MARKET)
                msg = "{} 买入{}  最新价={:.2f} 下单函数返回={}".format(cur_date,instr,price,rv)
                context.write_log(msg, stdout=0) 
       
        #短周期均线下穿越长周期均线卖出
        elif short_ma.iloc[-2] > long_ma.iloc[-2] and short_ma.iloc[-1] < long_ma.iloc[-1]:
            #有持仓则卖出    
            if (position.current_qty != 0):
                rv = context.order(instr, -position.current_qty, price, order_type=OrderType.MARKET)
                msg = "{} 卖出{}  最新价={:.2f} 下单函数返回={}".format(cur_date,instr,price,rv)
                context.write_log(msg, stdout=0)

def handle_order(context, order):
    """委托回报通知函数,每个订单状态有变化时会触发"""
    #输出关键日志
    msg = "handle_order data:{}".format(order.log_str())
    context.write_log(msg, stdout=0) # stdout=0表示不在console里打印 

def handle_trade(context, trade):
    """成交回报通知函数,有成交时会触发"""
    #输出关键日志
    msg = "handle_trade data:{}".format(trade.log_str())
    context.write_log(msg, stdout=0) 

backtest_result = M.hftrade.v2(
    instruments=['688517.SHA'],  
    start_date='2023-01-01',
    end_date='2023-02-09',
    handle_data=handle_data,
    before_trading_start=before_trading_start, 
    initialize=initialize,
    volume_limit=0.025,
    order_price_field_buy='open',
    order_price_field_sell='open',
    capital_base=1000000,
    frequency='minute',
    price_type='真实价格',
    product_type='股票',
    plot_charts=True,
    backtest_only=False,
    benchmark='000300.HIX' # 比较基准
)
[2023-05-15 14:56:34.726431] INFO moduleinvoker: hfbacktest.v2 开始运行..
INFO:moduleinvoker:hfbacktest.v2 开始运行..
[2023-05-15 14:56:34.750522] INFO hfbacktest: hfbacktest2 V2.0.0
INFO:hfbacktest:hfbacktest2 V2.0.0
[2023-05-15 14:56:34.780096] INFO hfbacktest: pytradersdk v1.0.0 2023-05-10
INFO:hfbacktest:pytradersdk v1.0.0 2023-05-10
[2023-05-15 14:56:34.871754] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-15 14:56:35.024979] INFO moduleinvoker: cached.v2 运行完成[0.153249s].
INFO:moduleinvoker:cached.v2 运行完成[0.153249s].
[2023-05-15 14:56:35.110716] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-15 14:56:35.432301] INFO moduleinvoker: cached.v2 运行完成[0.321528s].
INFO:moduleinvoker:cached.v2 运行完成[0.321528s].
[2023-05-15 14:56:35.512381] INFO moduleinvoker: cached.v2 开始运行..
INFO:moduleinvoker:cached.v2 开始运行..
[2023-05-15 14:56:35.704899] INFO moduleinvoker: cached.v2 运行完成[0.192496s].
INFO:moduleinvoker:cached.v2 运行完成[0.192496s].
[2023-05-15 14:56:35.769546] INFO hfbacktest: read history data done, call run backtest(equity,1m,1000000,2023-01-01~2023-02-09) ...
INFO:hfbacktest:read history data done, call run backtest(equity,1m,1000000,2023-01-01~2023-02-09) ...
2023-05-15 14:56:35.801186 initialize:
2023-05-15 14:56:35.817596 before_trading dt:2023-01-03 08:30:00
2023-05-15 14:56:36.133663 before_trading dt:2023-01-04 08:30:00
2023-05-15 14:56:36.427244 before_trading dt:2023-01-05 08:30:00
2023-05-15 14:56:36.920344 before_trading dt:2023-01-06 08:30:00
2023-05-15 14:56:37.315538 before_trading dt:2023-01-09 08:30:00
2023-05-15 14:56:37.614047 before_trading dt:2023-01-10 08:30:00
2023-05-15 14:56:37.899153 before_trading dt:2023-01-11 08:30:00
2023-05-15 14:56:38.215694 before_trading dt:2023-01-12 08:30:00
2023-05-15 14:56:38.566009 before_trading dt:2023-01-13 08:30:00
2023-05-15 14:56:38.882259 before_trading dt:2023-01-16 08:30:00
2023-05-15 14:56:39.186570 before_trading dt:2023-01-17 08:30:00
2023-05-15 14:56:39.516032 before_trading dt:2023-01-18 08:30:00
2023-05-15 14:56:39.856813 before_trading dt:2023-01-19 08:30:00
2023-05-15 14:56:40.146016 before_trading dt:2023-01-20 08:30:00
2023-05-15 14:56:40.508331 before_trading dt:2023-01-30 08:30:00
2023-05-15 14:56:40.830637 before_trading dt:2023-01-31 08:30:00
2023-05-15 14:56:41.198633 before_trading dt:2023-02-01 08:30:00
2023-05-15 14:56:41.483915 before_trading dt:2023-02-02 08:30:00
2023-05-15 14:56:41.830110 before_trading dt:2023-02-03 08:30:00
2023-05-15 14:56:42.150795 before_trading dt:2023-02-06 08:30:00
2023-05-15 14:56:42.579982 before_trading dt:2023-02-07 08:30:00
2023-05-15 14:56:42.907880 before_trading dt:2023-02-08 08:30:00
2023-05-15 14:56:43.259611 before_trading dt:2023-02-09 08:30:00
[2023-05-15 14:56:43.855189] INFO hfbacktest: backtest done, raw_perf_ds:DataSource(8bcaeca1b5354993afe541ec31517c09T)
INFO:hfbacktest:backtest done, raw_perf_ds:DataSource(8bcaeca1b5354993afe541ec31517c09T)
/usr/local/python3/lib/python3.8/site-packages/pandas/compat/_optional.py:116: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  if distutils.version.LooseVersion(version) < minimum_version:
/usr/local/python3/lib/python3.8/site-packages/setuptools/_distutils/version.py:346: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead.
  other = LooseVersion(other)
/usr/local/python3/lib/python3.8/site-packages/tables/atom.py:1224: DeprecationWarning: tostring() is deprecated. Use tobytes() instead.
  return pickle.loads(array.tostring())
[2023-05-15 14:56:44.536803] INFO: bigcharts.impl.render:render.py:407:render_chart Data is None, skip loading it to chart.
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
get_transactions read names from daily data DataSource(282f77b590444abf80d0bdefcf281e21T) failed
  • 收益率22.34%
  • 年化收益率734.05%
  • 基准收益率6.25%
  • 阿尔法5.21
  • 贝塔0.72
  • 夏普比率4.72
  • 胜率0.5
  • 盈亏比6.06
  • 收益波动率48.62%
  • 信息比率0.22
  • 最大回撤1.51%
日期 时间 股票代码 股票名称 买/卖 数量 成交价 总成本 交易佣金 平仓盈亏
Loading... (need help?)
日期 标的代码 标的名称 持仓均价 收盘价 数量 持仓价值 收益
Loading... (need help?)
时间 级别 内容
Loading... (need help?)
[2023-05-15 14:56:47.060328] INFO moduleinvoker: hfbacktest.v2 运行完成[12.333825s].
INFO:moduleinvoker:hfbacktest.v2 运行完成[12.333825s].
[2023-05-15 14:56:47.084656] INFO moduleinvoker: hftrade.v2 运行完成[12.387596s].
INFO:moduleinvoker:hftrade.v2 运行完成[12.387596s].