示例#1
0
    def generate_setting(self):
        """"""
        self.optimization_setting = OptimizationSetting()

        self.target_display = self.target_combo.currentText()
        target_name = self.DISPLAY_NAME_MAP[self.target_display]
        self.optimization_setting.set_target(target_name)

        for name, d in self.edits.items():
            type_ = d["type"]
            start_value = type_(d["start"].text())
            step_value = type_(d["step"].text())
            end_value = type_(d["end"].text())

            if start_value == end_value:
                self.optimization_setting.add_parameter(name, start_value)
            else:
                self.optimization_setting.add_parameter(
                    name,
                    start_value,
                    end_value,
                    step_value
                )

        self.accept()
    def optimize_strategy(self, symbol: str, strategy, opt_params: List[Tuple], *, target_metric="sharpe_ratio",
                          alg='genetic'):
        engine = BacktestingEngine()
        engine.set_parameters(
            vt_symbol=symbol,
            interval=self._tf,
            start=self._from_date,
            end=self._to_date,
            rate=self._fee,
            slippage=self._slippage,
            size=self._size,
            pricetick=self._min_tick,
            capital=self._capital,
        )
        engine.add_strategy(strategy, {})
        setting = OptimizationSetting()
        setting.set_target(target_metric)
        for o in opt_params:
            setting.add_parameter(*o)

        if alg:
            results = engine.run_ga_optimization(setting)
        else:
            results = engine.run_optimization(setting)

        return results
示例#3
0
            "capital": 1_000_000,  # 资金分配需要动态调整
        }

        strategy_cls_list = [
                AtrRsiStrategy, BollChannelStrategy,
                AtrStrategy]
        for strategy_idx, strategy_cls in enumerate(strategy_cls_list):
            df = pb.run_backtesting(
                strategy_class=strategy_cls,
                setting={},
                vt_symbol=vt_symbol,
                bk_param_dict=bk_param_dict
            )
            pb.show_portafolio(df)

            setting = OptimizationSetting()
            setting.set_target("sharpe_ratio")
            op_params_list = pb.backtesting_engine.strategy.parameters

            setting.set_target("sharpe_ratio")
            setting.add_parameter(op_params_list[0], 3, 100, 10)
            setting.add_parameter(op_params_list[1], 3, 100, 10)
            op_params_result_list = pb.backtesting_engine.run_ga_optimization(setting)
            # show op result
            op_df = pb.run_backtesting(
                strategy_class=strategy_cls,
                setting=op_params_result_list[0][0],
                vt_symbol=vt_symbol,
                bk_param_dict=bk_param_dict
            )
            pb.show_portafolio(op_df)
示例#4
0
from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from vnpy.app.cta_strategy.strategies.atr_rsi_strategy_digu import (
    AtrRsiStrategyDigu, )
from datetime import datetime

engine = BacktestingEngine()
engine.set_parameters(
    vt_symbol="000001_SH.SSE",
    interval="d",
    start=datetime(2019, 1, 1),
    end=datetime(2019, 12, 31),
    rate=0.3 / 10000,
    slippage=0.2,
    size=300,
    pricetick=0.2,
    capital=1_000_000,
)
engine.add_strategy(AtrRsiStrategyDigu, {})

engine.load_data()
engine.run_backtesting()
df = engine.calculate_result()
engine.calculate_statistics()
engine.show_chart()

setting = OptimizationSetting()
setting.set_target("sharpe_ratio")
setting.add_parameter("atr_length", 3, 39, 1)
setting.add_parameter("atr_ma_length", 10, 30, 1)

# engine.run_ga_optimization(setting)
示例#5
0
        result = engine.run_ga_optimization(setting)

    return result


