港股回測沒有問題, 模擬盤卻沒有信號


(wwwburoka) #1

非常奇怪, 我的策略在回測時沒有問題, 但去了模擬盤時卻沒有信號, 是不是哪裏出錯?

代碼:

本代码由可视化策略环境自动生成 2018年5月18日 13:56

本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。

m1 = M.instruments.v2(
start_date=‘2016-01-01’,
end_date=‘2017-11-21’,
market=‘HK_STOCK’,
instrument_list=""“0001.HKEX
0002.HKEX
0003.HKEX
0005.HKEX
0006.HKEX
0011.HKEX
0012.HKEX
0016.HKEX
0017.HKEX
0019.HKEX
0023.HKEX
0027.HKEX
0066.HKEX
0083.HKEX
0101.HKEX
0151.HKEX
0175.HKEX
0267.HKEX
0288.HKEX
0386.HKEX
0388.HKEX
0688.HKEX
0700.HKEX
0762.HKEX
0823.HKEX
0836.HKEX
0857.HKEX
0883.HKEX
0939.HKEX
0941.HKEX
0992.HKEX
1038.HKEX
1044.HKEX
1088.HKEX
1109.HKEX
1113.HKEX
1299.HKEX
1398.HKEX
1928.HKEX
1997.HKEX
2007.HKEX
2018.HKEX
2318.HKEX
2319.HKEX
2382.HKEX
2388.HKEX
2628.HKEX
3328.HKEX
3988.HKEX”"",
max_count=0
)

def add_column(df, series, name):
df[name] = series
return df

计算atr函数

def atr(high,low,close,window):
a=high-low
b=np.abs(close.shift(1)-high)
c=np.abs(close.shift(1)-low)
tr=a.where(a>b,b)
tr=tr.where(tr>c,c)
return tr.rolling(window).mean()

Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端

def m2_run_bigquant_run(input_1, input_2, input_3):
# 示例代码如下。在这里编写您的代码
df = input_1.read_pickle()

start_date = df['start_date']
end_date = df['end_date']
fields = ['open','high','low','close']
instruments =  df['instruments']
data = D.history_data(instruments, start_date, end_date, fields)
atr_data  = data.groupby('instrument').apply(lambda x:add_column(x,atr(x.high,x.low,x.close,20),'ATR')).set_index('date')  
data = DataSource.write_df(atr_data)
return Outputs(data_1=data, data_2=None, data_3=None)

m2 = M.cached.v3(
input_1=m1.data,
run=m2_run_bigquant_run
)

回测引擎:每日数据处理函数,每天执行一次

def m3_handle_data_bigquant_run(context, data):

dt = data.current_dt.strftime('%Y-%m-%d') #  
for i in context.instruments:
    # 当天没有该股票的ATR数据就continue 
    try:
        atr = context.atr_data.ix[dt].set_index('instrument').ix[i]['ATR']
    except KeyError:
        continue
    # 如果该股票的ATR为nan或者为0,就填充其为100    
    if numpy.isnan(atr) == False and atr != 0:
        a_unit = int(context.portfolio.portfolio_value*0.01/atr)
    else:
        a_unit = 100
        
    sid = context.symbol(i)
    price = data.current(sid, 'price')  
    high_point = data.history(sid, 'high', context.entry_pos_period, '1d').max()
    low_point = data.history(sid, 'low', context.exit_pos_period, '1d').min()
    stock_hold_now = [equity.symbol for equity in context.portfolio.positions]
    
    # 计算加仓点和止损点
    if i in stock_hold_now:
        add_pos_point = context.portfolio.positions[sid].last_sale_price+0.5*atr
        stop_loss_point = context.portfolio.positions[sid].last_sale_price-2*atr
    else:
        add_pos_point = np.nan
        stop_loss_point = np.nan
    # 卖出逻辑和加仓逻辑
    if i in stock_hold_now:
        # 是否需要止损
        if price<stop_loss_point and context.portfolio.positions[sid].amount>0 and data.can_trade(sid):
            order_target_value(sid, 0)
            context.unit_remark[i] = 0
        # 是否需要出场  
        if price<low_point and context.portfolio.positions[sid].amount>0 and data.can_trade(sid):
            order_target_value(sid, 0)   
            context.unit_remark[i] = 0
        # 是否需要加仓,超过4 unit就不加仓了
        if price>add_pos_point and context.portfolio.positions[sid].amount>0 and data.can_trade(sid) and context.unit_remark[i]<4:
            order(sid, a_unit)
            context.unit_remark[i] = context.unit_remark[i]+1
    else:
        pass
    # 买入逻辑
    if price>high_point and context.portfolio.positions[sid].amount==0 and data.can_trade(sid):
        order(sid, a_unit)
        context.unit_remark[i] = 1
    else:
        pass

回测引擎:准备数据,只执行一次

def m3_prepare_bigquant_run(context):
pass

回测引擎:初始化函数,只执行一次

def m3_initialize_bigquant_run(context):

context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
context.entry_pos_period = 55
context.exit_pos_period = 20
context.unit_remark = {}
context.atr_data = context.options['data'].read_df()
context.instruments = m1.data.read_pickle()['instruments']

回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。

def m3_before_trading_start_bigquant_run(context, data):
pass

m3 = M.trade.v3(
instruments=m1.data,
options_data=m2.data_1,
start_date=’’,
end_date=’’,
handle_data=m3_handle_data_bigquant_run,
prepare=m3_prepare_bigquant_run,
initialize=m3_initialize_bigquant_run,
before_trading_start=m3_before_trading_start_bigquant_run,
volume_limit=0,
order_price_field_buy=‘open’,
order_price_field_sell=‘open’,
capital_base=10000000,
benchmark=‘HSI.HKEX’,
auto_cancel_non_tradable_orders=True,
data_frequency=‘daily’,
price_type=‘后复权’,
plot_charts=True,
backtest_only=False,
amount_integer=False
)


