You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pyalgotrade中enterlong()整数数量限制问题求助

解决pyalgotrade交易比特币时无法使用小数数量的问题

核心逻辑

pyalgotrade默认是为股票(整数股数)设计的,要支持加密货币的小数交易,关键是修改经纪商的数量取整规则,同时适配下单逻辑。

具体解决方案

1. 自定义经纪商类,取消数量取整

创建继承自BacktestingBroker的子类,重写roundQuantity方法,让它直接返回原数值而非强制取整:

from pyalgotrade.broker import backtesting

class CryptoBroker(backtesting.Broker):
    def roundQuantity(self, quantity):
        # 跳过整数取整,直接返回小数数量
        return quantity

2. 在策略中替换默认经纪商

初始化回测策略时,使用自定义的CryptoBroker替代默认经纪商:

from pyalgotrade import strategy
from pyalgotrade.feed import csvfeed

class BitcoinStrategy(strategy.BacktestingStrategy):
    def __init__(self, feed, instrument):
        # 传入佣金率(示例为0.1%),初始化自定义经纪商
        custom_broker = CryptoBroker(0.001, feed)
        super().__init__(feed, custom_broker)
        self.__instrument = instrument

    def onBars(self, bars):
        bar = bars[self.__instrument]
        # 现在可以直接传入小数数量下单
        self.enterLong(self.__instrument, 0.5, True)  # 第三个参数为True表示市价单

# 加载比特币历史CSV数据
feed = csvfeed.GenericBarFeed(frequency=feed.Frequency.DAY)
feed.addBarsFromCSV("BTC", "btc_daily_history.csv")

# 运行回测
btc_strategy = BitcoinStrategy(feed, "BTC")
btc_strategy.run()

3. 额外注意点

  • 确保历史数据的价格字段为精确小数,避免计算误差
  • 限价单的价格参数默认支持小数,无需额外修改
  • 回测时可适当控制资金计算的小数位数,避免精度溢出

内容的提问来源于stack exchange,提问作者Hamze Kabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:50:26