Beispiel #1
1
def test(detail):
    def get_first_n_lines(string, n):
        lines = string.splitlines()
        n = min(n, len(lines))
        return '\n'.join(lines[:n])

    #gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_SAVEALL)
    start_time = time.time()
    with codecs.open('../test/testcode7.py', 'r', 'utf-8') as f:
        code = f.read()
    user = User('10032')
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-01', '2016-01-01')
    print(backtest.progress)
    for _ in range(4):
        backtest.start()
        print(backtest.get_performance().trade_summary)
    if detail:
        translator = DataframeTranslator()
        user_dir = UserDirectory(user)
        print(user_dir.get_sys_func_list())
        print(backtest.get_profit_records())  # 获取浮动收益曲线
        print(backtest.get_parameters())  # 获取策略中的参数(用于优化)
        performance = backtest.get_performance()  # 获取策略的各项指标
        print('trade_info:\n%s' % performance._manager.trade_info)
        print('trade_summary:\n%s' % performance.trade_summary)
        print('trade_details:\n%s' % performance.trade_details)
        print(translator.dumps(performance._manager.trade_info))
        print(translator.dumps(performance.trade_details))
        print('strategy_summary:\n%s' % performance.strategy_summary)
        print('optimize_info:\n%s' % performance.optimize_info)
        print('info_on_home_page\n%s' % performance.get_info_on_home_page())
        print(performance.get_factor_list())
        # print(performance.yield_curve)
        print('ar:\n%s' % performance.ar)  # 年化收益率
        print('risk_free_rate:\n%s' % performance._manager.risk_free_rate)  # 无风险收益率
        print('volatility:\n%s' % performance.volatility)  # 波动率
        print('sharpe_ratio:\n%s' % performance.sharpe_ratio)  # sharpe比率
        print('max_drawdown:\n%s' % performance.max_drawdown)  # 最大回测
        print('trade_position\n%s' % performance.trade_positions)  # 交易仓位
        print(time.time() - start_time)
        # print('output:\n%s' % get_first_n_lines(backtest.get_output(), 100))
        print(time.time() - start_time)
        print(backtest.progress)
    paras = {'handle': {'times': {'start': 10, 'end': 10, 'step': 1}}}
    optimize = backtest.optimize(paras, None, None)
    print('optimize\n%s' % optimize)
    print(time.time() - start_time)
    del backtest
    performance = None
    optimize = None
Beispiel #2
0
def run_backest(kwargs):
    try:
        file = kwargs.pop('code')
        with codecs.open(file, 'r', 'utf-8') as f:
            code = f.read()
            f.close()
        user = '******'
        parameters = kwargs.pop('paras')
        start_time = kwargs.pop('start_time')
        end_time = kwargs.pop('end_time')
        symbol = kwargs.pop('symbol')
        time_frame = kwargs.pop('time_frame')
        log = kwargs.pop('log')
        backtest = Backtesting(user, 'test', code, [symbol], time_frame, start_time, end_time)
        if log:
            handle = logging.FileHandler(log, encoding='utf-8')
            logger = logging.getLogger('backtest')
            logger.addHandler(handle)
            logger.setLevel(logging.INFO)
            backtest.set_logger(logger)
        backtest.start(paras=parameters)
        performance = backtest.get_performance()
        result = performance.optimize_info
        temp = pd.Series({signal + '.' + k: v for signal, paras in parameters.items() for k, v in paras.items()})
        result = pd.concat([temp, result])
        backtest.log(backtest.time("绩效计算完毕,耗时:{0}"), logging.INFO)
        return result
    except Exception as e:
        print("Error: {0}, Para: {1}".format(e, parameters))
        print(traceback.format_exc())
        return None
Beispiel #3
0
def run_backest(**parameters):
    with codecs.open('../test/testcode9.py', 'r', 'utf-8') as f:
        code = f.read()
    user = User('10032')
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-02', '2015-03-01')
    backtest.start(paras=parameters)
    performance = backtest.get_performance()
    print(performance.trade_summary)
