920 字
5 分钟
vectorbt学习_02started
教程:https://vectorbt.dev/,started部分
Getting started
基础demo
btc_price = vbt.YFData.download('BTC-USD', start=start, end=end).get('Close')
fast_ma = vbt.MA.run(btc_price, 10, short_name='fast')slow_ma = vbt.MA.run(btc_price, 20, short_name='slow')
entries = fast_ma.ma_crossed_above(slow_ma)exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(btc_price, entries, exits)pf.total_return()多窗口+多标的
eth_price = vbt.YFData.download('ETH-USD', start=start, end=end).get('Close')comb_price = btc_price.vbt.concat(eth_price, keys=pd.Index(['BTC', 'ETH'], name='symbol'))comb_price.vbt.drop_levels(-1, inplace=True)
fast_ma = vbt.MA.run(comb_price, [10, 20], short_name='fast')slow_ma = vbt.MA.run(comb_price, [30, 30], short_name='slow')
entries = fast_ma.ma_crossed_above(slow_ma)exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(comb_price, entries, exits)pf.total_return()
回测区间切分
mult_comb_price, _ = comb_price.vbt.range_split(n=2)mult_comb_pricefast_ma = vbt.MA.run(mult_comb_price, [10, 20], short_name='fast')slow_ma = vbt.MA.run(mult_comb_price, [30, 30], short_name='slow')
entries = fast_ma.ma_crossed_above(slow_ma)exits = fast_ma.ma_crossed_below(slow_ma)
pf = vbt.Portfolio.from_signals(mult_comb_price, entries, exits, freq='1D')pf.total_return()