(wwwburoka) #2

日誌會出現000300.SHA 的字樣, 但我代碼中已把benchmark 都改為HSI.HKEX了

[2018-05-24 03:33:19.681805] INFO: bigquant: instruments.v2 开始运行…
[2018-05-24 03:33:19.686747] INFO: bigquant: 命中缓存
[2018-05-24 03:33:19.687699] INFO: bigquant: instruments.v2 运行完成[0.005908s].
[2018-05-24 03:33:19.701324] INFO: bigquant: cached.v3 开始运行…
[2018-05-24 03:33:19.703781] INFO: bigquant: 命中缓存
[2018-05-24 03:33:19.704831] INFO: bigquant: cached.v3 运行完成[0.003512s].
[2018-05-24 03:33:19.990458] INFO: forward_register: start to register
[2018-05-24 03:33:20.047537] INFO: forward_register: done of register
[2018-05-24 03:33:20.659510] INFO: forward_test: last record: <EquityAlgoDaily(run_date=2018-05-22, is_sync=0, cash=10000000.0, positions=’[]’, transactions=’[]’, orders=’[]’, extension=’{“order_price_field_buy”: “open”, “order_price_field_sell”: “open”}’, benchmark=’{“000300.SHA”: -0.0038340091705322266}’, portfolio=’{“max_pv”: 10000000.0, “pv”: 0.0, “drawdown”: 0.0, “annual_return”: 0.0, “first_date”: “2018-05-18”, “cum_return”: 0.0, “today_return”: 0.0}’, risk_indicator=’{“volatility”: 0.0, “ir”: 11.242169550657904, “alpha”: -0.03, “sharpe”: 0.0, “beta”: 0.0}’, trading_days=‘3’
[2018-05-24 03:33:20.673082] INFO: forward_test: today record: <EquityAlgoDaily(run_date=2018-05-23, is_sync=0, cash=10000000.0, positions=’[]’, transactions=’[]’, orders=’[]’, extension=’{“order_price_field_buy”: “open”, “order_price_field_sell”: “open”}’, benchmark=’{“000300.SHA.CUM”: -0.01242130994796753, “000300.SHA”: -0.013216257095336914}’, portfolio=’{“first_date”: “2018-05-18”, “max_pv”: 10000000.0, “annual_return”: 0.0, “drawdown”: 0.0, “today_return”: 0.0, “cum_return”: 0.0, “pv”: 0.0}’, risk_indicator=’{“alpha”: -0.03, “sharpe”: 0.0, “volatility”: 0.0, “ir”: 20.43082350175817, “beta”: 0.0}’, trading_days=‘4’
[2018-05-24 03:33:20.678374] INFO: forward_test: first record: <EquityAlgoDaily(run_date=2018-05-18, is_sync=0, cash=10000000.0, positions=’[]’, transactions=’[]’, orders=’[]’, extension=’{“order_price_field_buy”: “open”, “order_price_field_sell”: “open”}’, benchmark=’{“000300.SHA”: 0.010096430778503418}’, portfolio=’{“pv”: 0.0, “drawdown”: 0.0, “first_date”: “2018-05-18”, “annual_return”: 0.0, “max_pv”: 10000000.0, “cum_return”: 0.0, “today_return”: 0.0}’, risk_indicator=’{“alpha”: 0.0, “ir”: 0.0, “sharpe”: 0.0, “volatility”: 0.0, “beta”: 0.0}’, trading_days=‘1’
[2018-05-24 03:33:20.850520] INFO: algo: set price type:backward_adjusted
[2018-05-24 03:33:23.643786] INFO: forward_test: positions len:0
[2018-05-24 03:33:24.730240] INFO: Performance: Simulated 1 trading days out of 1.
[2018-05-24 03:33:24.731812] INFO: Performance: first open: 2018-05-23 01:30:00+00:00
[2018-05-24 03:33:24.732808] INFO: Performance: last close: 2018-05-23 07:00:00+00:00
[2018-05-24 03:33:24.756564] INFO: forward_test: get last row of algo result: algo_volatility algorithm_period_return alpha
2018-05-23 07:00:00+00:00 0 0.0 0

                       benchmark_period_return  benchmark_volatility  \

2018-05-23 07:00:00+00:00 -0.013216 0

                       beta  capital_used  ending_cash  ending_exposure  \

2018-05-23 07:00:00+00:00 0 0.0 10000000.0 0.0

                       ending_value          ...            \

2018-05-23 07:00:00+00:00 0.0 …

                       short_exposure  short_value  shorts_count  sortino  \

2018-05-23 07:00:00+00:00 0 0 0 0

                       starting_cash  starting_exposure  starting_value  \

2018-05-23 07:00:00+00:00 10000000.0 0.0 0.0

                       trading_days  transactions treasury_period_return  

2018-05-23 07:00:00+00:00 1 [] 0.044297

[1 rows x 38 columns]
cum_return:0.0, current_sharpe: 0.0, annual_return: 0.0, max_drawdown: 0.0
cum_return_plot: 4, before_shared_cum_return_plot: 0, after_shared_cum_return_plot: 0, benchmark_cum_return_plot: 4, hold_percent_plot: 4
[2018-05-24 03:33:24.816002] INFO: forward_test: new orders for date 2018-05-23
No display for HTML output
[2018-05-24 03:33:24.864579] INFO: forward_test: forward test result, cash 10000000.0, positions [], orders [], extension


(达达) #3

这个模拟交易暂时还不支持~