Ejemplo n.º 1
0
def test_context():
    r = random.random()
    path = '../../output/tests/storage{:.6f}.pic'.format(r)
    context = model.Context()
    context.load_store(path)
    assert len(context.storage) == 0
    context.storage['me'] = 1.0
    context.save_store(path)
    
    context = model.Context()
    context.load_store(path)
    assert context.storage['me'] == 1.0
Ejemplo n.º 2
0
def test_livetrade():
    props = {'symbol': 'rb1801.SHF', 'strategy_no': 46}
    tapi = RealTimeTradeApi(trade_config)
    ins = EventLiveTradeInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = DoubleMaStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds,
                            trade_api=tapi,
                            instance=ins,
                            strategy=strat,
                            pm=pm)

    ins.init_from_config(props)
    ds.subscribe(props['symbol'])

    ins.run()
    time.sleep(3)
    ins.stop()
    ins.save_results(result_dir_path)
    do_analyze()
Ejemplo n.º 3
0
def run_strategy():
    """
                    回测模式
    """
    props = {"symbol": '510300.SH',
             "start_date": 20160201,
             "end_date": 20171231,
             "fast_ma_length": 10,
             "slow_ma_length": 20,
             "bar_type": "1d",
             "benchmark" : '000300.SH',
             "init_balance": 50000}

    tapi = BacktestTradeApi()
    ins = EventBacktestInstance()
        
    props.update(data_config)
    props.update(trade_config)
    
    ds = RemoteDataService()
    strat = DoubleMaStrategy()
    pm = PortfolioManager()
    
    context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
                            strategy=strat, pm=pm)
    
    ins.init_from_config(props)

    ins.run()

    ins.save_results(folder_path=result_dir_path)
Ejemplo n.º 4
0
def do_livetrade():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_store_folder)

    props = {"period": "day", "strategy_no": 1044, "init_balance": 1e6}
    props.update(data_config)
    props.update(trade_config)

    strategy = AlphaStrategy(pc_method='market_value_weight')
    pm = PortfolioManager()

    bt = AlphaLiveTradeInstance()
    trade_api = RealTimeTradeApi(props)
    ds = RemoteDataService()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm,
                            data_api=ds)

    bt.init_from_config(props)
    bt.run_alpha()

    goal_positions = strategy.goal_positions
    print("Length of goal positions:", len(goal_positions))
    task_id, msg = trade_api.goal_portfolio(goal_positions)
    print(task_id, msg)
Ejemplo n.º 5
0
def do_backtest():
    # Load local data file that we just stored.
    dv = DataView()
    dv.load_dataview(folder_path=dataview_store_folder)

    backtest_props = {
        "start_date": dv.start_date,  # start and end date of back-test
        "end_date": dv.end_date,
        "period": "month",  # re-balance period length
        "benchmark": dv.benchmark,  # benchmark and universe
        "universe": dv.universe,
        "init_balance": 1e8,  # Amount of money at the start of back-test
        "position_ratio": 1.0,  # Amount of money at the start of back-test
    }
    backtest_props.update(data_config)
    backtest_props.update(trade_config)

    # Create model context using AlphaTradeApi, AlphaStrategy, PortfolioManager and AlphaBacktestInstance.
    # We can store anything, e.g., public variables in context.

    trade_api = AlphaTradeApi()
    strategy = AlphaStrategy(pc_method='market_value_weight')
    pm = PortfolioManager()
    bt = AlphaBacktestInstance()
    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)

    bt.init_from_config(backtest_props)
    bt.run_alpha()

    # After finishing back-test, we save trade results into a folder
    bt.save_results(folder_path=backtest_result_folder)
Ejemplo n.º 6
0
def test_backtest():
    props = {
        "symbol": "rb1710.SHF",
        "start_date": 20170710,
        "end_date": 20170730,
        "bar_type": "1M",  # '1d'
        "init_balance": 2e4
    }

    tapi = BacktestTradeApi()
    ins = EventBacktestInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = DoubleMaStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds,
                            trade_api=tapi,
                            instance=ins,
                            strategy=strat,
                            pm=pm)

    ins.init_from_config(props)

    ins.run()
    ins.save_results(result_dir_path)
    do_analyze()