Features
Pandas<对pandas做了改写和加速>对pandas做了改写和加速>
Pandas acceleration: Compiled versions of most popular pandas functions, such as mapping, reducing, rolling, grouping, and resamping. For best performance, most operations are done strictly using NumPy and Numba. Attaches a custom accessor on top of pandas to easily switch between pandas and vectorbt functionality.Flexible broadcasting: Mechanism for broadcasting array-like objects of arbitrary shapes, including pandas objects with MultiIndex.Pandas utilities: Grouping columns, wrapping NumPy arrays, transforming pandas objects and their indexes, and more.Data
Data acquisition: Supports various data providers, such as Yahoo Finance, Binance, CCXT and Alpaca. Can merge multiple symbols with different index, as well as update them.Data generation: Supports various (random) data generators, such as GBM.Scheduled data updates: Can periodically update any previously downloaded data.Data preparation: Transformation, rescaling, and normalization of data. Custom splitters for cross-validation. Supports Scikit-Learn splitters, such as for K-Folds cross-validation.Labeling for ML: Discrete and continuous label generation for effective training of ML models.Indicators
Technical indicators: Most popular technical indicators with full Numba support, including Moving Average, Bollinger Bands, RSI, Stochastic, MACD, and more. Out-of-the-box support for 99% indicators in Technical Analysis Library, Pandas TA, and TA-Lib thanks to built-in parsers. Each indicator is wrapped with the vectorbt's indicator engine and thus accepts arbitrary hyperparameter combinations - from arrays to Cartesian products.Indicator factory: Sophisticated factory for building custom technical indicators of any complexity. Takes a function and does all the magic for you: generates an indicator skeleton that takes inputs and parameters of any shape and type, and runs the vectorbt's indicator engine. The easiest and most flexible way to create indicators you will find in open source.Signals
Signal analysis: Generation, mapping and reducing, ranking, and distribution analysis of entry and exit signals.Signal generators: Random and stop loss (SL, TSL, TP, etc.) signal generators with full Numba support.Signal factory: Signal factory based on indicator factory specialized for iterative signal generation.Modeling
Portfolio modeling: The fastest backtesting engine in open source: fills 1,000,000 orders in 70-100ms on Apple M1. Flexible and powerful simulation functions for portfolio modeling, highly optimized for highest performance and lowest memory footprint. Supports two major simulation modes: 1) vectorized backtesting using user-provided arrays, such as orders, signals, and records, and 2) event-driven backtesting using user-defined callbacks. Supports shorting and individual as well as multi-asset mixed portfolios. Combines many features across vectorbt into a single behemoth class.Analysis
Performance metrics: Numba-compiled versions of metrics from empyrical and their rolling versions. Adapter for QuantStats.Stats builder: Class for building statistics out of custom metrics. Implements a preset of tailored statistics for many backtesting components, such as signals, returns, and portfolio.Records and mapped arrays: In-house data structures for analyzing complex data, such as simulation logs. Fully compiled with Numba.Trade analysis: Retrospective analysis of trades from various view points. Supports entry trades, exit trades, and positions.Drawdown analysis: Drawdown statistics of any numeric time series.Plotting
Data visualization: Numerous flexible data plotting functions distributed across vectorbt.Figures and widgets: Custom interactive figures and widgets using Plotly, such as Heatmap and Volume. All custom widgets have dedicated methods for efficiently updating their state.Plots builder: Class for building plots out of custom subplots. Implements a preset of tailored subplots for many backtesting components, such as signals, returns, and portfolio.Extra
Notifications: Telegram bot based on Python Telegram Bot.General utilities: Scheduling using schedule, templates, decorators, configs, and more.Caching: Property and method decorators for caching most frequently used objects.Persistance: Most Python objects including data and portfolio can be saved to a file and retrieved back using Dill.Installation(略,已有)
代码和数据结构分析
import numpy as npimport pandas as pdfrom datetime import datetime
import vectorbt as vbt
# Prepare datagbm_data = vbt.GBMData.download( list(range(5)), start='2023-01-01', end='2023-06-01')price=gbm_data.get()[0]fast_ma = vbt.MA.run(price, 5)slow_ma = vbt.MA.run(price, 10)entries = fast_ma.ma_crossed_above(slow_ma)exits = fast_ma.ma_crossed_below(slow_ma)
print(fast_ma.ma.head(40)[20:])print(slow_ma.ma.head(40)[20:])print(entries.head(40)[20:])print(exits.head(40)[20:])
pf = vbt.Portfolio.from_signals(price, entries, exits, init_cash=100)pf.total_profit()
fase_ma slow_ma entries exits2023-01-20 16:00:00+00:00 84.647574 84.049794 True False2023-01-21 16:00:00+00:00 83.575365 82.846123 False False2023-01-22 16:00:00+00:00 82.321140 81.643256 False False2023-01-23 16:00:00+00:00 82.111900 82.375203 False True2023-01-24 16:00:00+00:00 83.728940 83.546189 True False2023-01-25 16:00:00+00:00 86.367612 85.507593 False False2023-01-26 16:00:00+00:00 89.732193 86.653779 False False2023-01-27 16:00:00+00:00 92.474193 87.397667 False False2023-01-28 16:00:00+00:00 93.575949 87.843924 False False2023-01-29 16:00:00+00:00 93.334410 88.531675 False False2023-01-30 16:00:00+00:00 92.383425 89.375519 False False2023-01-31 16:00:00+00:00 93.128770 91.430482 False False2023-02-01 16:00:00+00:00 95.725233 94.099713 False False2023-02-02 16:00:00+00:00 99.180058 96.378003 False False2023-02-03 16:00:00+00:00 103.323654 98.329032 False False2023-02-04 16:00:00+00:00 106.262713 99.323069 False False2023-02-05 16:00:00+00:00 108.586491 100.857631 False False2023-02-06 16:00:00+00:00 111.566106 103.645670 False False2023-02-07 16:00:00+00:00 114.347398 106.763728 False False2023-02-08 16:00:00+00:00 114.953030 109.138342 False False可见:
ma_crossed_above:金叉的第一个bar信号true,后续false
ma_crossed_below:死叉的第一个bar信号true,后续false
Usage(强悍的实例片段,略)
部分信息可能已经过时