Elffuss BraidHub

kikocis/freqtrade public

develop · 6.4 KiBRenderedRawPermalink
1# Strategy analysis example
2
3Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data.
4The following assumes you work with SampleStrategy, data for 5m timeframe from Binance and have downloaded them into the data directory in the default location.
5
6## Setup
7
8
9```python
10from pathlib import Path
11from freqtrade.configuration import Configuration
12
13# Customize these according to your needs.
14
15# Initialize empty configuration object
16config = Configuration.from_files([])
17# Optionally, use existing configuration file
18# config = Configuration.from_files(["config.json"])
19
20# Define some constants
21config["timeframe"] = "5m"
22# Name of the strategy class
23config["strategy"] = "SampleStrategy"
24# Location of the data
25data_location = Path(config['user_data_dir'], 'data', 'binance')
26# Pair to analyze - Only use one pair here
27pair = "BTC/USDT"
28```
29
30
31```python
32# Load data using values set above
33from freqtrade.data.history import load_pair_history
34
35candles = load_pair_history(datadir=data_location,
36 timeframe=config["timeframe"],
37 pair=pair,
38 data_format = "hdf5",
39 )
40
41# Confirm success
42print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}")
43candles.head()
44```
45
46## Load and run strategy
47* Rerun each time the strategy file is changed
48
49
50```python
51# Load strategy using values set above
52from freqtrade.resolvers import StrategyResolver
53strategy = StrategyResolver.load_strategy(config)
54
55# Generate buy/sell signals using strategy
56df = strategy.analyze_ticker(candles, {'pair': pair})
57df.tail()
58```
59
60### Display the trade details
61
62* Note that using `data.head()` would also work, however most indicators have some "startup" data at the top of the dataframe.
63* Some possible problems
64 * Columns with NaN values at the end of the dataframe
65 * Columns used in `crossed*()` functions with completely different units
66* Comparison with full backtest
67 * having 200 buy signals as output for one pair from `analyze_ticker()` does not necessarily mean that 200 trades will be made during backtesting.
68 * Assuming you use only one condition such as, `df['rsi'] < 30` as buy condition, this will generate multiple "buy" signals for each pair in sequence (until rsi returns > 29). The bot will only buy on the first of these signals (and also only if a trade-slot ("max_open_trades") is still available), or on one of the middle signals, as soon as a "slot" becomes available.
69
70
71
72```python
73# Report results
74print(f"Generated {df['buy'].sum()} buy signals")
75data = df.set_index('date', drop=False)
76data.tail()
77```
78
79## Load existing objects into a Jupyter notebook
80
81The following cells assume that you have already generated data using the cli.
82They will allow you to drill deeper into your results, and perform analysis which otherwise would make the output very difficult to digest due to information overload.
83
84### Load backtest results to pandas dataframe
85
86Analyze a trades dataframe (also used below for plotting)
87
88
89```python
90from freqtrade.data.btanalysis import load_backtest_data, load_backtest_stats
91
92# if backtest_dir points to a directory, it'll automatically load the last backtest file.
93backtest_dir = config["user_data_dir"] / "backtest_results"
94# backtest_dir can also point to a specific file
95# backtest_dir = config["user_data_dir"] / "backtest_results/backtest-result-2020-07-01_20-04-22.json"
96```
97
98
99```python
100# You can get the full backtest statistics by using the following command.
101# This contains all information used to generate the backtest result.
102stats = load_backtest_stats(backtest_dir)
103
104strategy = 'SampleStrategy'
105# All statistics are available per strategy, so if `--strategy-list` was used during backtest, this will be reflected here as well.
106# Example usages:
107print(stats['strategy'][strategy]['results_per_pair'])
108# Get pairlist used for this backtest
109print(stats['strategy'][strategy]['pairlist'])
110# Get market change (average change of all pairs from start to end of the backtest period)
111print(stats['strategy'][strategy]['market_change'])
112# Maximum drawdown ()
113print(stats['strategy'][strategy]['max_drawdown'])
114# Maximum drawdown start and end
115print(stats['strategy'][strategy]['drawdown_start'])
116print(stats['strategy'][strategy]['drawdown_end'])
117
118
119# Get strategy comparison (only relevant if multiple strategies were compared)
120print(stats['strategy_comparison'])
121
122```
123
124
125```python
126# Load backtested trades as dataframe
127trades = load_backtest_data(backtest_dir)
128
129# Show value-counts per pair
130trades.groupby("pair")["sell_reason"].value_counts()
131```
132
133### Load live trading results into a pandas dataframe
134
135In case you did already some trading and want to analyze your performance
136
137
138```python
139from freqtrade.data.btanalysis import load_trades_from_db
140
141# Fetch trades from database
142trades = load_trades_from_db("sqlite:///tradesv3.sqlite")
143
144# Display results
145trades.groupby("pair")["sell_reason"].value_counts()
146```
147
148## Analyze the loaded trades for trade parallelism
149This can be useful to find the best `max_open_trades` parameter, when used with backtesting in conjunction with `--disable-max-market-positions`.
150
151`analyze_trade_parallelism()` returns a timeseries dataframe with an "open_trades" column, specifying the number of open trades for each candle.
152
153
154```python
155from freqtrade.data.btanalysis import analyze_trade_parallelism
156
157# Analyze the above
158parallel_trades = analyze_trade_parallelism(trades, '5m')
159
160parallel_trades.plot()
161```
162
163## Plot results
164
165Freqtrade offers interactive plotting capabilities based on plotly.
166
167
168```python
169from freqtrade.plot.plotting import generate_candlestick_graph
170# Limit graph period to keep plotly quick and reactive
171
172# Filter trades to one pair
173trades_red = trades.loc[trades['pair'] == pair]
174
175data_red = data['2019-06-01':'2019-06-10']
176# Generate candlestick graph
177graph = generate_candlestick_graph(pair=pair,
178 data=data_red,
179 trades=trades_red,
180 indicators1=['sma20', 'ema50', 'ema55'],
181 indicators2=['rsi', 'macd', 'macdsignal', 'macdhist']
182 )
183
184
185
186```
187
188
189```python
190# Show graph inline
191# graph.show()
192
193# Render graph in a seperate window
194graph.show(renderer="browser")
195
196```
197
198Feel free to submit an issue or Pull Request enhancing this document if you would like to share ideas on how to best analyze the data.