Ejemplo n.º 7
0
def test_double_ma():
    prop_file_path = fileio.join_relative_path("etc/backtest.json")
    print prop_file_path
    prop_file = open(prop_file_path, 'r')
    
    props = json.load(prop_file)
    
    enum_props = {'bar_type': common.QUOTE_TYPE}
    for k, v in enum_props.iteritems():
        props[k] = v.to_enum(props[k])
    
    # strategy   = CtaStrategy()
    strategy = DoubleMaStrategy()
    gateway = BarSimulatorGateway()
    data_service = RemoteDataService()

    context = model.Context()
    context.register_data_api(data_service)
    context.register_gateway(gateway)
    context.register_trade_api(gateway)
    
    backtest = EventBacktestInstance()
    backtest.init_from_config(props, strategy, context=context)
    
    # trade.run()
    backtest.run()
    report = backtest.generate_report(output_format="")
Ejemplo n.º 8
0
def run_strategy():
    '''
    universe可以自己定义吗,就是从我筛选的一组股票里面挑选
    把universe改成symbol,然后值设置成一系列代码的字符串,用逗号隔开
    :return:
    '''
    if is_backtest:
        """
        回测模式
        """
        props = {
            "symbol": '600519.SH',
            # "symbol": '002050.SZ',
            # "benchmark": '002050.SZ',
            "benchmark": '000300.SH',
            "start_date": 20170101,
            "end_date": 20171219,
            "fast_ma_length": 3,
            "slow_ma_length": 8,
            "live_ma_length": 34,
            "bar_type": "1d",  # '1d'
            "init_balance": 50000}

        tapi = BacktestTradeApi()
        ins = EventBacktestInstance()

    else:
        """
        实盘/仿真模式
        """
        props = {'symbol': '600519.SH',
                 "fast_ma_length": 3,
                 "slow_ma_length": 5,
                 "live_ma_length": 34,
                 'strategy.no': 1062}
        tapi = RealTimeTradeApi(trade_config)
        ins = EventLiveTradeInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = TripleMaStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
                            strategy=strat, pm=pm)

    ins.init_from_config(props)
    if not is_backtest:
        ds.subscribe(props['symbol'])

    ins.run()
    if not is_backtest:
        time.sleep(9999)
    ins.save_results(folder_path=result_dir_path)
Ejemplo n.º 9
0
def test_alpha_strategy_dataview():
    dv_subfolder_name = 'test_dataview'
    save_dataview(sub_folder=dv_subfolder_name)

    dv = DataView()

    fullpath = fileio.join_relative_path('../output/prepared',
                                         dv_subfolder_name)
    dv.load_dataview(folder=fullpath)

    props = {
        "benchmark": "000300.SH",
        # "symbol": ','.join(dv.symbol),
        "universe": ','.join(dv.symbol),
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        "period": "month",
        "days_delay": 0,
        "init_balance": 1e9,
        "position_ratio": 0.7,
    }

    gateway = DailyStockSimGateway()
    gateway.init_from_config(props)

    context = model.Context()
    context.register_gateway(gateway)
    context.register_trade_api(gateway)
    context.register_dataview(dv)

    risk_model = model.FactorRiskModel()
    signal_model = model.FactorRevenueModel_dv()
    cost_model = model.SimpleCostModel()

    risk_model.register_context(context)
    signal_model.register_context(context)
    cost_model.register_context(context)

    signal_model.register_func('my_factor', my_factor)
    signal_model.activate_func({'my_factor': {}})
    cost_model.register_func('my_commission', my_commission)
    cost_model.activate_func({'my_commission': {'myrate': 1e-2}})

    strategy = DemoAlphaStrategy(risk_model, signal_model, cost_model)
    # strategy.active_pc_method = 'equal_weight'
    # strategy.active_pc_method = 'mc'
    strategy.active_pc_method = 'factor_value_weight'

    bt = AlphaBacktestInstance_dv()
    bt.init_from_config(props, strategy, context=context)

    bt.run_alpha()

    bt.save_results(fileio.join_relative_path('../output/'))
