| 1 | # Strategy analysis example |
| 2 | |
| 3 | Debugging a strategy can be time-consuming. Freqtrade offers helper functions to visualize raw data. |
| 4 | The 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 |
| 10 | from pathlib import Path |
| 11 | from freqtrade.configuration import Configuration |
| 12 | |
| 13 | # Customize these according to your needs. |
| 14 | |
| 15 | # Initialize empty configuration object |
| 16 | config = Configuration.from_files([]) |
| 17 | # Optionally, use existing configuration file |
| 18 | # config = Configuration.from_files(["config.json"]) |
| 19 | |
| 20 | # Define some constants |
| 21 | config["timeframe"] = "5m" |
| 22 | # Name of the strategy class |
| 23 | config["strategy"] = "SampleStrategy" |
| 24 | # Location of the data |
| 25 | data_location = Path(config['user_data_dir'], 'data', 'binance') |
| 26 | # Pair to analyze - Only use one pair here |
| 27 | pair = "BTC/USDT" |
| 28 | ``` |
| 29 | |
| 30 | |
| 31 | ```python |
| 32 | # Load data using values set above |
| 33 | from freqtrade.data.history import load_pair_history |
| 34 | |
| 35 | candles = load_pair_history(datadir=data_location, |
| 36 | timeframe=config["timeframe"], |
| 37 | pair=pair, |
| 38 | data_format = "hdf5", |
| 39 | ) |
| 40 | |
| 41 | # Confirm success |
| 42 | print("Loaded " + str(len(candles)) + f" rows of data for {pair} from {data_location}") |
| 43 | candles.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 |
| 52 | from freqtrade.resolvers import StrategyResolver |
| 53 | strategy = StrategyResolver.load_strategy(config) |
| 54 | |
| 55 | # Generate buy/sell signals using strategy |
| 56 | df = strategy.analyze_ticker(candles, {'pair': pair}) |
| 57 | df.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 |
| 74 | print(f"Generated {df['buy'].sum()} buy signals") |
| 75 | data = df.set_index('date', drop=False) |
| 76 | data.tail() |
| 77 | ``` |
| 78 | |
| 79 | ## Load existing objects into a Jupyter notebook |
| 80 | |
| 81 | The following cells assume that you have already generated data using the cli. |
| 82 | They 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 | |
| 86 | Analyze a trades dataframe (also used below for plotting) |
| 87 | |
| 88 | |
| 89 | ```python |
| 90 | from 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. |
| 93 | backtest_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. |
| 102 | stats = load_backtest_stats(backtest_dir) |
| 103 | |
| 104 | strategy = '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: |
| 107 | print(stats['strategy'][strategy]['results_per_pair']) |
| 108 | # Get pairlist used for this backtest |
| 109 | print(stats['strategy'][strategy]['pairlist']) |
| 110 | # Get market change (average change of all pairs from start to end of the backtest period) |
| 111 | print(stats['strategy'][strategy]['market_change']) |
| 112 | # Maximum drawdown () |
| 113 | print(stats['strategy'][strategy]['max_drawdown']) |
| 114 | # Maximum drawdown start and end |
| 115 | print(stats['strategy'][strategy]['drawdown_start']) |
| 116 | print(stats['strategy'][strategy]['drawdown_end']) |
| 117 | |
| 118 | |
| 119 | # Get strategy comparison (only relevant if multiple strategies were compared) |
| 120 | print(stats['strategy_comparison']) |
| 121 | |
| 122 | ``` |
| 123 | |
| 124 | |
| 125 | ```python |
| 126 | # Load backtested trades as dataframe |
| 127 | trades = load_backtest_data(backtest_dir) |
| 128 | |
| 129 | # Show value-counts per pair |
| 130 | trades.groupby("pair")["sell_reason"].value_counts() |
| 131 | ``` |
| 132 | |
| 133 | ### Load live trading results into a pandas dataframe |
| 134 | |
| 135 | In case you did already some trading and want to analyze your performance |
| 136 | |
| 137 | |
| 138 | ```python |
| 139 | from freqtrade.data.btanalysis import load_trades_from_db |
| 140 | |
| 141 | # Fetch trades from database |
| 142 | trades = load_trades_from_db("sqlite:///tradesv3.sqlite") |
| 143 | |
| 144 | # Display results |
| 145 | trades.groupby("pair")["sell_reason"].value_counts() |
| 146 | ``` |
| 147 | |
| 148 | ## Analyze the loaded trades for trade parallelism |
| 149 | This 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 |
| 155 | from freqtrade.data.btanalysis import analyze_trade_parallelism |
| 156 | |
| 157 | # Analyze the above |
| 158 | parallel_trades = analyze_trade_parallelism(trades, '5m') |
| 159 | |
| 160 | parallel_trades.plot() |
| 161 | ``` |
| 162 | |
| 163 | ## Plot results |
| 164 | |
| 165 | Freqtrade offers interactive plotting capabilities based on plotly. |
| 166 | |
| 167 | |
| 168 | ```python |
| 169 | from freqtrade.plot.plotting import generate_candlestick_graph |
| 170 | # Limit graph period to keep plotly quick and reactive |
| 171 | |
| 172 | # Filter trades to one pair |
| 173 | trades_red = trades.loc[trades['pair'] == pair] |
| 174 | |
| 175 | data_red = data['2019-06-01':'2019-06-10'] |
| 176 | # Generate candlestick graph |
| 177 | graph = 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 |
| 194 | graph.show(renderer="browser") |
| 195 | |
| 196 | ``` |
| 197 | |
| 198 | Feel 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. |