Skip to content

Backtest: FX bar data

Loren1166 edited this page Sep 25, 2024 · 6 revisions

Backtest: FX bar data 回测:外汇K线数据

Tutorial for NautilusTrader a high-performance algorithmic trading platform and event driven backtester.

NautilusTrader 教程,一个高性能算法交易平台和事件驱动的回测器。

View source on GitHub.

在 GitHub 上查看源代码。

info 信息

We are currently working on this article.

我们目前正在撰写本文。

Overview 概述

This tutorial runs through how to set up a BacktestEngine (low-level API) for a single 'one-shot' backtest run using FX bar data.

本教程介绍如何设置 BacktestEngine(低级 API)以使用外汇K线数据运行单个“一次性”回测。

Prerequisites 先决条件

  • Python 3.10+ installed 安装 Python 3.10+
  • JupyterLab or similar installed (pip install -U jupyterlab) 安装 JupyterLab 或类似软件 (pip install -U jupyterlab)
  • NautilusTrader latest release installed (pip install -U nautilus_trader) 安装 NautilusTrader 最新版本 (pip install -U nautilus_trader)

Imports 导入

We'll start with all of our imports for the remainder of this tutorial.

我们将从本教程其余部分的所有导入开始。

from decimal import Decimal

from nautilus_trader.backtest.engine import BacktestEngine
from nautilus_trader.backtest.engine import BacktestEngineConfig
from nautilus_trader.backtest.models import FillModel
from nautilus_trader.backtest.modules import FXRolloverInterestConfig
from nautilus_trader.backtest.modules import FXRolloverInterestModule
from nautilus_trader.config import LoggingConfig
from nautilus_trader.config import RiskEngineConfig
from nautilus_trader.examples.strategies.ema_cross import EMACross
from nautilus_trader.examples.strategies.ema_cross import EMACrossConfig
from nautilus_trader.model.currencies import JPY
from nautilus_trader.model.currencies import USD
from nautilus_trader.model.data import BarType
from nautilus_trader.model.enums import AccountType
from nautilus_trader.model.enums import OmsType
from nautilus_trader.model.identifiers import Venue
from nautilus_trader.model.objects import Money
from nautilus_trader.persistence.wranglers import QuoteTickDataWrangler
from nautilus_trader.test_kit.providers import TestDataProvider
from nautilus_trader.test_kit.providers import TestInstrumentProvider

Set up backtest engine 设置回测引擎

# Initialize a backtest configuration
# 初始化回测配置
config = BacktestEngineConfig(
    trader_id="BACKTESTER-001",
    logging=LoggingConfig(log_level="ERROR"),
    risk_engine=RiskEngineConfig(
        bypass=True,  # Example of bypassing pre-trade risk checks for backtests 回测绕过交易前风险检查的示例
    ),
)

# Build backtest engine
# 构建回测引擎
engine = BacktestEngine(config=config)

Add simulation module 添加模拟模块

We can optionally plug in a module to simulate rollover interest. The data is available from pre-packaged test data.

我们可以选择插入一个模块来模拟隔夜利息。数据可从预先打包的测试数据中获得。

provider = TestDataProvider()
interest_rate_data = provider.read_csv("short-term-interest.csv")
config = FXRolloverInterestConfig(interest_rate_data)
fx_rollover_interest = FXRolloverInterestModule(config=config)

Add fill model 添加成交模型

For this backtest we'll use a simple probabilistic fill model.

对于此回测,我们将使用一个简单的概率成交模型。

fill_model = FillModel(
    prob_fill_on_limit=0.2,
    prob_fill_on_stop=0.95,
    prob_slippage=0.5,
    random_seed=42,
)

Add venue 添加交易平台

For this backtest we just need a single trading venue which will be a similated FX ECN.

对于此回测,我们只需要一个交易平台,它将是一个模拟的外汇 ECN。

SIM = Venue("SIM")
engine.add_venue(
    venue=SIM,
    oms_type=OmsType.HEDGING,  # Venue will generate position IDs 交易平台将生成头寸 ID
    account_type=AccountType.MARGIN,
    base_currency=None,  # Multi-currency account 多币种账户
    starting_balances=[Money(1_000_000, USD), Money(10_000_000, JPY)],
    fill_model=fill_model,
    modules=[fx_rollover_interest],
)

Add instruments and data 添加Instrument和数据

Now we can add instruments and data. For this backtest we'll pre-process bid and ask side bar data into quote ticks using a QuoteTickDataWrangler.

现在我们可以添加Instrument和数据了。对于此回测,我们将使用 QuoteTickDataWrangler 将买卖双方K线数据预处理为报价。

# Add instruments
# 添加Instrument
USDJPY_SIM = TestInstrumentProvider.default_fx_ccy("USD/JPY", SIM)
engine.add_instrument(USDJPY_SIM)

# Add data
# 添加数据
wrangler = QuoteTickDataWrangler(instrument=USDJPY_SIM)
ticks = wrangler.process_bar_data(
    bid_data=provider.read_csv_bars("fxcm/usdjpy-m1-bid-2013.csv"),
    ask_data=provider.read_csv_bars("fxcm/usdjpy-m1-ask-2013.csv"),
)
engine.add_data(ticks)

Configure strategy 配置策略

Next we'll configure and initialize a simple EMACross strategy we'll use for the backtest.

接下来,我们将配置和初始化一个简单的 EMACross 策略,用于回测。

# Configure your strategy
# 配置您的策略
config = EMACrossConfig(
    instrument_id=USDJPY_SIM.id,
    bar_type=BarType.from_str("USD/JPY.SIM-5-MINUTE-BID-INTERNAL"),
    fast_ema_period=10,
    slow_ema_period=20,
    trade_size=Decimal(1_000_000),
)

# Instantiate and add your strategy
# 实例化并添加您的策略
strategy = EMACross(config=config)
engine.add_strategy(strategy=strategy)

Run backtest 运行回测

We now have everything required to run the backtest. Once the engine has completed running through all the data, a post-analysis report will be logged.

我们现在拥有运行回测所需的一切。一旦引擎完成所有数据的运行,将记录事后分析报告。

engine.run()

Generating reports 生成报告

Additionally, we can produce various reports to further analyze the backtest result.

此外,我们可以生成各种报告以进一步分析回测结果。

engine.trader.generate_account_report(SIM)

engine.trader.generate_order_fills_report()

engine.trader.generate_positions_report()
文档 (Documentation)
入门 (Getting Started)
概念 (Concepts)
教程 (Tutorials)
集成 (Integrations)
Python API
Rust API[未翻译]
开发者指南 (Developer Guide)
Clone this wiki locally