Ejemplo n.º 10
0
def test_alpha_strategy_dataview():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_dir_path)
    
    props = {
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        
        "period": "week",
        "days_delay": 0,
        
        "init_balance": 1e8,
        "position_ratio": 1.0,
    }
    
    gateway = AlphaTradeApi()
    gateway.init_from_config(props)
    
    context = model.Context(dataview=dv, gateway=gateway)
    
    stock_selector = model.StockSelector()
    stock_selector.add_filter(name='myselector', func=my_selector)
    
    signal_model = model.FactorRevenueModel()
    signal_model.add_signal(name='signalsize', func=signal_size)
    
    strategy = AlphaStrategy(stock_selector=stock_selector, pc_method='factor_value_weight',
                             revenue_model=signal_model)
    pm = PortfolioManager()
    
    bt = AlphaBacktestInstance()
    context = model.Context(dataview=dv, instance=bt, strategy=strategy, trade_api=trade_api, pm=pm)
    
    for mdl in [signal_model, stock_selector]:
        mdl.register_context(context)
    
    bt.init_from_config(props)
    bt.run_alpha()
    
    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 11
0
def run_strategy():
    if is_backtest:
        """
        回测模式
        """
        props = {
            "symbol": '600519.SH',
            "start_date": 20170101,
            "end_date": 20171104,
            "fast_ma_length": 5,
            "slow_ma_length": 15,
            "bar_type": "1d",  # '1d'
            "init_balance": 50000
        }

        tapi = BacktestTradeApi()
        ins = EventBacktestInstance()

    else:
        """
        实盘/仿真模式
        """
        props = {
            'symbol': '600519.SH',
            "fast_ma_length": 5,
            "slow_ma_length": 15,
            'strategy.no': 1062
        }
        tapi = RealTimeTradeApi(trade_config)
        ins = EventLiveTradeInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = DoubleMaStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds,
                            trade_api=tapi,
                            instance=ins,
                            strategy=strat,
                            pm=pm)

    ins.init_from_config(props)
    if not is_backtest:
        ds.subscribe(props['symbol'])

    ins.run()
    if not is_backtest:
        time.sleep(9999)
    ins.save_results(folder_path=result_dir_path)
Ejemplo n.º 12
0
def test_alpha_strategy_dataview():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "benchmark": "000300.SH",
        "universe": ','.join(dv.symbol),
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        "period": "month",
        "days_delay": 0,
        "init_balance": 1e8,
        "position_ratio": 1.0,
    }

    trade_api = AlphaTradeApi()

    context = model.Context(dataview=dv, gateway=trade_api)

    stock_selector = model.StockSelector(context)
    stock_selector.add_filter(name='myrank', func=my_selector)

    strategy = AlphaStrategy(stock_selector=stock_selector,
                             pc_method='equal_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)
    stock_selector.register_context(context)

    bt.init_from_config(props)
    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 13
0
def run_strategy():

    start_date = 20150501
    end_date = 20171030
    index = '399975.SZ'

    ds = RemoteDataService()
    ds.init_from_config(data_config)
    symbol_list = ds.get_index_comp(index, start_date, start_date)

    # add the benchmark index to the last position of symbol_list
    symbol_list.append(index)
    props = {
        "symbol": ','.join(symbol_list),
        "start_date": start_date,
        "end_date": end_date,
        "bar_type": "1d",
        "init_balance": 1e7,
        "std multiplier": 1.5,
        "m": 10,
        "n": 60,
        "commission_rate": 2E-4
    }
    props.update(data_config)
    props.update(trade_config)

    tapi = BacktestTradeApi()
    ins = EventBacktestInstance()

    strat = SectorRolling()
    pm = PortfolioManager()

    context = model.Context(data_api=ds,
                            trade_api=tapi,
                            instance=ins,
                            strategy=strat,
                            pm=pm)

    ins.init_from_config(props)
    ins.run()
    ins.save_results(folder_path=result_dir_path)

    ta = ana.EventAnalyzer()

    ta.initialize(data_server_=ds, file_folder=result_dir_path)
    df_bench, _ = ds.daily(index, start_date=start_date, end_date=end_date)
    ta.data_benchmark = df_bench.set_index('trade_date').loc[:, ['close']]

    ta.do_analyze(result_dir=result_dir_path,
                  selected_sec=props['symbol'].split(',')[:2])
Ejemplo n.º 14
0
def run_strategy():
    tapi = BacktestTradeApi()
    ins = EventBacktestInstance()

    ds = RemoteDataService()
    strat = DualThrust()
    pm = PortfolioManager()

    context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
                            strategy=strat, pm=pm)

    ins.init_from_config(props)
    ins.run()
    ins.save_results(folder_path=result_dir_path)
