在 Freqtrade 中进行超参数优化时如何正确使用超参数

本人github

在 Freqtrade 中进行超参数优化时如何正确使用超参数

超参数优化(Hyperparameter Optimization, HPO)是提高交易策略性能的关键步骤之一。通过优化策略中的参数,我们可以找到最佳的参数组合,从而提高收益、减少风险。然而,在 Freqtrade 中进行超参数优化时,有一些需要注意的地方,尤其是如何正确使用超参数。

问题背景

在 Freqtrade 中,超参数优化过程中一个常见的错误是尝试在 populate_indicators 方法中使用超参数。这会导致优化结果不准确,并且 Freqtrade 会抛出以下错误:

Hyperoptable parameters cannot be used in populate_indicators - as hyperopt does not recalculate indicators for each epoch, so the starting value would be used in this case.
为什么会出现这个问题?

超参数优化涉及到在每次迭代中调整参数,并使用这些参数进行回测。然而,populate_indicators 方法中的指标计算只在优化开始时执行一次。如果在这个方法中使用了超参数,那么这些参数的初始值将被用于整个优化过程,而不会在每次迭代中动态调整。这违背了超参数优化的目的。

解决方案

要解决这个问题,我们应该避免在 populate_indicators 方法中使用超参数。相反,我们可以在 populate_buy_trendpopulate_sell_trend 方法中使用这些参数。这些方法会在每次迭代中被调用,从而确保超参数在优化过程中被正确地计算和调整。

示例:正确使用超参数

以下是一个包含 RSI 和 EMA 参数优化的策略示例:

不正确的做法(有错误)

populate_indicators 中使用超参数:

from freqtrade.strategy.interface import IStrategy
from freqtrade.strategy.hyper import IntParameter
from pandas import DataFrame
import talib.abstract as ta

class MyStrategy(IStrategy):
    buy_rsi = IntParameter(10, 30, default=20, space='buy')
    buy_ema_short = IntParameter(5, 50, default=12, space='buy')
    buy_ema_long = IntParameter(20, 200, default=26, space='buy')

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema_short'] = ta.EMA(dataframe, timeperiod=self.buy_ema_short.value)
        dataframe['ema_long'] = ta.EMA(dataframe, timeperiod=self.buy_ema_long.value)
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (dataframe['rsi'] < self.buy_rsi.value) &
            (dataframe['ema_short'] > dataframe['ema_long']),
            'buy'] = 1
        return dataframe
正确的做法

populate_indicators 中使用固定值,在 populate_buy_trendpopulate_sell_trend 中使用超参数:

from freqtrade.strategy.interface import IStrategy
from freqtrade.strategy.hyper import IntParameter
from pandas import DataFrame
import talib.abstract as ta

class MyStrategy(IStrategy):
    buy_rsi = IntParameter(10, 30, default=20, space='buy')
    buy_ema_short = IntParameter(5, 50, default=12, space='buy')
    buy_ema_long = IntParameter(20, 200, default=26, space='buy')

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['ema_short'] = ta.EMA(dataframe, timeperiod=12)  # 固定的 EMA 短期参数
        dataframe['ema_long'] = ta.EMA(dataframe, timeperiod=26)  # 固定的 EMA 长期参数
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (dataframe['rsi'] < self.buy_rsi.value) &
            (dataframe['ema_short'] > dataframe['ema_long']),
            'buy'] = 1
        return dataframe
配置超参数优化

config.json 中启用超参数优化,并设置相关的配置:

{
    "strategy": "MyStrategy",
    "hyperopt": {
        "enabled": true,
        "loss": "SharpeHyperOptLoss",
        "space": {
            "buy_rsi": {
                "type": "int",
                "min": 10,
                "max": 30,
                "default": 20
            },
            "buy_ema_short": {
                "type": "int",
                "min": 5,
                "max": 50,
                "default": 12
            },
            "buy_ema_long": {
                "type": "int",
                "min": 20,
                "max": 200,
                "default": 26
            }
        }
    }
}
运行超参数优化

使用 freqtrade hyperopt 命令运行超参数优化:

freqtrade hyperopt --strategy MyStrategy --timerange 20210101-20211231 --epochs 100
总结

在 Freqtrade 中进行超参数优化时,避免在 populate_indicators 方法中使用超参数,而应在 populate_buy_trendpopulate_sell_trend 方法中使用。这确保了超参数在每次优化迭代中被正确计算和调整,从而实现有效的超参数优化。通过正确使用超参数,可以提升策略的收益和降低风险,优化交易策略的整体性能。

在Java中,可以利用Apache POI库来实现在Excel文件中插入图片导出功能。Apache POI是一个流行的用于处理Microsoft Office格式文档(如Word、Excel和PowerPoint)的API。以下是基本步骤: 1. 引入依赖:首先需要在项目中添加Apache POI的依赖,包括`poi`, `poi-ooxml`, 和 `poi-ooxml-schemas`。 ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>最新版本号</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>最新版本号</version> </dependency> <dependency> <groupId>org.apache.xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>最新版本号</version> </dependency> ``` 2. 创建HSSFWorkbook对象:这是Excel的工作簿。 ```java HSSFWorkbook workbook = new HSSFWorkbook(); ``` 3. 添加Sheet:创建一个新的工作表。 ```java HSSFSheet sheet = workbook.createSheet("Sheet1"); ``` 4. 插入图片:找到一个ImageDataRecord对象来保存图片数据,然后将其添加到单元格。 ```java // 获取图片路径 File imageFile = new File("path_to_your_image.jpg"); // 将图片读取为字节流 InputStream inputStream = new FileInputStream(imageFile); byte[] imageData = IOUtils.toByteArray(inputStream); // 创建ImageDataRecord HSSFDataFormat format = workbook.createDataFormat(); // 图片数据格式 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, 1, 1, 5, 5); // 定位图片位置 XSSFComment comment = sheet.createCellComment(new XSSFRichTextString("Your Image Comment")); // 注释 XSSFImage image = wb.addPicture(imageData, Workbook.PICTURE_TYPE_JPEG, anchor, comment); // 将图片插入到单元格 HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue("Image Cell"); cell.setCellStyle(format.getCenteredStyle()); // 设置单元格样式 cell.setDrawingCell(true); // 标记为包含图像 cell.set Drawing(new XSSFDrawing(sheet)); cell.getDrawing().addAnchor(image); ``` 5. 保存文件:完成所有操作后,将工作簿保存到磁盘上。 ```java try { FileOutputStream outputStream = new FileOutputStream("output.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我想要身体健康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值