if __name__ == "__main__":

    from strategies.AAA import AAA

    # 回测参数设置
    strategy = AAA  # 参数优化策略
    product = "IF"  # 参数优化品种
    start = date(2020, 1, 1)  # 回测起始时间
    end = date(2020, 6, 30)  # 回测结束时间
    capital = 500000  # 初始资金

    # 参数优化设置
    setting = OptimizationSetting()
    setting.set_target("total_return")
    setting.add_parameter("long_period", 3, 10, 1)
    setting.add_parameter("rsi_win", 10, 20, 1)
    setting.add_parameter("k_line_win", 6, 20, 1)
    setting.add_parameter("donchian_win", 6, 20, 1)
    setting.add_parameter("trailing_long", 0.5, 1, 0.1)
    setting.add_parameter("trailing_short", 0.5, 1, 0.1)

    print("开始运行参数优化")
    result = run_optimization(strategy=strategy,
                              product=product,
                              setting=setting,
                              ga=False)
    run_backtesting(
        strategy_class=strategy_class,
        setting={},
        vt_symbol=vt_symbol,
        interval=interval,
        start=start,
        end=end,
        rate=rate,
        slippage=slippage,
        size=size,
        pricetick=pricetick,
        capital=capital,
        inverse=inverse,  # 正反向合约
    )

    setting = OptimizationSetting()
    setting.set_target(f"{class_name}")
    setting.add_parameter("open_window", 10, 15, 5)  # 开始值,结束值,步长
    setting.add_parameter("boll_length", 10, 500, 10)
    setting.add_parameter("sl_multiplier", 0.3, 1, 0.02)
    setting.add_parameter("dc_length", 10, 200, 5)
    setting.add_parameter("prop", 1, 2, 0.2)
    # setting.add_parameter("", 1, 3, 1)
    # setting.add_parameter("atr_window", 1, 3, 1)
    #setting.add_parameter("risk_level", 0.2, 0.2, 0.1)
    # setting.add_parameter("trailing_tax", 0.7, 2.5, 0.1)

    # 调用算法类型(遗传,穷举)
    result = backtests(backtest, setting)

    to_csv_result(
示例#7
0
class OptimizationSettingEditor(QtWidgets.QDialog):
    """
    For setting up parameters for optimization.
    """
    DISPLAY_NAME_MAP = {
        "总收益率": "total_return",
        "夏普比率": "sharpe_ratio",
        "收益回撤比": "return_drawdown_ratio",
        "日均盈亏": "daily_net_pnl"
    }

    def __init__(
            self, class_name: str, parameters: dict
    ):
        """"""
        super().__init__()

        self.class_name = class_name
        self.parameters = parameters
        self.edits = {}

        self.optimization_setting = None
        self.use_ga = False

        self.init_ui()

    def init_ui(self):
        """"""
        QLabel = QtWidgets.QLabel

        self.target_combo = QtWidgets.QComboBox()
        self.target_combo.addItems(list(self.DISPLAY_NAME_MAP.keys()))

        grid = QtWidgets.QGridLayout()
        grid.addWidget(QLabel("目标"), 0, 0)
        grid.addWidget(self.target_combo, 0, 1, 1, 3)
        grid.addWidget(QLabel("参数"), 1, 0)
        grid.addWidget(QLabel("开始"), 1, 1)
        grid.addWidget(QLabel("步进"), 1, 2)
        grid.addWidget(QLabel("结束"), 1, 3)

        # Add vt_symbol and name edit if add new strategy
        self.setWindowTitle(f"优化参数配置:{self.class_name}")

        validator = QtGui.QDoubleValidator()
        row = 2

        for name, value in self.parameters.items():
            type_ = type(value)
            if type_ not in [int, float]:
                continue

            start_edit = QtWidgets.QLineEdit(str(value))
            step_edit = QtWidgets.QLineEdit(str(1))
            end_edit = QtWidgets.QLineEdit(str(value))

            for edit in [start_edit, step_edit, end_edit]:
                edit.setValidator(validator)

            grid.addWidget(QLabel(name), row, 0)
            grid.addWidget(start_edit, row, 1)
            grid.addWidget(step_edit, row, 2)
            grid.addWidget(end_edit, row, 3)

            self.edits[name] = {
                "type": type_,
                "start": start_edit,
                "step": step_edit,
                "end": end_edit
            }

            row += 1

        parallel_button = QtWidgets.QPushButton("多进程优化")
        parallel_button.clicked.connect(self.generate_parallel_setting)
        grid.addWidget(parallel_button, row, 0, 1, 4)

        row += 1
        ga_button = QtWidgets.QPushButton("遗传算法优化")
        ga_button.clicked.connect(self.generate_ga_setting)
        grid.addWidget(ga_button, row, 0, 1, 4)

        self.setLayout(grid)

    def generate_ga_setting(self):
        """"""
        self.use_ga = True
        self.generate_setting()

    def generate_parallel_setting(self):
        """"""
        self.use_ga = False
        self.generate_setting()

    def generate_setting(self):
        """"""
        self.optimization_setting = OptimizationSetting()

        self.target_display = self.target_combo.currentText()
        target_name = self.DISPLAY_NAME_MAP[self.target_display]
        self.optimization_setting.set_target(target_name)

        for name, d in self.edits.items():
            type_ = d["type"]
            start_value = type_(d["start"].text())
            step_value = type_(d["step"].text())
            end_value = type_(d["end"].text())

            if start_value == end_value:
                self.optimization_setting.add_parameter(name, start_value)
            else:
                self.optimization_setting.add_parameter(
                    name,
                    start_value,
                    end_value,
                    step_value
                )

        self.accept()

    def get_setting(self):
        """"""
        return self.optimization_setting, self.use_ga
示例#8
0
        inverse=inverse,  # 正反向合约
    )
    """
    open_window = 15
    boll_length = 80
    boll_dev = 2.0
    bias = 2.0
    cci_length = 6
    cci_exit = 10.0
    atr_window = 16
    atr_multiple = 2.0
    long_trailing = 4.0
    short_trailing = 4.0
    """

    setting = OptimizationSetting()
    setting.set_target(f"{class_name}")
    # setting.add_parameter("open_window", 15, 60, 15)
    # setting.add_parameter("rsi_window", 10, 150, 10)
    # setting.add_parameter("exit_window", 30, 80, 5)
    # setting.add_parameter("ema_window", 30, 80, 5)
    # setting.add_parameter("pos_trailing", 2, 3, 0.2)

    # setting.add_parameter("open_window", 15, 15, 15)
    # setting.add_parameter("fast_length", 20, 140, 5)
    # setting.add_parameter("slow_length", 20, 300, 20)

    # setting.add_parameter("open_window", 30, 30, 30)
    # setting.add_parameter("boll_length", 100, 600, 20)
    # setting.add_parameter("boll_dev", 1.4, 3, 0.1)
    # setting.add_parameter("bias", 0.1, 0.5, 0.03)
