finlab-python / finlab_crypto

Documentation
https://finlab-python.github.io/finlab_crypto/index.html
GNU General Public License v3.0
267 stars 98 forks source link
backtesting portfolio-backtest trading-strategy

Build Status PyPI version codecov

Develop and verify crypto trading strategies at a glance.

Key Features

Installation

pip install finlab_crypto

Colab Example

Usage

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/.

import finlab_crypto
finlab_crypto.setup()

Get Historical Price

ohlcv = finlab_crypto.crawler.get_all_binance('BTCUSDT', '4h')
ohlcv.head()

'dataframe'

Trading Strategy

@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

# 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)

image

Optimization

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)

cumulative returns parameter performance parameter range view

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 into TradingMethod

from finlab_crypto.online import TradingMethod, TradingPortfolio, render_html

# 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',
    execution_price='close' # trade at close or open price
)

2. register TradingMethods to TradingPortfolio

A TradingPortfolio 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 execute_before_candle_complete when creating the TradingPortfolio:

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(BINANCE_KEY, BINANCE_SECRET, execute_before_candle_complete=False)
tp.register(tm0)

# additional trading methods can be registered
# tp.register(tm1)

3. view and execute orders

Finally, we could call tp.get_ohlcvs() to get history data of all trading assets and call tp.get_latest_signals to calculate the trading signals. The aggregate information is created using tp.calculate_position_size. All the information can be viewed by tp.render_html.

ohlcvs = tp.get_ohlcvs()
signals = tp.get_latest_signals(ohlcvs)
position, position_btc, new_orders = tp.calculate_position_size(signals)

render_html(signals, position, position_btc, new_orders, order_results)

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.
order_results = tp.execute_orders(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 BINANCE_KEY and BINANCE_SECRET, respectively.

git clone https://github.com/finlab-python/finlab_crypto.git
cd finlab_crypto
pip install requirements.txt
pip install coverage
BINANCE_KEY=<<YOUR_BINANCE_KEY>> BINANCE_SECRET=<<YOUR_BINANCE_SECRET>> coverage run -m unittest discover --pattern *_test.py

Updates

Version 0.2.27

Version 0.2.26

Version 0.2.25 Version 0.2.24

Version 0.2.23

Version 0.2.22

Version 0.2.21

Version 0.2.20

Version 0.2.19

Verison 0.2.18

Verison 0.2.17

Version 0.2.16

Version 0.2.15

Version 0.2.14

Version 0.2.12

Version 0.2.11 Version 0.2.10

Version 0.2.8

Version 0.2.7

Version 0.2.6

Version 0.2.5

Verison 0.2.4

Version 0.2.3

Version 0.2.2: not stable

Version 0.2.1

Version 0.2.0

Version 0.1.19

Version 0.1.18

Version 0.1.17

Version 0.1.16

Version 0.1.15

Version 0.1.14

Version 0.1.13

Version 0.1.12

Version 0.1.11

Version 0.1.10

Version 0.1.9

Version 0.1.8

Version 0.1.7

Version 0.1.6

Version 0.1.5

Version 0.1.4

Version 0.1.3

Version 0.1.2

Version 0.1.1

Version 0.1.0

Version 0.0.9.dev1

Version 0.0.8.dev1

Version 0.0.7.dev1

Version 0.0.6.dev1

Version 0.0.5.dev1

Version 0.0.4.dev1

Version 0.0.3.dev1

Version 0.0.2.dev1