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

使用VectorBT IndicatorFactory与from_talib()时的AttributeError修复求助

解决VectorBT中IndicatorFactory.from_talib的AttributeError错误

错误原因

vbt.IndicatorFactory.from_talib('RSI')这行代码存在问题:from_talib方法需要接收TA-Lib的实际函数对象(比如talib.RSI),而非函数名字符串。传入字符串会导致VectorBT内部无法正确读取函数的元信息,从而抛出_Functioninfo不存在的错误。

修正后的完整代码

import vectorbt as vbt
import numpy as np
import pandas as pd
import talib
from numba import njit

# 下载BTC-GBP的1小时收盘价数据
btc_price = vbt.YFData.download(symbols='BTC-GBP', period='100d', interval='1h').get("Close")

# 正确用法:传入talib.RSI函数对象,而非字符串
RSI = vbt.IndicatorFactory.from_talib(talib.RSI)

@njit
def produce_signal(rsi, entry, exit):
    trend = np.where(rsi > exit, -1, 0)
    trend = np.where(rsi < entry, 1, trend)
    return trend

def custom_indicator(close, rsi_window=14, entry=30, exit=70):
    # 调用RSI.run时使用TA-Lib原生参数名timeperiod
    rsi = RSI.run(close, timeperiod=rsi_window).real
    return produce_signal(rsi.to_numpy(), entry, exit)

# 创建自定义指标
ind = vbt.IndicatorFactory(
    class_name="Combination",
    short_name="comb",
    input_names=["close"],
    param_names=["rsi_window", "entry", "exit"],
    output_names=["value"],
).from_apply_func(
    custom_indicator,
    rsi_window=14,
    entry=30,
    exit=70,
)

# 运行指标参数优化
res = ind.run(
    btc_price,
    rsi_window=np.arange(2, 40, step=2, dtype=int),
    entry=np.arange(10, 40, step=2, dtype=int),
    exit=np.arange(60, 90, step=2, dtype=int),
    param_product=True
)

# 生成交易信号
entries = res.value == 1
exits = res.value == -1

# 构建投资组合并分析
pf = vbt.Portfolio.from_signals(
    btc_price,
    entries,
    exits,
    freq='1h',
    sl_stop=0.02,  # 单个数值即可,无需用列表包裹
    sl_trail=True,
)

print(pf.stats())
pf.plot().show()

额外优化点

  • 调用RSI.run时使用TA-Lib原生参数名timeperiod,避免参数不匹配
  • sl_stop参数直接传入单个数值即可,VectorBT会自动处理,无需用列表包裹
  • 保留@njit装饰器加速信号生成逻辑,在多参数组合测试时能显著提升运行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 07:09:26