示例#9
0
    cost_multiple = 2.0
    interval = 'd'
    keep_last_open = True
    note_str = 'double_ma_exit_atr_rein_daily'

    commodity_list = [
        "cu", "al", "zn", "pb", "ni", "sn", "au", "ag", "rb", "hc", "bu", "ru",
        "sp", "m", "y", "a", "b", "p", "c", "cs", "jd", "l", "v", "pp", "j",
        "jm", "i", "SR", "CF", "ZC", "FG", "TA", "MA", "OI", "RM", "SF", "SM"
    ]

    # for test
    # commodity_list = ["cu", "al", "zn"]
    # commodity_list = ["sp"]

    turtle_gen = OptimizationSetting()
    turtle_gen.add_parameter("fast_window", 5)
    turtle_gen.add_parameter("slow_window", 50)
    turtle_gen.add_parameter("atr_multi", 1.0, 2.5, 0.5)
    turtle_gen.add_parameter("exit_atr_multi", 2, 4, 1)
    turtle_gen.add_parameter("max_rein", 1, 3, 1)

    # turtle_gen.add_parameter("entry_window", 5, 10, 5)
    # turtle_gen.add_parameter("exit_window", 20)
    # turtle_gen.add_parameter("sl_multiplier", 3.5)

    turtle_settings = turtle_gen.generate_setting()

    # load custom setting
    # df = pd.read_csv('custom_turtle_settings.csv')
    # series = dict(df.iterrows()).values()