Ejemplo n.º 15
0
def test_alpha_strategy_dataview():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "benchmark": BENCHMARK,
        "universe": ','.join(dv.symbol),
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        "period": "day",
        "days_delay": 0,
        "init_balance": 1e8,
        "position_ratio": 1.0,
        "strategy_no": 44
    }
    props.update(data_config)
    props.update(trade_config)

    stock_selector = model.StockSelector()
    stock_selector.add_filter(name='rank_ret_top10', func=my_selector)

    strategy = AlphaStrategy(stock_selector=stock_selector,
                             pc_method='equal_weight')
    pm = PortfolioManager()

    if is_backtest:
        bt = AlphaBacktestInstance()
        trade_api = AlphaTradeApi()
        ds = None
    else:
        bt = AlphaLiveTradeInstance()
        trade_api = RealTimeTradeApi(props)
        ds = RemoteDataService()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm,
                            data_api=ds)
    stock_selector.register_context(context)

    bt.init_from_config(props)
    bt.run_alpha()

    if is_backtest:
        bt.save_results(folder_path=backtest_result_dir_path)
    else:
        goal_positions = strategy.goal_positions
        print(goal_positions)
def test_alpha_strategy_dataview():
    dv = DataView()

    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "benchmark": "000300.SH",
        "universe": ','.join(dv.symbol),
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        "period": "month",
        "days_delay": 0,
        "init_balance": 1e8,
        "position_ratio": 1.0,
    }
    props.update(data_config)
    props.update(trade_config)

    trade_api = AlphaTradeApi()
    trade_api.init_from_config(props)

    def selector_growth(context, user_options=None):
        growth_rate = context.snapshot['net_profit_growth']
        return (growth_rate >= 0.2) & (growth_rate <= 4)

    def selector_pe(context, user_options=None):
        pe_ttm = context.snapshot['pe_ttm']
        return (pe_ttm >= 5) & (pe_ttm <= 80)

    stock_selector = model.StockSelector()
    stock_selector.add_filter(name='net_profit_growth', func=selector_growth)
    stock_selector.add_filter(name='pe', func=selector_pe)

    strategy = AlphaStrategy(stock_selector=stock_selector,
                             pc_method='equal_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)
    stock_selector.register_context(context)

    bt.init_from_config(props)
    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 17
0
def test_alpha_strategy_dataview():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_dir_path)
    #回测参数选择
    props = {
        "benchmark": "000905.SH",
        "universe": ','.join(dv.symbol),
        "start_date": 20170605,
        "end_date": 20180807,
        "period": "day",
        "days_delay": 0,
        "init_balance": 1e9,
        "position_ratio": 1.0,
        "commission_rate": 0.0015,  #手续费
        "n_periods": 2
    }
    props.update(data_config)
    props.update(trade_config)

    trade_api = AlphaTradeApi()

    signal_model = model.FactorSignalModel()
    #添加信号
    signal_model.add_signal('alpha3', alpha)  #在使用新因子时,alpha3应改为新因子的名称
    stock_selector = model.StockSelector()
    stock_selector.add_filter(name='myselector', func=my_selector)

    strategy = AlphaStrategy(stock_selector=stock_selector,
                             signal_model=signal_model,
                             pc_method='factor_value_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)

    for mdl in [signal_model, stock_selector]:
        mdl.register_context(context)

    bt.init_from_config(props)

    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 18
0
def test_alpha_strategy_dataview():
    dv = DataView()

    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "benchmark": "000300.SH",
        "universe": ','.join(dv.symbol),
        "start_date": 20170131,
        "end_date": dv.end_date,
        "period": "month",
        "days_delay": 0,
        "init_balance": 1e9,
        "position_ratio": 1.0,
    }
    props.update(data_config)
    props.update(trade_config)

    trade_api = AlphaTradeApi()

    def singal_gq30(context, user_options=None):
        import numpy as np
        res = np.power(context.snapshot['gq30'], 8)
        return res

    signal_model = model.FactorSignalModel()
    signal_model.add_signal('signal_gq30', singal_gq30)

    strategy = AlphaStrategy(signal_model=signal_model,
                             pc_method='factor_value_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)

    signal_model.register_context(context)

    bt.init_from_config(props)

    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 19
0
def run_strategy():
    dv = EventDataView()
    dv.load_dataview(dataview_dir_path)
    
    tapi = BacktestTradeApi()
    ins = EventBacktestInstance()
    
    strat = DoubleMaStrategy()
    pm = PortfolioManager()
    
    context = model.Context(dataview=dv, # data_api=ds,
                            trade_api=tapi, instance=ins,
                            strategy=strat, pm=pm)
    
    ins.init_from_config(backtest_props)
    ins.run()
    ins.save_results(folder_path=result_dir_path)
def do_backtest():
    # Load local data file that we just stored.
    dv = DataView()
    dv.load_dataview(folder_path=dataview_store_folder)

    backtest_props = {# start and end date of back-test
                      "start_date": dv.start_date,
                      "end_date": dv.end_date,
                      # re-balance period length
                      "period": "month",
                      # benchmark and universe
                      "benchmark": dv.benchmark,
                      "universe": dv.universe,
                      # Amount of money at the start of back-test
                      "init_balance": 1e8,
                      # Amount of money at the start of back-test
                      "position_ratio": 1.0,
                      }
    backtest_props.update(data_config)
    backtest_props.update(trade_config)

    # We use trade_api to send orders
    trade_api = AlphaTradeApi()
    # This is our strategy
    strategy = AlphaStrategy(pc_method='market_value_weight')
    # PortfolioManager helps us to manage tasks, orders and calculate positions
    pm = PortfolioManager()
    # BacktestInstance is in charge of running the back-test
    bt = AlphaBacktestInstance()

    # Public variables are stored in context. We can also store anything in it
    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)

    bt.init_from_config(backtest_props)
    bt.run_alpha()

    # After finishing back-test, we save trade results into a folder
    bt.save_results(folder_path=backtest_result_folder)