Beispiel #4
0
def run_backest(**parameters):
    with codecs.open("../test/testcode9.py", "r", "utf-8") as f:
        code = f.read()
    user = User("10032")
    backtest = Backtesting(user, "test", code, ["EURUSD"], "M30", "2015-01-02", "2015-03-01")
    backtest.start(paras=parameters)
    performance = backtest.get_performance()
    print(performance.trade_summary)
Beispiel #5
0
def run_backest(**parameters):
    with codecs.open('../test/testcode9.py', 'r', 'utf-8') as f:
        code = f.read()
    user = User('10032')
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-02',
                           '2015-03-01')
    backtest.start(paras=parameters)
    performance = backtest.get_performance()
    print(performance.trade_summary)
Beispiel #6
0
def get_para(file, out=None):
    with codecs.open(file, 'r', 'utf-8') as f:
        code = f.read()
        f.close()
    user = '******'
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-01', '2015-01-02')
    backtest.init()
    result = backtest.get_parameters()
    if out:
        with codecs.open(out, 'w', 'utf-8') as f:
            f.write(json.dumps(result))
        f.close()
    else:
        print(json.dumps(result))
Beispiel #7
0
def run_backtest(file, config):
    cache = StrategyPerformanceJsonCache(user)  # TODO 修改为JSON
    try:
        with codecs.open(file, 'r', 'utf-8') as f:
            code = f.read()
            f.close()
        backtesting = Backtesting(**config)
        backtesting.set_code(code)
        backtesting.start()
        performance = backtesting.get_performance()
        cache.put_performance(performance)
        cache.put('setting', json.dumps(backtesting.get_setting()))  # TODO 修改为JSON
        output = get_output(user, name)
        result = {'stat': 'OK', 'result': performance.yield_curve,
                  'performance': performance.info_on_home_page}
    except SlaverThreadError as e:
        tb_message = get_user_friendly_traceback(*e.get_exc())
        result = {"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))}
    except Exception:
        tb_message = get_user_friendly_traceback(*sys.exc_info())
        result = {"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))}
    finally:
        output = get_output(user, name)
        result['output'] = string_to_html(output)
        cache.put('response', json.dumps(result))
Beispiel #8
0
def backtest(conn, *args):
    try:
        user = args[0]
        backtesting = Backtesting(*args)
        backtesting.start()
        performance = backtesting.get_performance()
        cache = StrategyPerformanceJsonCache(user)
        cache.put_performance(performance)
        cache.put('setting', json.dumps(backtesting.get_setting()))
        conn.put({"stat": "OK"})
    except SlaverThreadError as e:
        tb_message = get_user_friendly_traceback(*e.get_exc())
        conn.put({"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))})
    except Exception:
        tb_message = get_user_friendly_traceback(*sys.exc_info())
        conn.put({"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))})
Beispiel #9
0
def test(detail):
    def get_first_n_lines(string, n):
        lines = string.splitlines()
        n = min(n, len(lines))
        return '\n'.join(lines[:n])

    #gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_SAVEALL)
    start_time = time.time()
    with codecs.open('../test/testcode7.py', 'r', 'utf-8') as f:
        code = f.read()
    user = User('10032')
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-01',
                           '2016-01-01')
    print(backtest.progress)
    for _ in range(4):
        backtest.start()
        print(backtest.get_performance().trade_summary)
    if detail:
        translator = DataframeTranslator()
        user_dir = UserDirectory(user)
        print(user_dir.get_sys_func_list())
        print(backtest.get_profit_records())  # 获取浮动收益曲线
        print(backtest.get_parameters())  # 获取策略中的参数(用于优化)
        performance = backtest.get_performance()  # 获取策略的各项指标
        print('trade_info:\n%s' % performance._manager.trade_info)
        print('trade_summary:\n%s' % performance.trade_summary)
        print('trade_details:\n%s' % performance.trade_details)
        print(translator.dumps(performance._manager.trade_info))
        print(translator.dumps(performance.trade_details))
        print('strategy_summary:\n%s' % performance.strategy_summary)
        print('optimize_info:\n%s' % performance.optimize_info)
        print('info_on_home_page\n%s' % performance.get_info_on_home_page())
        print(performance.get_factor_list())
        # print(performance.yield_curve)
        print('ar:\n%s' % performance.ar)  # 年化收益率
        print('risk_free_rate:\n%s' %
              performance._manager.risk_free_rate)  # 无风险收益率
        print('volatility:\n%s' % performance.volatility)  # 波动率
        print('sharpe_ratio:\n%s' % performance.sharpe_ratio)  # sharpe比率
        print('max_drawdown:\n%s' % performance.max_drawdown)  # 最大回测
        print('trade_position\n%s' % performance.trade_positions)  # 交易仓位
        print(time.time() - start_time)
        # print('output:\n%s' % get_first_n_lines(backtest.get_output(), 100))
        print(time.time() - start_time)
        print(backtest.progress)
    paras = {'handle': {'times': {'start': 10, 'end': 10, 'step': 1}}}
    optimize = backtest.optimize(paras, None, None)
    print('optimize\n%s' % optimize)
    print(time.time() - start_time)
    del backtest
    performance = None
    optimize = None
Beispiel #10
0
def run_backest(**parameters):
    with codecs.open('../test/testcode9.py', 'r', 'utf-8') as f:
        code = f.read()
    user = '******'
    backtest = Backtesting(user, 'test', code, ['EURUSD'], 'M30', '2015-01-02', '2015-03-01')
    backtest.start(paras=parameters)
    performance = backtest.get_performance()
    result = performance.optimize_info
    temp = pd.Series({signal + '.' + k: v for signal, paras in parameters.items() for k, v in paras.items()})
    result = pd.concat([temp, result])
    backtest.log(backtest.time("绩效计算完毕,耗时:{0}"), logging.INFO)
    return result
Beispiel #11
0
def run_backtest(user, name, file, symbols, time_frame, start_time, end_time, commission, slippage):
    cache = StrategyPerformanceJsonCache(user)  # TODO 修改为JSON
    try:
        with codecs.open(file, 'r', 'utf-8') as f:
            code = f.read()
            f.close()
        backtesting = Backtesting(user, name, code, symbols, time_frame, start_time, end_time, commission, slippage)
        backtesting.start()
        performance = backtesting.get_performance()
        cache.put_performance(performance)
        cache.put('setting', json.dumps(backtesting.get_setting()))  # TODO 修改为JSON
        output = get_output(user, name)
        result = {'stat': 'OK', 'result': performance.yield_curve,
                  'performance': performance.info_on_home_page}
    except SlaverThreadError as e:
        tb_message = get_user_friendly_traceback(*e.get_exc())
        result = {"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))}
    except Exception:
        tb_message = get_user_friendly_traceback(*sys.exc_info())
        result = {"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))}
    finally:
        output = get_output(user, name)
        result['output'] = string_to_html(output)
        cache.put('response', json.dumps(result))
Beispiel #12
0
def backtest(conn, *args):
    try:

        config = BfConfig(**{v[0]: v[1] for v in zip(["user", "name", "symbols", "time_frame", "start_time",
                                                      "end_time", "commission", "slippage"], args)})
        config.trading_mode = TradingMode.on_tick
        user = User(config.user)
        code = get_strategy(user, "LastBacktest").content
        backtesting = Backtesting()
        backtesting.set_code(code)
        backtesting.set_config(config)
        backtesting.start()
        performance = backtesting.get_performance()
        cache = StrategyPerformanceJsonCache(user.user_id)
        cache.put_performance(performance)
        cache.put('setting', json.dumps(backtesting.get_setting()))
        conn.put({"stat": "OK"})
    except SlaverThreadError as e:
        tb_message = get_user_friendly_traceback(*e.get_exc())
        conn.put({"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))})
    except Exception:
        tb_message = get_user_friendly_traceback(*sys.exc_info())
        conn.put({"stat": "FALSE", "error": string_to_html('\n'.join(tb_message))})