示例#10
0
    run_backtesting(
        strategy_class=strategy_class,
        setting={},
        vt_symbol=vt_symbol,
        interval=interval,
        start=start,
        end=end,
        rate=rate,
        slippage=slippage,
        size=size,
        pricetick=pricetick,
        capital=capital,
        inverse=inverse,  # 正反向合约
    )
    # 优化函数
    setting = OptimizationSetting()

    # 优化指示名称  如果夏普率
    setting.set_target(f"{class_name}")
    setting.add_parameter("open_window", 15, 15, 5)  # 开始值,结束值,步长
    setting.add_parameter("boll_length", 60, 100, 2)
    setting.add_parameter("sl_multiplier", 0.6, 0.8, 0.01)
    setting.add_parameter("dc_length", 70, 100, 5)
    setting.add_parameter("prop", 1.8, 1.8, 0.2)

    # 多进程穷举优化
    result = engine.run_optimization(setting)

    to_csv_result(
        result=result,
        signal_name=str(strategy_class.__qualname__),  # 策略名称
    run_backtesting(
        strategy_class=strategy_class,
        setting={},
        vt_symbol=vt_symbol,
        interval=interval,
        start=start,
        end=end,
        rate=rate,
        slippage=slippage,
        size=size,
        pricetick=pricetick,
        capital=capital,
        inverse=inverse,  # 正反向合约
    )

    setting = OptimizationSetting()
    setting.set_target(f"{class_name}")
    setting.add_parameter("open_window", 5, 5, 1)
    setting.add_parameter("nloss_singnal", 2.5, 4, 0.1)
    setting.add_parameter("atrstop_window", 40, 60, 5)
    # setting.add_parameter("", 16, 32, 2)
    # setting.add_parameter("", 7, 11, 1)
    # setting.add_parameter("", 1, 3, 1)
    # setting.add_parameter("atr_window", 1, 3, 1)
    #setting.add_parameter("risk_level", 0.2, 0.2, 0.1)
    # setting.add_parameter("trailing_tax", 0.7, 2.5, 0.1)

    result = engine.run_ga_optimization(setting)  #遗传算法

    to_csv_result(
        result=result,
示例#12
0
    engine = BacktestingEngine()
    engine.set_parameters(
        vt_symbol="510050.SSE",
        interval="1m",
        start=start,
        end=datetime(2020, 4, 1),
        rate=1/10000,
        slippage=0.002,
        size=10000,
        pricetick=0.001,
        capital=1_000_000,
    )
    engine.add_strategy(test_strategy_cls, {})

    setting = OptimizationSetting()
    setting.set_target("sharpe_ratio")

    # setting.add_parameter("hedge_range_param", 10, 200, 10)
    # setting.add_parameter("hedge_multiple_param", 40, 100, 20)
    # setting.add_parameter("hedge_size", 10)

    setting.add_parameter("hedge_range_percent", 20)
    setting.add_parameter("hedge_multiple_percent", 30, 100, 10)

    # setting.add_parameter("atr_range", 5, 30, 5)
    # setting.add_parameter("hedge_multiple_percent", 40, 100, 20)

    results = engine.run_optimization(setting)

    start_str = dt_to_str(start)
示例#13
0
engine = BacktestingEngine()
engine.set_parameters(
    vt_symbol="AG2005.SHFE",
    interval="1m",
    start=datetime(2010, 1, 1),
    end=datetime.now(),
    rate=2.25 / 10000,
    slippage=1,
    size=10,
    pricetick=1,
    capital=30000,
)
engine.add_strategy(CincoP2005Strategy, {})


engine.load_data()
engine.run_backtesting()
df = engine.calculate_result()
engine.calculate_statistics()


setting = OptimizationSetting()
setting.set_target("sharpe_ratio")
setting.add_parameter("boll_window", 16, 30, 2)
setting.add_parameter("boll_dev", 1.2, 3.2, 0.1)

result_values = engine.run_ga_optimization(setting)
print(result_values)