Documentation
Develop and verify crypto trading strategies at a glance.
Key Features
- Pandas vectorize backtest
- Talib wrapper to composite strategies easily
- Backtest visualization and analysis (uses vectorbt as backend)
- Analyze the probability of overfitting (combinatorially symmetric cross validation)
- Easy to deploy strategies on google cloud functions
- Colab and Jupyter compatable
- 10 hours trading bot online course
Installation
pip install finlab_crypto
Colab Example
* basic example for backtesting and optimizationUsage
Setup Research Environment (Recommend)
Create directory./history/ for saving historical data. If Colab notebook is detected, it creates GoogleDrive/crypto_workspace/history and link the folder to ./history/.
python
import finlab_crypto
finlab_crypto.setup()
Get Historical Price
python
ohlcv = finlabcrypto.crawler.getall_binance('BTCUSDT', '4h')
ohlcv.head()
Trading Strategy
python
@finlab_crypto.Strategy(n1=20, n2=60)
def sma_strategy(ohlcv):
n1 = sma_strategy.n1
n2 = sma_strategy.n2
sma1 = ohlcv.close.rolling(int(n1)).mean()
sma2 = ohlcv.close.rolling(int(n2)).mean()
return (sma1 > sma2), (sma1 < sma2)
Backtest
python
default fee and slipagge are 0.1% and 0.1%
vars = {'n1': 20, 'n2': 60} portfolio = sma_strategy.backtest(ohlcv, vars, freq='4h', plot=True)
Optimization
python
import numpy as np
vars = {
'n1': np.arange(10, 100, 5),
'n2': np.arange(10, 100, 5)
}
portfolio = sma_strategy.backtest(ohlcv, vars, freq='4h', plot=True)
Live Trading
To perform live trading of a strategy, the following 3 sections should be executed when any candle is complete.
1. Create TradingMethods
First, we need to encapsulate a strategy intoTradingMethod
from finlabcrypto.online import TradingMethod, TradingPortfolio, renderhtml
create TradingMethod for live trading
tm_sma = TradingMethod(
name='live-strategy-sma'
symbols=['ADAUSDT', 'DOTBTC', 'ETHBTC'], freq='4h', lookback=1200,
strategy=sma_strategy,
variables=dict(n1 = 35, n2 = 105,),
weight=5000,
weight_unit='USDT',
executi # trade at close or open price
)
2. register TradingMethods to TradingPortfolio
ATradingPortfolio can sync the virtual portfolio to your Binance trading account. A TradingPortfolio contains many TradingMethods, which should be executed whenever any new candle is (going to) closed. You can decide when to rebalance the portfolio by giving executebeforecandle_complete when creating the TradingPortfolio:
executebeforecandle_complete=True: rebalance right before* a candle is closed (i.e. setting xx:59 for 1h frequency strategy), so you can execute orders faster then others. However, signal hazards may occur due to incomplete candles.
executebeforecandle_complete=False (default): rebalance right after* a candle is closed (i.e. setting xx:00 for 1h frequency strategy)
The above information is crucial to help TradingPortfolio decide whether to remove incomplete candles when generating trading signals or not. However, Tradingportfolio will not execute periodically for you. So, you should set up a crontab or cloud function to execute it. We recommend you run the code by yourself before setting the crontab or cloud function.
# setup portftolio
BINANCE_KEY = '' # Enter your key and secret here!
BINANCE_SECRET = ''
tp = TradingPortfolio(BINANCEKEY, BINANCESECRET, executebeforecandle_complete=False) tp.register(tm0)
additional trading methods can be registered
tp.register(tm1)
3. view and execute orders
Finally, we could calltp.getohlcvs() to get history data of all trading assets and call tp.getlatestsignals to calculate the trading signals. The aggregate information is created using tp.calculatepositionsize. All the information can be viewed by tp.renderhtml.
ohlcvs = tp.get_ohlcvs()
signals = tp.getlatestsignals(ohlcvs)
position, positionbtc, neworders = tp.calculatepositionsize(signals)
renderhtml(signals, position, positionbtc, neworders, orderresults)
If the result makes sense, use tp.execute_orders to sync the position of your real account. Please make an issue if there is any bug:
# (order) mode can be either 'TEST', 'MARKET', 'LIMIT' TEST mode will show orders without real executions.
orderresults = tp.executeorders(new_orders, mode='TEST')
Testing
The following script runs all test cases on your local environment. Creating an isolated python environment is recommended. To test crawler functions, please provide Binance API's key and secret by setting environment variables BINANCEKEY and BINANCE_SECRET, respectively.
bash
git clone https://github.com/finlab-python/finlab_crypto.git
cd finlab_crypto
pip install requirements.txt
pip install coverage
BINANCEKEY=<<YOURBINANCEKEY>> BINANCESECRET=<<YOURBINANCESECRET>> coverage run -m unittest discover --pattern *_test.py
Updates
Version 0.2.27- support new version of pandas 3.8
- support 3.8 syntax
- fix dependency of python 3.10
- fix dependency in colab
- fix binance min_notional not found
- fix compatability of seaborn in cscv algorithm plotting
- fix pyecharts compatibility
- set the default argument
clientof getnbarsbinance
- fix getallbinance last candle not updated
- fix bar color
- fix stop loss and take profit and add them into tests
- update vectorbt version
- update pandas version
- fix tp.portfolio_backtest
- add
executebeforecandle_complete - add
weightandweight_unitforTradingMethod
- fix numba version
- fix numpy version
- merge transactions to reduce fees
- fix test error (request binance api too fast)
- add USDC as base stable coin (tp.setdefaultstable_coin('USDC'))
- fix version of pandas==1.1.5, since pandas==1.2.0 is not compatable with vectorbt
- fix show_parameters function in Strategy and Filter
- fix weight_btc error
- fix strategy mutable input
- fix entry price online.py
- fix execution price issue
- improve syntax
- add execution price for the strategy
- fix vectorbt version
- update vectorbt to 0.14.4
- refactor(strategy.py): refactor strategy
- refactor(cscv.py): refactor cscv
- add cscvnbins and cscvobjective to strategy.backtest
- add bitmex support
- fix(crawler): getnbars
- fix(TradingPortfolio): get_ohlcv
- fix(TradingPortfolio): portfolio_backtest
- fix error for latestsignal assetbtc_value
- add unittest for latest_signal
- fix web page error
- fix error for zero orders
- fix web page error
- refine render_html function
- refine display html for TradingPortfolio
- add delay when portfolio backtesting
- fix colab compatability
- improve interface of TradingPortfolio
- fix portfolio backtest error
- add last date equity for backtest
- add portfolio backtest
- rename online.py functions
- refactor error tolerance of different position in online.py functions
- set usdt to excluded asset when calculate position size
- set 'filters' as an optional argument on TradingMethod
- set plot range dynamically
- portfolio backtest
- fix talib parameter type incompatable issue
- fix talib parameter type incompatable issue
- fix talib-binary compatable issue using talibstrategy or talibfilter
- add filters to online.py
- add lambda argument options to talib_filter
- move talibfilter to finlabcrypto package
- fix talib filter and strategy pandas import error
- fix talib import error in indicators, talibstrategy, and talibfilter
- remove progress bar when only single strategy is backtested
- adjust online portfolio to support leaverge
- new theme for overfitting plots
- fix online order with zero order amount
- fix SD2 for overfitting plots
- fix strategy variables
- fix talib error
- add filters folder
- add excluded assets when sync portfolio
- add filter folder to setup
- fix variable eval failure
- add filter interface
- add talib strategy wrapper
- add talib filter wrapper
- vectorbt heatmap redesign
- improve optimization plots
- redesign strategy interface
- add new function setup, to replace setup_colab
- fix transaction duplicate bug
- fix bugs of zero transaction
- fix latest signal
- rename strategy.recent_signal
- restructure rebalance function in online.py
- add init module
- add colab setup function
- set vectorbt default
- fix crawler duplicated index
- add seaborn to dependencies
- remove talib-binary from dependencies
- fix padding style
- remove logs when calculating portfolio
- add render html to show final portfolio changes
- add button in html to place real trade with google cloud function
- skip heatmap if it is broken
- add portfolio strategies
- add talib dependency