Ejemplo n.º 21
0
def test_alpha_strategy_dataview():
    dv = DataView()

    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "symbol": dv.symbol,
        "universe": ','.join(dv.symbol),

        "start_date": dv.start_date,
        "end_date": dv.end_date,

        "period": "week",
        "days_delay": 0,

        "init_balance": 1e7,
        "position_ratio": 1.0,
        "commission_rate": 2E-4  # 手续费万2
    }
    props.update(data_config)
    props.update(trade_config)

    trade_api = AlphaTradeApi()

    signal_model = model.FactorSignalModel()
    signal_model.add_signal('stockWeight', stockWeight)

    strategy = AlphaStrategy(signal_model=signal_model, pc_method='factor_value_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()
    
    context = model.Context(dataview=dv, instance=bt, strategy=strategy, trade_api=trade_api, pm=pm)
    
    signal_model.register_context(context)

    bt.init_from_config(props)

    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 22
0
def test_alpha_strategy_dataview():
    dv = DataView()

    dv.load_dataview(folder_path=dataview_dir_path)

    props = {
        "start_date": dv.start_date,
        "end_date": dv.end_date,
        "period": "week",
        "days_delay": 0,
        "init_balance": 1e8,
        "position_ratio": 1.0,
    }
    props.update(data_config)
    props.update(trade_config)

    trade_api = AlphaTradeApi()

    stock_selector = model.StockSelector()
    stock_selector.add_filter(name='myselector', func=my_selector)

    strategy = AlphaStrategy(stock_selector=stock_selector,
                             pc_method='equal_weight')
    pm = PortfolioManager()

    bt = AlphaBacktestInstance()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm)
    stock_selector.register_context(context)

    bt.init_from_config(props)

    bt.run_alpha()

    bt.save_results(folder_path=backtest_result_dir_path)
Ejemplo n.º 23
0
def run_strategy():
    if is_backtest:
        props = {
            "symbol": "rb1710.SHF",
            "start_date": 20170510,
            "end_date": 20170930,
            "bar_type": "1M",  # '1d'
            "init_balance": 2e4
        }

        tapi = BacktestTradeApi()
        ins = EventBacktestInstance()

    else:
        props = {'symbol': 'rb1801.SHF', 'strategy.no': 46}
        tapi = RealTimeTradeApi(trade_config)
        ins = EventLiveTradeInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = DoubleMaStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds,
                            trade_api=tapi,
                            instance=ins,
                            strategy=strat,
                            pm=pm)

    ins.init_from_config(props)
    if not is_backtest:
        ds.subscribe(props['symbol'])

    ins.run()
    if not is_backtest:
        time.sleep(9999)
    ins.save_results(folder_path=result_dir_path)
