지원되는 트레이딩 전략에서 Backtrader와 Zipline 비교
코드 Machine Learning for Trading
요약
이 노트북은 선정된 실제 사례 연구 전략에서 Backtrader, Zipline Reloaded, 내부 트레이딩 프레임워크 간 패리티 비교 결과를 보고합니다. 두 외부 엔진의 ETF 및 US 주식 패널 비교와 Backtrader의 CME 선물 및 USD 표시 FX 비교를 포함합니다. 감사에서는 체결 가격과 수량, 평가 시점, 계좌 가치를 센트 단위 정밀도로 확인합니다. 지원되지 않는 자산 모델은 성공적인 비교로 간주하지 않고 별도로 나열하며, 이 감사에서는 어느 엔진도 암호화폐 무기한 계약의 펀딩을 기본 지원한다고 보지 않습니다.
노트북은 통과한 비교에서 엔진 실행 시간만 따로 보고하고, 일치하는 프레임워크 프로필에 대한 합성 스트레스 테스트도 제시합니다. 시간 측정에는 데이터 및 어댑터 준비가 포함되지 않으므로 다른 전략이나 기기에 일반화하지 말라고 주의를 줍니다. 합성 스트레스 결과는 작업 규모와 이벤트 규약을 보여주는 부차적 근거입니다. 각 프로필이 자체 프레임워크 규약을 따르므로 최종 값은 서로 다릅니다. 통과 기록은 이 감사에서 시험한 조합만 설명하며, 다른 상품, 엔진 기능, 체결 가정의 동등성을 입증하지 않습니다.
핵심 아이디어
- 감사에서는 지원되는 전략과 엔진 조합의 체결, 평가, 타임스탬프, 계좌 가치를 비교합니다.
- Backtrader는 ETF, US 주식, CME 선물, USD 표시 FX을 시험하고, Zipline은 ETF와 US 주식을 시험합니다.
- 지원되지 않는 자산 모형은 지원된 것으로 처리하지 않고 통과 분모에서 제외합니다.
- 실행 시간 측정은 엔진 호출만 포함하며 다른 기기나 전략에는 적용되지 않을 수 있습니다.
- 합성 스트레스 테스트는 규모와 이벤트 규약을 살펴보며, 실제 데이터 행은 필요한 비교를 제공합니다.
태그
전문
# 17_backtrader_zipline_engine_parity.py
```py
# ---
# jupyter:
# jupytext:
# cell_metadata_filter: tags,-all
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.19.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Backtrader and Zipline on Current Case-Study Strategies
#
# This notebook reports the Backtrader and Zipline Reloaded rows from the current real-strategy
# audit. It does not infer asset support from ML4T's configurability: a pair is included only when
# the external engine and frozen bundle can express the same native contract.
#
# **Learning objectives**
#
# - Compare Backtrader and Zipline against ML4T on supported real strategies
# - Apply a monetary comparison unit to account values without weakening fill comparison
# - Interpret the measured engine-only runtime boundary
# - Use synthetic stress evidence as a secondary conformance result
#
# **Book reference**: Chapter 16, Section 16.3
# %% [markdown]
# ## Setup
# %%
"""Current Backtrader and Zipline parity evidence."""
import json
import polars as pl
from IPython.display import display
from utils.paths import get_chapter_dir
# %% tags=["parameters"]
# Production defaults - Papermill injects overrides after this cell
ROUND_SECONDS = 3
# %%
AUDIT_PATH = get_chapter_dir(16) / "resources" / "framework_parity_audit.json"
audit = json.loads(AUDIT_PATH.read_text(encoding="utf-8"))
FRAMEWORKS = ["backtrader", "zipline"]
FRAMEWORK_NAMES = {
key: f"{audit['frameworks'][key]['display_name']} {audit['frameworks'][key]['version']}"
for key in FRAMEWORKS
}
CASE_NAMES = {
"etfs": "ETF allocation",
"cme_futures": "CME futures",
"crypto_perps_funding": "Crypto perpetual funding",
"fx_pairs": "FX allocation (USD-quoted pairs)",
"us_equities_panel": "US equity panel",
}
# %% [markdown]
# ## 1. Required comparisons
# %% tags=["results"]
results = (
pl.DataFrame(audit["real_strategy_records"])
.filter(pl.col("framework").is_in(FRAMEWORKS))
.with_columns(
pl.col("case_study").replace_strict(CASE_NAMES).alias("strategy"),
pl.col("framework").replace_strict(FRAMEWORK_NAMES).alias("engine"),
)
.select(
"strategy",
"engine",
"status",
"fills",
"valuations",
"valuation_timestamps_match",
"equity_gap",
"equity_raw_gap",
"terminal_gap",
"terminal_raw_gap",
)
.sort("strategy", "engine")
)
assert results.height == 6
assert results.filter(pl.col("status") == "pass").height == 6
assert results["valuation_timestamps_match"].all()
display(results)
# %% [markdown]
# Backtrader and Zipline both participate in the ETF and US equity-panel comparisons. Backtrader
# also participates in the CME and USD-quoted foreign-exchange comparisons. The fill stream is
# compared at eight-decimal price precision and five-decimal quantity precision, while account
# values must round to the same cent. Zipline has no required CME or spot-FX row because the frozen
# inputs do not map to its native asset models.
# %% [markdown]
# ## 2. Unsupported asset models
# %% tags=["results"]
unsupported = (
pl.DataFrame(audit["unsupported_records"])
.filter(pl.col("framework").is_in(FRAMEWORKS))
.with_columns(
pl.col("case_study").replace_strict(CASE_NAMES).alias("strategy"),
pl.col("framework").replace_strict(FRAMEWORK_NAMES).alias("engine"),
)
.select("strategy", "engine", "reason")
.sort("strategy", "engine")
)
display(unsupported)
# %% [markdown]
# Neither engine is credited with crypto-perpetual funding support it does not natively provide.
# Unsupported rows are excluded from the pass denominator.
# %% [markdown]
# ## 3. Engine-only timing
#
# Timing is retained only for correctness-passing rows and covers the engine call only.
# %% tags=["results"]
timing = (
pl.DataFrame(audit["performance_records"])
.filter(pl.col("framework").is_in(FRAMEWORKS))
.with_columns(
pl.col("case_study").replace_strict(CASE_NAMES).alias("strategy"),
pl.col("framework").replace_strict(FRAMEWORK_NAMES).alias("engine"),
pl.col("framework_median_seconds").round(ROUND_SECONDS).alias("external_seconds"),
pl.col("ml4t_median_seconds").round(ROUND_SECONDS).alias("ml4t_seconds"),
pl.col("framework_to_ml4t_ratio").round(2).alias("external_div_ml4t"),
)
.select("strategy", "engine", "external_seconds", "ml4t_seconds", "external_div_ml4t")
)
assert timing.height == 6
display(timing)
# %% [markdown]
# The timer excludes data and adapter preparation. The ratios should not be applied to other
# strategies or machines.
# %% [markdown]
# ## 4. Synthetic stress evidence
# %% tags=["results"]
stress = (
pl.DataFrame(audit["synthetic_stress"]["records"])
.filter(pl.col("framework").is_in(FRAMEWORKS))
.with_columns(pl.col("framework").replace_strict(FRAMEWORK_NAMES).alias("engine"))
.select("engine", "intents", "fills", "trades", "terminal_value", "status")
)
display(stress)
# %% [markdown]
# Both synthetic stress rows pass against their matching ML4T profiles. Their terminal values differ
# because the profiles reproduce different framework conventions. The test is pairwise: ML4T versus
# Backtrader and ML4T versus Zipline. The workload tests scale and event conventions, while the
# required rows above determine the real-data comparison.
```출처의 라이선스에 따라 출처를 표시하고 전문을 공개합니다. 라이선스: MIT
이 요약은 원문을 바탕으로 Stratmill의 리서치 에이전트가 작성했으며, 원문을 복사한 것이 아닙니다.