def do_livetrade():
    dv = DataView()
    dv.load_dataview(folder_path=dataview_store_folder)

    # print("total_mv", dv.get_ts('total_mv'))
    # print("float_mv", dv.get_ts('float_mv'))

    props = {"period": "day", "strategy_no": 1683, "init_balance": 1e6}
    props.update(data_config)
    props.update(trade_config)

    strategy = AlphaStrategy(pc_method='market_value_weight')
    pm = PortfolioManager()

    bt = AlphaLiveTradeInstance()
    trade_api = RealTimeTradeApi(props)
    ds = RemoteDataService()

    context = model.Context(dataview=dv,
                            instance=bt,
                            strategy=strategy,
                            trade_api=trade_api,
                            pm=pm,
                            data_api=ds)

    trade_api.set_ordstatus_callback(on_orderstatus)
    trade_api.set_trade_callback(on_trade)
    trade_api.set_task_callback(on_taskstatus)
    bt.init_from_config(props)
    bt.run_alpha()

    goal_positions = strategy.goal_positions
    # print("strategy.weights", strategy.weights)
    # print("Length of goal positions:", len(goal_positions))
    # print(goal_positions)
    task_id, msg = trade_api.goal_portfolio(goal_positions)
    print(task_id, msg)
Ejemplo n.º 25
0
Archivo: live.py Proyecto: gglive/JAQS
#
trade_api = RealTimeTradeApi({
    "remote.trade.address": "tcp://1.85.40.235:58086",
    "remote.trade.username": '******',
    #"remote.trade.address": "tcp://127.0.0.1:58086",
    #"remote.trade.username": "******",
    "remote.trade.password": "******"
})
trade_api.init_from_config({
    "remote.trade.address": "tcp://1.85.40.235:58086",
    "remote.trade.username": "******",
    #"remote.trade.address": "tcp://127.0.0.1:58086",
    #"remote.trade.username": "******",
    "remote.trade.password": "******"
})
context = model.Context(data_api=None, trade_api=trade_api, instance=None, strategy=None, pm=None)

#
for order in orders:
    if order['order_qty'] == 0:
        continue

    if order['order_place_method'] == "TWAP":
        offer_start_time = order['offer_start_time'].strftime("%H:%M:%S")
        offer_stop_time = order['offer_stop_time'].strftime("%H:%M:%S")
    elif order['order_place_method'] == "DMA":
        now  = datetime.now()
        _date = now.date()
        _time = now.time()
        _time = max ( _time, order['offer_start_time'] )
        offer_start_time = _time.strftime("%H:%M:%S")
Ejemplo n.º 26
0
def run_strategy():
    if is_backtest:
        """
        回测模式
        """

        ds = RemoteDataService()
        ds.init_from_config(data_config)
        symbol_list = ds.query_index_member(index, start_date, end_date)
        # symbol_list = ['600887.SH']
        # symbol_list = sample(symbol_list, 20)
        print(symbol_list)

        # add the benchmark index to the last position of symbol_list
        symbol_list.append(index)
        props = {"symbol": ','.join(symbol_list),
                 "holding_Count": 15,
                 "start_date": start_date,
                 "end_date": end_date,
                 "bar_type": "1d",  # '1d'
                 "init_balance": 300000,
                 "commission_rate": 2E-4}

        tapi = BacktestTradeApi()
        ins = EventBacktestInstance()

    else:
        """
        实盘/仿真模式
        """
        props = {'symbol': '600519.SH',
                 "fast_ma_length": 5,
                 "slow_ma_length": 15,
                 'strategy.no': 1062}
        tapi = RealTimeTradeApi(trade_config)
        ins = EventLiveTradeInstance()

    props.update(data_config)
    props.update(trade_config)

    ds = RemoteDataService()
    strat = RNNStrategy()
    pm = PortfolioManager()

    context = model.Context(data_api=ds, trade_api=tapi, instance=ins,
                            strategy=strat, pm=pm)

    ins.init_from_config(props)
    if not is_backtest:
        ds.subscribe(props['symbol'])

    ins.run()
    if not is_backtest:
        time.sleep(9999)
    ins.save_results(folder_path=result_dir_path)

    ta = ana.EventAnalyzer()

    ds = RemoteDataService()
    ds.init_from_config(data_config)

    ta.initialize(data_server_=ds, file_folder=result_dir_path)
    df_bench, _ = ds.daily(index, start_date=start_date, end_date=end_date)
    ta.data_benchmark = df_bench.set_index('trade_date').loc[:, ['close']]

    temp = pd.read_csv(result_dir_path + '/trades.csv')
    symbols = set(temp['symbol'].unique())
    print(symbols)

    ta.do_analyze(result_dir=result_dir_path, selected_sec=list(symbols))