Merge pull request #7395 from freqtrade/improve-freqai-docs
Reorganize and improve FreqAI docs
This commit is contained in:
commit
853a4d1014
BIN
docs/assets/freqai_algorithm-diagram.jpg
Normal file
BIN
docs/assets/freqai_algorithm-diagram.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 490 KiB |
BIN
docs/assets/freqai_inlier-metric.jpg
Normal file
BIN
docs/assets/freqai_inlier-metric.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 458 KiB |
217
docs/freqai-configuration.md
Normal file
217
docs/freqai-configuration.md
Normal file
@ -0,0 +1,217 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
`FreqAI` is configured through the typical [Freqtrade config file](configuration.md) and the standard [Freqtrade strategy](strategy-customization.md). Examples of `FreqAI` config and strategy files can be found in `config_examples/config_freqai.example.json` and `freqtrade/templates/FreqaiExampleStrategy.py`, respectively.
|
||||||
|
|
||||||
|
## Setting up the configuration file
|
||||||
|
|
||||||
|
Although there are plenty of additional parameters to choose from, as highlighted in the [parameter table](freqai-parameter-table.md#parameter-table), a `FreqAI` config must at minimum include the following parameters (the parameter values are only examples):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"enabled": true,
|
||||||
|
"purge_old_models": true,
|
||||||
|
"train_period_days": 30,
|
||||||
|
"backtest_period_days": 7,
|
||||||
|
"identifier" : "unique-id",
|
||||||
|
"feature_parameters" : {
|
||||||
|
"include_timeframes": ["5m","15m","4h"],
|
||||||
|
"include_corr_pairlist": [
|
||||||
|
"ETH/USD",
|
||||||
|
"LINK/USD",
|
||||||
|
"BNB/USD"
|
||||||
|
],
|
||||||
|
"label_period_candles": 24,
|
||||||
|
"include_shifted_candles": 2,
|
||||||
|
"indicator_periods_candles": [10, 20]
|
||||||
|
},
|
||||||
|
"data_split_parameters" : {
|
||||||
|
"test_size": 0.25
|
||||||
|
},
|
||||||
|
"model_training_parameters" : {
|
||||||
|
"n_estimators": 100
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
A full example config is available in `config_examples/config_freqai.example.json`.
|
||||||
|
|
||||||
|
## Building a `FreqAI` strategy
|
||||||
|
|
||||||
|
The `FreqAI` strategy requires including the following lines of code in the standard [Freqtrade strategy](strategy-customization.md):
|
||||||
|
|
||||||
|
```python
|
||||||
|
# user should define the maximum startup candle count (the largest number of candles
|
||||||
|
# passed to any single indicator)
|
||||||
|
startup_candle_count: int = 20
|
||||||
|
|
||||||
|
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||||
|
|
||||||
|
# the model will return all labels created by user in `populate_any_indicators`
|
||||||
|
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
||||||
|
# the target mean/std values for each of the labels created by user in
|
||||||
|
# `populate_any_indicators()` for each training period.
|
||||||
|
|
||||||
|
dataframe = self.freqai.start(dataframe, metadata, self)
|
||||||
|
|
||||||
|
return dataframe
|
||||||
|
|
||||||
|
def populate_any_indicators(
|
||||||
|
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Function designed to automatically generate, name and merge features
|
||||||
|
from user indicated timeframes in the configuration file. User controls the indicators
|
||||||
|
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||||
|
(see convention below). I.e. user should not prepend any supporting metrics
|
||||||
|
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||||
|
model.
|
||||||
|
:param pair: pair to be used as informative
|
||||||
|
:param df: strategy dataframe which will receive merges from informatives
|
||||||
|
:param tf: timeframe of the dataframe which will modify the feature names
|
||||||
|
:param informative: the dataframe associated with the informative pair
|
||||||
|
:param coin: the name of the coin which will modify the feature names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
coin = pair.split('/')[0]
|
||||||
|
|
||||||
|
if informative is None:
|
||||||
|
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||||
|
|
||||||
|
# first loop is automatically duplicating indicators for time periods
|
||||||
|
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||||
|
t = int(t)
|
||||||
|
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||||
|
|
||||||
|
indicators = [col for col in informative if col.startswith("%")]
|
||||||
|
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||||
|
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||||
|
if n == 0:
|
||||||
|
continue
|
||||||
|
informative_shift = informative[indicators].shift(n)
|
||||||
|
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||||
|
informative = pd.concat((informative, informative_shift), axis=1)
|
||||||
|
|
||||||
|
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||||
|
skip_columns = [
|
||||||
|
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
]
|
||||||
|
df = df.drop(columns=skip_columns)
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call this
|
||||||
|
# function to populate indicators during training). Notice how we ensure not to
|
||||||
|
# add them multiple times
|
||||||
|
if set_generalized_indicators:
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
Notice how the `populate_any_indicators()` is where [features](freqai-feature-engineering.md#feature-engineering) and labels/targets are added. A full example strategy is available in `templates/FreqaiExampleStrategy.py`.
|
||||||
|
|
||||||
|
Notice also the location of the labels under `if set_generalized_indicators:` at the bottom of the example. This is where single features and labels/targets should be added to the feature set to avoid duplication of them from various configuration parameters that multiply the feature set, such as `include_timeframes`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
The `self.freqai.start()` function cannot be called outside the `populate_indicators()`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Features **must** be defined in `populate_any_indicators()`. Defining `FreqAI` features in `populate_indicators()`
|
||||||
|
will cause the algorithm to fail in live/dry mode. In order to add generalized features that are not associated with a specific pair or timeframe, the following structure inside `populate_any_indicators()` should be used
|
||||||
|
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`):
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False):
|
||||||
|
|
||||||
|
...
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call only this function to populate
|
||||||
|
# indicators for retraining). Notice how we ensure not to add them multiple times by associating
|
||||||
|
# these generalized indicators to the basepair/timeframe
|
||||||
|
if set_generalized_indicators:
|
||||||
|
df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7
|
||||||
|
df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`.
|
||||||
|
|
||||||
|
## Important dataframe key patterns
|
||||||
|
|
||||||
|
Below are the values you can expect to include/use inside a typical strategy dataframe (`df[]`):
|
||||||
|
|
||||||
|
| DataFrame Key | Description |
|
||||||
|
|------------|-------------|
|
||||||
|
| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target (label) inside `FreqAI` (typically following the naming convention `&-s*`). The names of these dataframe columns are fed back as the predictions. For example, to predict the price change in the next 40 candles (similar to `templates/FreqaiExampleStrategy.py`), you would set `df['&-s_close']`. `FreqAI` makes the predictions and gives them back under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`. <br> **Datatype:** Depends on the output of the model.
|
||||||
|
| `df['&*_std/mean']` | Standard deviation and mean values of the defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand the rarity of a prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` and explained [here](#creating-a-dynamic-target-threshold) to evaluate how often a particular prediction was observed during training or historically with `fit_live_predictions_candles`). <br> **Datatype:** Float.
|
||||||
|
| `df['do_predict']` | Indication of an outlier data point. The return value is integer between -1 and 2, which lets you know if the prediction is trustworthy or not. `do_predict==1` means that the prediction is trustworthy. If the Dissimilarity Index (DI, see details [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di)) of the input data point is above the threshold defined in the config, `FreqAI` will subtract 1 from `do_predict`, resulting in `do_predict==0`. If `use_SVM_to_remove_outliers()` is active, the Support Vector Machine (SVM, see details [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm)) may also detect outliers in training and prediction data. In this case, the SVM will also subtract 1 from `do_predict`. If the input data point was considered an outlier by the SVM but not by the DI, or vice versa, the result will be `do_predict==0`. If both the DI and the SVM considers the input data point to be an outlier, the result will be `do_predict==-1`. A particular case is when `do_predict == 2`, which means that the model has expired due to exceeding `expired_hours`. <br> **Datatype:** Integer between -1 and 2.
|
||||||
|
| `df['DI_values']` | Dissimilarity Index (DI) values are proxies for the level of confidence `FreqAI` has in the prediction. A lower DI means the prediction is close to the training data, i.e., higher prediction confidence. See details about the DI [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Float.
|
||||||
|
| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature. For example, you can include the RSI in the training feature set (similar to in `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](freqai-feature-engineering.md). <br> **Note:** Since the number of features prepended with `%` can multiply very quickly (10s of thousands of features is easily engineered using the multiplictative functionality described in the `feature_parameters` table shown above), these features are removed from the dataframe upon return from `FreqAI`. To keep a particular type of feature for plotting purposes, you would prepend it with `%%`. <br> **Datatype:** Depends on the output of the model.
|
||||||
|
|
||||||
|
## Setting the `startup_candle_count`
|
||||||
|
|
||||||
|
The `startup_candle_count` in the `FreqAI` strategy needs to be set up in the same way as in the standard Freqtrade strategy (see details [here](strategy-customization.md#strategy-startup-period)). This value is used by Freqtrade to ensure that a sufficient amount of data is provided when calling the `dataprovider`, to avoid any NaNs at the beginning of the first training. You can easily set this value by identifying the longest period (in candle units) which is passed to the indicator creation functions (e.g., Ta-Lib functions). In the presented example, `startup_candle_count` is 20 since this is the maximum value in `indicators_periods_candles`.
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
There are instances where the Ta-Lib functions actually require more data than just the passed `period` or else the feature dataset gets populated with NaNs. Anecdotally, multiplying the `startup_candle_count` by 2 always leads to a fully NaN free training dataset. Hence, it is typically safest to multiply the expected `startup_candle_count` by 2. Look out for this log message to confirm that the data is clean:
|
||||||
|
|
||||||
|
```
|
||||||
|
2022-08-31 15:14:04 - freqtrade.freqai.data_kitchen - INFO - dropped 0 training points due to NaNs in populated dataset 4319.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Creating a dynamic target threshold
|
||||||
|
|
||||||
|
Deciding when to enter or exit a trade can be done in a dynamic way to reflect current market conditions. `FreqAI` allows you to return additional information from the training of a model (more info [here](freqai-feature-engineering.md#returning-additional-info-from-training)). For example, the `&*_std/mean` return values describe the statistical distribution of the target/label *during the most recent training*. Comparing a given prediction to these values allows you to know the rarity of the prediction. In `templates/FreqaiExampleStrategy.py`, the `target_roi` and `sell_roi` are defined to be 1.25 z-scores away from the mean which causes predictions that are closer to the mean to be filtered out.
|
||||||
|
|
||||||
|
```python
|
||||||
|
dataframe["target_roi"] = dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * 1.25
|
||||||
|
dataframe["sell_roi"] = dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * 1.25
|
||||||
|
```
|
||||||
|
|
||||||
|
To consider the population of *historical predictions* for creating the dynamic target instead of information from the training as discussed above, you would set `fit_live_prediction_candles` in the config to the number of historical prediction candles you wish to use to generate target statistics.
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"fit_live_prediction_candles": 300,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If this value is set, `FreqAI` will initially use the predictions from the training data and subsequently begin introducing real prediction data as it is generated. `FreqAI` will save this historical data to be reloaded if you stop and restart a model with the same `identifier`.
|
||||||
|
|
||||||
|
## Using different prediction models
|
||||||
|
|
||||||
|
`FreqAI` has multiple example prediction model libraries that are ready to be used as is via the flag `--freqaimodel`. These libraries include `Catboost`, `LightGBM`, and `XGBoost` regression, classification, and multi-target models, and can be found in `freqai/prediction_models/`. However, it is possible to customize and create your own prediction models using the `IFreqaiModel` class. You are encouraged to inherit `fit()`, `train()`, and `predict()` to let these customize various aspects of the training procedures.
|
||||||
|
|
||||||
|
### Setting classifier targets
|
||||||
|
|
||||||
|
`FreqAI` includes a variety of classifiers, such as the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. If you elects to use a classifier, the classes need to be set using strings. For example:
|
||||||
|
|
||||||
|
```python
|
||||||
|
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
||||||
|
```
|
||||||
|
|
||||||
|
Additionally, the example classifier models do not accommodate multiple labels, but they do allow multi-class classification within a single label column.
|
78
docs/freqai-developers.md
Normal file
78
docs/freqai-developers.md
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
# Development
|
||||||
|
|
||||||
|
## Project architecture
|
||||||
|
|
||||||
|
The architecture and functions of `FreqAI` are generalized to encourages development of unique features, functions, models, etc.
|
||||||
|
|
||||||
|
The class structure and a detailed algorithmic overview is depicted in the following diagram:
|
||||||
|
|
||||||
|
![image](assets/freqai_algorithm-diagram.jpg)
|
||||||
|
|
||||||
|
As shown, there are three distinct objects comprising `FreqAI`:
|
||||||
|
|
||||||
|
* **IFreqaiModel** - A singular persistent object containing all the necessary logic to collect, store, and process data, engineer features, run training, and inference models.
|
||||||
|
* **FreqaiDataKitchen** - A non-persistent object which is created uniquely for each unique asset/model. Beyond metadata, it also contains a variety of data processing tools.
|
||||||
|
* **FreqaiDataDrawer** - A singular persistent object containing all the historical predictions, models, and save/load methods.
|
||||||
|
|
||||||
|
There are a variety of built-in [prediction models](freqai-configuration.md#using-different-prediction-models) which inherit directly from `IFreqaiModel`. Each of these models have full access to all methods in `IFreqaiModel` and can therefore override any of those functions at will. However, advanced users will likely stick to overriding `fit()`, `train()`, `predict()`, and `data_cleaning_train/predict()`.
|
||||||
|
|
||||||
|
## Data handling
|
||||||
|
|
||||||
|
`FreqAI` aims to organize model files, prediction data, and meta data in a way that simplifies post-processing and enhances crash resilience by automatic data reloading. The data is saved in a file structure,`user_data_dir/models/`, which contains all the data associated with the trainings and backtests. The `FreqaiDataKitchen()` relies heavily on the file structure for proper training and inferencing and should therefore not be manually modified.
|
||||||
|
|
||||||
|
### File structure
|
||||||
|
|
||||||
|
The file structure is automatically generated based on the model `identifier` set in the [config](freqai-configuration.md#setting-up-the-configuration-file). The following structure shows where the data is stored for post processing:
|
||||||
|
|
||||||
|
| Structure | Description |
|
||||||
|
|-----------|-------------|
|
||||||
|
| `config_*.json` | A copy of the model specific configuration file. |
|
||||||
|
| `historic_predictions.pkl` | A file containing all historic predictions generated during the lifetime of the `identifier` model during live deployment. `historic_predictions.pkl` is used to reload the model after a crash or a config change. A backup file is always held incase of corruption on the main file. **`FreqAI` automatically detects corruption and replaces the corrupted file with the backup**. |
|
||||||
|
| `pair_dictionary.json` | A file containing the training queue as well as the on disk location of the most recently trained model. |
|
||||||
|
| `sub-train-*_TIMESTAMP` | A folder containing all the files associated with a single model, such as: <br>
|
||||||
|
|| `*_metadata.json` - Metadata for the model, such as normalization max/mins, expected training feature list, etc. <br>
|
||||||
|
|| `*_model.*` - The model file saved to disk for reloading from a crash. Can be `joblib` (typical boosting libs), `zip` (stable_baselines), `hd5` (keras type), etc. <br>
|
||||||
|
|| `*_pca_object.pkl` - The [Principal component analysis (PCA)](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis) transform (if `principal_component_analysis: true` is set in the config) which will be used to transform unseen prediction features. <br>
|
||||||
|
|| `*_svm_model.pkl` - The [Support Vector Machine (SVM)](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm) model which is used to detect outliers in unseen prediction features. <br>
|
||||||
|
|| `*_trained_df.pkl` - The dataframe containing all the training features used to train the `identifier` model. This is used for computing the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) and can also be used for post-processing. <br>
|
||||||
|
|| `*_trained_dates.df.pkl` - The dates associated with the `trained_df.pkl`, which is useful for post-processing. |
|
||||||
|
|
||||||
|
The example file structure would look like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
├── models
|
||||||
|
│ └── unique-id
|
||||||
|
│ ├── config_freqai.example.json
|
||||||
|
│ ├── historic_predictions.backup.pkl
|
||||||
|
│ ├── historic_predictions.pkl
|
||||||
|
│ ├── pair_dictionary.json
|
||||||
|
│ ├── sub-train-1INCH_1662821319
|
||||||
|
│ │ ├── cb_1inch_1662821319_metadata.json
|
||||||
|
│ │ ├── cb_1inch_1662821319_model.joblib
|
||||||
|
│ │ ├── cb_1inch_1662821319_pca_object.pkl
|
||||||
|
│ │ ├── cb_1inch_1662821319_svm_model.joblib
|
||||||
|
│ │ ├── cb_1inch_1662821319_trained_dates_df.pkl
|
||||||
|
│ │ └── cb_1inch_1662821319_trained_df.pkl
|
||||||
|
│ ├── sub-train-1INCH_1662821371
|
||||||
|
│ │ ├── cb_1inch_1662821371_metadata.json
|
||||||
|
│ │ ├── cb_1inch_1662821371_model.joblib
|
||||||
|
│ │ ├── cb_1inch_1662821371_pca_object.pkl
|
||||||
|
│ │ ├── cb_1inch_1662821371_svm_model.joblib
|
||||||
|
│ │ ├── cb_1inch_1662821371_trained_dates_df.pkl
|
||||||
|
│ │ └── cb_1inch_1662821371_trained_df.pkl
|
||||||
|
│ ├── sub-train-ADA_1662821344
|
||||||
|
│ │ ├── cb_ada_1662821344_metadata.json
|
||||||
|
│ │ ├── cb_ada_1662821344_model.joblib
|
||||||
|
│ │ ├── cb_ada_1662821344_pca_object.pkl
|
||||||
|
│ │ ├── cb_ada_1662821344_svm_model.joblib
|
||||||
|
│ │ ├── cb_ada_1662821344_trained_dates_df.pkl
|
||||||
|
│ │ └── cb_ada_1662821344_trained_df.pkl
|
||||||
|
│ └── sub-train-ADA_1662821399
|
||||||
|
│ ├── cb_ada_1662821399_metadata.json
|
||||||
|
│ ├── cb_ada_1662821399_model.joblib
|
||||||
|
│ ├── cb_ada_1662821399_pca_object.pkl
|
||||||
|
│ ├── cb_ada_1662821399_svm_model.joblib
|
||||||
|
│ ├── cb_ada_1662821399_trained_dates_df.pkl
|
||||||
|
│ └── cb_ada_1662821399_trained_df.pkl
|
||||||
|
|
||||||
|
```
|
268
docs/freqai-feature-engineering.md
Normal file
268
docs/freqai-feature-engineering.md
Normal file
@ -0,0 +1,268 @@
|
|||||||
|
# Feature engineering
|
||||||
|
|
||||||
|
## Defining the features
|
||||||
|
|
||||||
|
Low level feature engineering is performed in the user strategy within a function called `populate_any_indicators()`. That function sets the `base features` such as, `RSI`, `MFI`, `EMA`, `SMA`, time of day, volume, etc. The `base features` can be custom indicators or they can be imported from any technical-analysis library that you can find. One important syntax rule is that all `base features` string names are prepended with `%`, while labels/targets are prepended with `&`.
|
||||||
|
|
||||||
|
Meanwhile, high level feature engineering is handled within `"feature_parameters":{}` in the `FreqAI` config. Within this file, it is possible to decide large scale feature expansions on top of the `base_features` such as "including correlated pairs" or "including informative timeframes" or even "including recent candles."
|
||||||
|
|
||||||
|
It is advisable to start from the template `populate_any_indicators()` in the source provided example strategy (found in `templates/FreqaiExampleStrategy.py`) to ensure that the feature definitions are following the correct conventions. Here is an example of how to set the indicators and labels in the strategy:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def populate_any_indicators(
|
||||||
|
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Function designed to automatically generate, name, and merge features
|
||||||
|
from user-indicated timeframes in the configuration file. The user controls the indicators
|
||||||
|
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
||||||
|
(see convention below). I.e., the user should not prepend any supporting metrics
|
||||||
|
(e.g., bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
||||||
|
model.
|
||||||
|
:param pair: pair to be used as informative
|
||||||
|
:param df: strategy dataframe which will receive merges from informatives
|
||||||
|
:param tf: timeframe of the dataframe which will modify the feature names
|
||||||
|
:param informative: the dataframe associated with the informative pair
|
||||||
|
:param coin: the name of the coin which will modify the feature names.
|
||||||
|
"""
|
||||||
|
|
||||||
|
coin = pair.split('/')[0]
|
||||||
|
|
||||||
|
if informative is None:
|
||||||
|
informative = self.dp.get_pair_dataframe(pair, tf)
|
||||||
|
|
||||||
|
# first loop is automatically duplicating indicators for time periods
|
||||||
|
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
||||||
|
t = int(t)
|
||||||
|
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
||||||
|
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
||||||
|
|
||||||
|
bollinger = qtpylib.bollinger_bands(
|
||||||
|
qtpylib.typical_price(informative), window=t, stds=2.2
|
||||||
|
)
|
||||||
|
informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"]
|
||||||
|
informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"]
|
||||||
|
informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"]
|
||||||
|
|
||||||
|
informative[f"%-{coin}bb_width-period_{t}"] = (
|
||||||
|
informative[f"{coin}bb_upperband-period_{t}"]
|
||||||
|
- informative[f"{coin}bb_lowerband-period_{t}"]
|
||||||
|
) / informative[f"{coin}bb_middleband-period_{t}"]
|
||||||
|
informative[f"%-{coin}close-bb_lower-period_{t}"] = (
|
||||||
|
informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"]
|
||||||
|
)
|
||||||
|
|
||||||
|
informative[f"%-{coin}relative_volume-period_{t}"] = (
|
||||||
|
informative["volume"] / informative["volume"].rolling(t).mean()
|
||||||
|
)
|
||||||
|
|
||||||
|
indicators = [col for col in informative if col.startswith("%")]
|
||||||
|
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
||||||
|
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
||||||
|
if n == 0:
|
||||||
|
continue
|
||||||
|
informative_shift = informative[indicators].shift(n)
|
||||||
|
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
||||||
|
informative = pd.concat((informative, informative_shift), axis=1)
|
||||||
|
|
||||||
|
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
||||||
|
skip_columns = [
|
||||||
|
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
||||||
|
]
|
||||||
|
df = df.drop(columns=skip_columns)
|
||||||
|
|
||||||
|
# Add generalized indicators here (because in live, it will call this
|
||||||
|
# function to populate indicators during training). Notice how we ensure not to
|
||||||
|
# add them multiple times
|
||||||
|
if set_generalized_indicators:
|
||||||
|
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
|
||||||
|
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
|
||||||
|
|
||||||
|
# user adds targets here by prepending them with &- (see convention below)
|
||||||
|
# If user wishes to use multiple targets, a multioutput prediction model
|
||||||
|
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
||||||
|
df["&-s_close"] = (
|
||||||
|
df["close"]
|
||||||
|
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
||||||
|
.mean()
|
||||||
|
/ df["close"]
|
||||||
|
- 1
|
||||||
|
)
|
||||||
|
|
||||||
|
return df
|
||||||
|
```
|
||||||
|
|
||||||
|
In the presented example, the user does not wish to pass the `bb_lowerband` as a feature to the model,
|
||||||
|
and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the
|
||||||
|
model for training/prediction and has therefore prepended it with `%`.
|
||||||
|
|
||||||
|
After having defined the `base features`, the next step is to expand upon them using the powerful `feature_parameters` in the configuration file:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
//...
|
||||||
|
"feature_parameters" : {
|
||||||
|
"include_timeframes": ["5m","15m","4h"],
|
||||||
|
"include_corr_pairlist": [
|
||||||
|
"ETH/USD",
|
||||||
|
"LINK/USD",
|
||||||
|
"BNB/USD"
|
||||||
|
],
|
||||||
|
"label_period_candles": 24,
|
||||||
|
"include_shifted_candles": 2,
|
||||||
|
"indicator_periods_candles": [10, 20]
|
||||||
|
},
|
||||||
|
//...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `include_timeframes` in the config above are the timeframes (`tf`) of each call to `populate_any_indicators()` in the strategy. In the presented case, the user is asking for the `5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set.
|
||||||
|
|
||||||
|
You can ask for each of the defined features to be included also for informative pairs using the `include_corr_pairlist`. This means that the feature set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of the correlated pairs defined in the config (`ETH/USD`, `LINK/USD`, and `BNB/USD` in the presented example).
|
||||||
|
|
||||||
|
`include_shifted_candles` indicates the number of previous candles to include in the feature set. For example, `include_shifted_candles: 2` tells `FreqAI` to include the past 2 candles for each of the features in the feature set.
|
||||||
|
|
||||||
|
In total, the number of features the user of the presented example strat has created is: length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
||||||
|
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
||||||
|
|
||||||
|
### Returning additional info from training
|
||||||
|
|
||||||
|
Important metrics can be returned to the strategy at the end of each model training by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside the custom prediction model class.
|
||||||
|
|
||||||
|
`FreqAI` takes the `my_new_value` assigned in this dictionary and expands it to fit the dataframe that is returned to the strategy. You can then use the returned metrics in your strategy through `dataframe['my_new_value']`. An example of how return values can be used in `FreqAI` are the `&*_mean` and `&*_std` values that are used to [created a dynamic target threshold](freqai-configuration.md#creating-a-dynamic-target-threshold).
|
||||||
|
|
||||||
|
Another example, where the user wants to use live metrics from the trade database, is shown below:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"extra_returns_per_train": {"total_profit": 4}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
You need to set the standard dictionary in the config so that `FreqAI` can return proper dataframe shapes. These values will likely be overridden by the prediction model, but in the case where the model has yet to set them, or needs a default initial value, the preset values are what will be returned.
|
||||||
|
|
||||||
|
## Feature normalization
|
||||||
|
|
||||||
|
`FreqAI` is strict when it comes to data normalization. The train features, $X^{train}$, are always normalized to [-1, 1] using a shifted min-max normalization:
|
||||||
|
|
||||||
|
$$X^{train}_{norm} = 2 * \frac{X^{train} - X^{train}.min()}{X^{train}.max() - X^{train}.min()} - 1$$
|
||||||
|
|
||||||
|
All other data (test data and unseen prediction data in dry/live/backtest) is always automatically normalized to the training feature space according to industry standards. `FreqAI` stores all the metadata required to ensure that test and prediction features will be properly normalized and that predictions are properly denormalized. For this reason, it is not recommended to eschew industry standards and modify `FreqAI` internals - however - advanced users can do so by inheriting `train()` in their custom `IFreqaiModel` and using their own normalization functions.
|
||||||
|
|
||||||
|
## Data dimensionality reduction with Principal Component Analysis
|
||||||
|
|
||||||
|
You can reduce the dimensionality of your features by activating the `principal_component_analysis` in the config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"principal_component_analysis": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will perform PCA on the features and reduce their dimensionality so that the explained variance of the data set is >= 0.999. Reducing data dimensionality makes training the model faster and hence allows for more up-to-date models.
|
||||||
|
|
||||||
|
## Inlier metric
|
||||||
|
|
||||||
|
The `inlier_metric` is a metric aimed at quantifying how similar a the features of a data point are to the most recent historic data points.
|
||||||
|
|
||||||
|
You define the lookback window by setting `inlier_metric_window` and `FreqAI` computes the distance between the present time point and each of the previous `inlier_metric_window` lookback points. A Weibull function is fit to each of the lookback distributions and its cumulative distribution function (CDF) is used to produce a quantile for each lookback point. The `inlier_metric` is then computed for each time point as the average of the corresponding lookback quantiles. The figure below explains the concept for an `inlier_metric_window` of 5.
|
||||||
|
|
||||||
|
![inlier-metric](assets/freqai_inlier-metric.jpg)
|
||||||
|
|
||||||
|
`FreqAI` adds the `inlier_metric` to the training features and hence gives the model access to a novel type of temporal information.
|
||||||
|
|
||||||
|
This function does **not** remove outliers from the data set.
|
||||||
|
|
||||||
|
## Weighting features for temporal importance
|
||||||
|
|
||||||
|
`FreqAI` allows you to set a `weight_factor` to weight recent data more strongly than past data via an exponential function:
|
||||||
|
|
||||||
|
$$ W_i = \exp(\frac{-i}{\alpha*n}) $$
|
||||||
|
|
||||||
|
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points in a feature set.
|
||||||
|
|
||||||
|
![weight-factor](assets/freqai_weight-factor.jpg)
|
||||||
|
|
||||||
|
## Outlier detection
|
||||||
|
|
||||||
|
Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. `FreqAI` implements a variety of methods to identify such outliers and hence mitigate risk.
|
||||||
|
|
||||||
|
### Identifying outliers with the Dissimilarity Index (DI)
|
||||||
|
|
||||||
|
The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model.
|
||||||
|
|
||||||
|
You can tell `FreqAI` to remove outlier data points from the training/test data sets using the DI by including the following statement in the config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"DI_threshold": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty. To do so, `FreqAI` measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points:
|
||||||
|
|
||||||
|
$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$
|
||||||
|
|
||||||
|
where $d_{ab}$ is the distance between the normalized points $a$ and $b$, and $p$ is the number of features, i.e., the length of the vector $X$. The characteristic distance, $\overline{d}$, for a set of training data points is simply the mean of the average distances:
|
||||||
|
|
||||||
|
$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$
|
||||||
|
|
||||||
|
$\overline{d}$ quantifies the spread of the training data, which is compared to the distance between a new prediction feature vectors, $X_k$ and all the training data:
|
||||||
|
|
||||||
|
$$ d_k = \arg \min d_{k,i} $$
|
||||||
|
|
||||||
|
This enables the estimation of the Dissimilarity Index as:
|
||||||
|
|
||||||
|
$$ DI_k = d_k/\overline{d} $$
|
||||||
|
|
||||||
|
You can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model. A higher `DI_threshold` means that the DI is more lenient and allows predictions further away from the training data to be used whilst a lower `DI_threshold` has the opposite effect and hence discards more predictions.
|
||||||
|
|
||||||
|
Below is a figure that describes the DI for a 3D data set.
|
||||||
|
|
||||||
|
![DI](assets/freqai_DI.jpg)
|
||||||
|
|
||||||
|
### Identifying outliers using a Support Vector Machine (SVM)
|
||||||
|
|
||||||
|
You can tell `FreqAI` to remove outlier data points from the training/test data sets using a Support Vector Machine (SVM) by including the following statement in the config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"use_SVM_to_remove_outliers": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The SVM will be trained on the training data and any data point that the SVM deems to be beyond the feature space will be removed.
|
||||||
|
|
||||||
|
`FreqAI` uses `sklearn.linear_model.SGDOneClassSVM` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDOneClassSVM.html) (external website)) and you can elect to provide additional parameters for the SVM, such as `shuffle`, and `nu`.
|
||||||
|
|
||||||
|
The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time.
|
||||||
|
|
||||||
|
The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers and should be between 0 and 1.
|
||||||
|
|
||||||
|
### Identifying outliers with DBSCAN
|
||||||
|
|
||||||
|
You can configure `FreqAI` to use DBSCAN to cluster and remove outliers from the training/test data set or incoming outliers from predictions, by activating `use_DBSCAN_to_remove_outliers` in the config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"use_DBSCAN_to_remove_outliers": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
DBSCAN is an unsupervised machine learning algorithm that clusters data without needing to know how many clusters there should be.
|
||||||
|
|
||||||
|
Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$.
|
||||||
|
|
||||||
|
![dbscan](assets/freqai_dbscan.jpg)
|
||||||
|
|
||||||
|
`FreqAI` uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html) (external website)) with `min_samples` ($N$) taken as 1/4 of the no. of time points in the feature set. `eps` ($\varepsilon$) is computed automatically as the elbow point in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set.
|
52
docs/freqai-parameter-table.md
Normal file
52
docs/freqai-parameter-table.md
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
# Parameter table
|
||||||
|
|
||||||
|
The table below will list all configuration parameters available for `FreqAI`. Some of the parameters are exemplified in `config_examples/config_freqai.example.json`.
|
||||||
|
|
||||||
|
Mandatory parameters are marked as **Required** and have to be set in one of the suggested ways.
|
||||||
|
|
||||||
|
| Parameter | Description |
|
||||||
|
|------------|-------------|
|
||||||
|
| | **General configuration parameters**
|
||||||
|
| `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling `FreqAI`. <br> **Datatype:** Dictionary.
|
||||||
|
| `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer.
|
||||||
|
| `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the `train_period_days` window defined above, and retraining the model during backtesting (more info [here](freqai-running.md#backtesting)). This can be fractional days, but beware that the provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
|
||||||
|
| `identifier` | **Required.** <br> A unique ID for the current model. If models are saved to disk, the `identifier` allows for reloading specific pre-trained models/data. <br> **Datatype:** String.
|
||||||
|
| `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> **Datatype:** Float > 0. <br> Default: 0 (models retrain as often as possible).
|
||||||
|
| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> **Datatype:** Positive integer. <br> Default: 0 (models never expire).
|
||||||
|
| `purge_old_models` | Delete obsolete models. <br> **Datatype:** Boolean. <br> Default: `False` (all historic models remain on disk).
|
||||||
|
| `save_backtest_models` | Save models to disk when running backtesting. Backtesting operates most efficiently by saving the prediction data and reusing them directly for subsequent runs (when you wish to tune entry/exit parameters). Saving backtesting models to disk also allows to use the same model files for starting a dry/live instance with the same model `identifier`. <br> **Datatype:** Boolean. <br> Default: `False` (no models are saved).
|
||||||
|
| `fit_live_predictions_candles` | Number of historical candles to use for computing target (label) statistics from prediction data, instead of from the training dataset (more information can be found [here](freqai-configuration.md#creating-a-dynamic-target-threshold)). <br> **Datatype:** Positive integer.
|
||||||
|
| `follow_mode` | Use a `follower` that will look for models associated with a specific `identifier` and load those for inferencing. A `follower` will **not** train new models. <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||||
|
| `continual_learning` | Use the final state of the most recently trained model as starting point for the new model, allowing for incremental learning (more information can be found [here](freqai-running.md#continual-learning)). <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||||
|
| | **Feature parameters**
|
||||||
|
| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples are shown [here](freqai-feature-engineering.md). <br> **Datatype:** Dictionary.
|
||||||
|
| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for. The list is added as features to the base indicators dataset. <br> **Datatype:** List of timeframes (strings).
|
||||||
|
| `include_corr_pairlist` | A list of correlated coins that `FreqAI` will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](freqai-feature-engineering.md)) will be created for each correlated coin. The correlated coins features are added to the base indicators dataset. <br> **Datatype:** List of assets (strings).
|
||||||
|
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). You can create custom labels and choose whether to make use of this parameter or not. <br> **Datatype:** Positive integer.
|
||||||
|
| `include_shifted_candles` | Add features from previous candles to subsequent candles with the intent of adding historical information. If used, `FreqAI` will duplicate and shift all features from the `include_shifted_candles` previous candles so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer.
|
||||||
|
| `weight_factor` | Weight training data points according to their recency (see details [here](freqai-feature-engineering.md#weighting-features-for-temporal-importance)). <br> **Datatype:** Positive float (typically < 1).
|
||||||
|
| `indicator_max_period_candles` | **No longer used (#7325)**. Replaced by `startup_candle_count` which is set in the [strategy](freqai-configuration.md#building-a-freqai-strategy). `startup_candle_count` is timeframe independent and defines the maximum *period* used in `populate_any_indicators()` for indicator creation. `FreqAI` uses this parameter together with the maximum timeframe in `include_time_frames` to calculate how many data points to download such that the first data point does not include a NaN <br> **Datatype:** Positive integer.
|
||||||
|
| `indicator_periods_candles` | Time periods to calculate indicators for. The indicators are added to the base indicator dataset. <br> **Datatype:** List of positive integers.
|
||||||
|
| `stratify_training_data` | Split the feature set into training and testing datasets. For example, `stratify_training_data: 2` would set every 2nd data point into a separate dataset to be pulled from during training/testing. See details about how it works [here](freqai-running.md#data-stratification-for-training-and-testing-the-model). <br> **Datatype:** Positive integer.
|
||||||
|
| `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean. defaults to `false`.
|
||||||
|
| `plot_feature_importances` | Create a feature importance plot for each model for the top/bottom `plot_feature_importances` number of features.<br> **Datatype:** Integer, defaults to `0`.
|
||||||
|
| `DI_threshold` | Activates the use of the Dissimilarity Index for outlier detection when set to > 0. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di). <br> **Datatype:** Positive float (typically < 1).
|
||||||
|
| `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training dataset, as well as from incoming data points. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean.
|
||||||
|
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](freqai-feature-engineering.md#identifying-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary.
|
||||||
|
| `use_DBSCAN_to_remove_outliers` | Cluster data using the DBSCAN algorithm to identify and remove outliers from training and prediction data. See details about how it works [here](freqai-feature-engineering.md#identifying-outliers-with-dbscan). <br> **Datatype:** Boolean.
|
||||||
|
| `inlier_metric_window` | If set, `FreqAI` adds an `inlier_metric` to the training feature set and set the lookback to be the `inlier_metric_window`, i.e., the number of previous time points to compare the current candle to. Details of how the `inlier_metric` is computed can be found [here](freqai-feature-engineering.md#inlier-metric). <br> **Datatype:** Integer. <br> Default: 0.
|
||||||
|
| `noise_standard_deviation` | If set, `FreqAI` adds noise to the training features with the aim of preventing overfitting. `FreqAI` generates random deviates from a gaussian distribution with a standard deviation of `noise_standard_deviation` and adds them to all data points. `noise_standard_deviation` should be kept relative to the normalized space, i.e., between -1 and 1. In other words, since data in `FreqAI` is always normalized to be between -1 and 1, `noise_standard_deviation: 0.05` would result in 32% of the data being randomly increased/decreased by more than 2.5% (i.e., the percent of data falling within the first standard deviation). <br> **Datatype:** Integer. <br> Default: 0.
|
||||||
|
| `outlier_protection_percentage` | Enable to prevent outlier detection methods from discarding too much data. If more than `outlier_protection_percentage` % of points are detected as outliers by the SVM or DBSCAN, `FreqAI` will log a warning message and ignore outlier detection, i.e., the original dataset will be kept intact. If the outlier protection is triggered, no predictions will be made based on the training dataset. <br> **Datatype:** Float. <br> Default: `30`.
|
||||||
|
| `reverse_train_test_order` | Split the feature dataset (see below) and use the latest data split for training and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, you should be careful to understand the unorthodox nature of this parameter before employing it. <br> **Datatype:** Boolean. <br> Default: `False` (no reversal).
|
||||||
|
| | **Data split parameters**
|
||||||
|
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary.
|
||||||
|
| `test_size` | The fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1.
|
||||||
|
| `shuffle` | Shuffle the training data points during training. Typically, for time-series forecasting, this is set to `False`. <br> **Datatype:** Boolean.
|
||||||
|
| | **Model training parameters**
|
||||||
|
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the selected model library. For example, if you use `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If you select a different model, this dictionary can contain any parameter from that model. <br> **Datatype:** Dictionary.
|
||||||
|
| `n_estimators` | The number of boosted trees to fit in regression. <br> **Datatype:** Integer.
|
||||||
|
| `learning_rate` | Boosting learning rate during regression. <br> **Datatype:** Float.
|
||||||
|
| `n_jobs`, `thread_count`, `task_type` | Set the number of threads for parallel processing and the `task_type` (`gpu` or `cpu`). Different model libraries use different parameter names. <br> **Datatype:** Float.
|
||||||
|
| | **Extraneous parameters**
|
||||||
|
| `keras` | If the selected model makes use of Keras (typical for Tensorflow-based prediction models), this flag needs to be activated so that the model save/loading follows Keras standards. <br> **Datatype:** Boolean. <br> Default: `False`.
|
||||||
|
| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for shifting candles (`include_shifted_candles`) by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. <br> **Datatype:** Integer. <br> Default: 2.
|
173
docs/freqai-running.md
Normal file
173
docs/freqai-running.md
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
# Running FreqAI
|
||||||
|
|
||||||
|
There are two ways to train and deploy an adaptive machine learning model - live deployment and historical backtesting. In both cases, `FreqAI` runs/simulates periodic retraining of models as shown in the following figure:
|
||||||
|
|
||||||
|
![freqai-window](assets/freqai_moving-window.jpg)
|
||||||
|
|
||||||
|
## Live deployments
|
||||||
|
|
||||||
|
FreqAI can be run dry/live using the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor
|
||||||
|
```
|
||||||
|
|
||||||
|
When launched, FreqAI will start training a new model, with a new `identifier`, based on the config settings. Following training, the model will be used to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the coin pairs to try to keep all models equally up to date. FreqAI will always use the most recently trained model to make predictions on incoming live data. If you do not want FreqAI to retrain new models as often as possible, you can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before training a new model. Additionally, you can set `expired_hours` to tell FreqAI to avoid making predictions on models that are older than that number of hours.
|
||||||
|
|
||||||
|
Trained models are by default saved to disk to allow for reuse during backtesting or after a crash. You can opt to [purge old models](#purging-old-model-data) to save disk space by setting `"purge_old_models": true` in the config.
|
||||||
|
|
||||||
|
To start a dry/live run from a saved backtest model (or from a previously crashed dry/live session), you only need to specify the `identifier` of the specific model:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"identifier": "example",
|
||||||
|
"live_retrain_hours": 0.5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this case, although FreqAI will initiate with a pre-trained model, it will still check to see how much time has elapsed since the model was trained. If a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will start training a new model.
|
||||||
|
|
||||||
|
### Automatic data download
|
||||||
|
|
||||||
|
FreqAI automatically downloads the proper amount of data needed to ensure training of a model through the defined `train_period_days` and `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters).
|
||||||
|
|
||||||
|
### Saving prediction data
|
||||||
|
|
||||||
|
All predictions made during the lifetime of a specific `identifier` model are stored in `historical_predictions.pkl` to allow for reloading after a crash or changes made to the config.
|
||||||
|
|
||||||
|
### Purging old model data
|
||||||
|
|
||||||
|
FreqAI stores new model files after each successful training. These files become obsolete as new models are generated to adapt to new market conditions. If you are planning to leave FreqAI running for extended periods of time with high frequency retraining, you should enable `purge_old_models` in the config:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"purge_old_models": true,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will automatically purge all models older than the two most recently trained ones to save disk space.
|
||||||
|
|
||||||
|
## Backtesting
|
||||||
|
|
||||||
|
The FreqAI backtesting module can be executed with the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade backtesting --strategy FreqaiExampleStrategy --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
|
||||||
|
```
|
||||||
|
|
||||||
|
If this command has never been executed with the existing config file, FreqAI will train a new model
|
||||||
|
for each pair, for each backtesting window within the expanded `--timerange`.
|
||||||
|
|
||||||
|
Backtesting mode requires [downloading the necessary data](#downloading-data-to-cover-the-full-backtest-period) before deployment (unlike in dry/live mode where FreqAI handles the data downloading automatically). You should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-size-of-the-sliding-training-window-and-backtesting-duration).
|
||||||
|
|
||||||
|
!!! Note "Model reuse"
|
||||||
|
Once the training is completed, you can execute the backtesting again with the same config file and
|
||||||
|
FreqAI will find the trained models and load them instead of spending time training. This is useful
|
||||||
|
if you want to tweak (or even hyperopt) buy and sell criteria inside the strategy. If you
|
||||||
|
*want* to retrain a new model with the same config file, you should simply change the `identifier`.
|
||||||
|
This way, you can return to using any model you wish by simply specifying the `identifier`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Saving prediction data
|
||||||
|
|
||||||
|
To allow for tweaking your strategy (**not** the features!), FreqAI will automatically save the predictions during backtesting so that they can be reused for future backtests and live runs using the same `identifier` model. This provides a performance enhancement geared towards enabling **high-level hyperopting** of entry/exit criteria.
|
||||||
|
|
||||||
|
An additional directory called `predictions`, which contains all the predictions stored in `hdf` format, will be created in the `unique-id` folder.
|
||||||
|
|
||||||
|
To change your **features**, you **must** set a new `identifier` in the config to signal to `FreqAI` to train new models.
|
||||||
|
|
||||||
|
To save the models generated during a particular backtest so that you can start a live deployment from one of them instead of training a new model, you must set `save_backtest_models` to `True` in the config.
|
||||||
|
|
||||||
|
### Downloading data to cover the full backtest period
|
||||||
|
|
||||||
|
For live/dry deployments, FreqAI will download the necessary data automatically. However, to use backtesting functionality, you need to download the necessary data using `download-data` (details [here](data-download.md#data-downloading)). You need to pay careful attention to understanding how much *additional* data needs to be downloaded to ensure that there is a sufficient amount of training data *before* the start of the backtesting timerange. The amount of additional data can be roughly estimated by moving the start date of the timerange backwards by `train_period_days` and the `startup_candle_count` (see the [parameter table](freqai-parameter-table.md) for detailed descriptions of these parameters) from the beginning of the desired backtesting timerange.
|
||||||
|
|
||||||
|
As an example, to backtest the `--timerange 20210501-20210701` using the [example config](freqai-configuration.md#setting-up-the-configuration-file) which sets `train_period_days` to 30, together with `startup_candle_count: 40` on a maximum `include_timeframes` of 1h, the start date for the downloaded data needs to be `20210501` - 30 days - 40 * 1h / 24 hours = 20210330 (31.7 days earlier than the start of the desired training timerange).
|
||||||
|
|
||||||
|
### Deciding the size of the sliding training window and backtesting duration
|
||||||
|
|
||||||
|
The backtesting timerange is defined with the typical `--timerange` parameter in the configuration file. The duration of the sliding training window is set by `train_period_days`, whilst `backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be
|
||||||
|
a float to indicate sub-daily retraining in live/dry mode). In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file) (found in `config_examples/config_freqai.example.json`), the user is asking FreqAI to use a training period of 30 days and backtest on the subsequent 7 days. After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`. This means that if you set `--timerange 20210501-20210701`, FreqAI will have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks).
|
||||||
|
|
||||||
|
!!! Note
|
||||||
|
Although fractional `backtest_period_days` is allowed, you should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, by setting a `--timerange` of 10 days, and a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it train constantly. In this case, backtesting would take the exact same amount of time as a dry run.
|
||||||
|
|
||||||
|
## Defining model expirations
|
||||||
|
|
||||||
|
During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If you are training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. You can decide to only make trade entries if the model is less than a certain number of hours old by setting the `expiration_hours` in the config file:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"expiration_hours": 0.5,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In the presented example config, the user will only allow predictions on models that are less than 1/2 hours old.
|
||||||
|
|
||||||
|
## Data stratification for training and testing the model
|
||||||
|
|
||||||
|
You can stratify (group) the training/testing data using:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"feature_parameters" : {
|
||||||
|
"stratify_training_data": 3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This will split the data chronologically so that every Xth data point is used to test the model after training. In the example above, the user is asking for every third data point in the dataframe to be used for
|
||||||
|
testing; the other points are used for training.
|
||||||
|
|
||||||
|
The test data is used to evaluate the performance of the model after training. If the test score is high, the model is able to capture the behavior of the data well. If the test score is low, either the model does not capture the complexity of the data, the test data is significantly different from the train data, or a different type of model should be used.
|
||||||
|
|
||||||
|
## Controlling the model learning process
|
||||||
|
|
||||||
|
Model training parameters are unique to the selected machine learning library. FreqAI allows you to set any parameter for any library using the `model_training_parameters` dictionary in the config. The example config (found in `config_examples/config_freqai.example.json`) shows some of the example parameters associated with `Catboost` and `LightGBM`, but you can add any parameters available in those libraries or any other machine learning library you choose to implement.
|
||||||
|
|
||||||
|
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with Scikit-learn's `train_test_split()` function. `train_test_split()` has a parameters called `shuffle` which allows to shuffle the data or keep it unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data. More details about these parameters can be found the [Scikit-learn website](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website).
|
||||||
|
|
||||||
|
The FreqAI specific parameter `label_period_candles` defines the offset (number of candles into the future) used for the `labels`. In the presented [example config](freqai-configuration.md#setting-up-the-configuration-file), the user is asking for `labels` that are 24 candles in the future.
|
||||||
|
|
||||||
|
## Continual learning
|
||||||
|
|
||||||
|
You can choose to adopt a continual learning scheme by setting `"continual_learning": true` in the config. By enabling `continual_learning`, after training an initial model from scratch, subsequent trainings will start from the final model state of the preceding training. This gives the new model a "memory" of the previous state. By default, this is set to `false` which means that all new models are trained from scratch, without input from previous models.
|
||||||
|
|
||||||
|
## Hyperopt
|
||||||
|
|
||||||
|
You can hyperopt using the same command as for [typical Freqtrade hyperopt](hyperopt.md):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
freqtrade hyperopt --hyperopt-loss SharpeHyperOptLoss --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --timerange 20220428-20220507
|
||||||
|
```
|
||||||
|
|
||||||
|
`hyperopt` requires you to have the data pre-downloaded in the same fashion as if you were doing [backtesting](#backtesting). In addition, you must consider some restrictions when trying to hyperopt FreqAI strategies:
|
||||||
|
|
||||||
|
- The `--analyze-per-epoch` hyperopt parameter is not compatible with FreqAI.
|
||||||
|
- It's not possible to hyperopt indicators in the `populate_any_indicators()` function. This means that you cannot optimize model parameters using hyperopt. Apart from this exception, it is possible to optimize all other [spaces](hyperopt.md#running-hyperopt-with-smaller-search-space).
|
||||||
|
- The backtesting instructions also apply to hyperopt.
|
||||||
|
|
||||||
|
The best method for combining hyperopt and FreqAI is to focus on hyperopting entry/exit thresholds/criteria. You need to focus on hyperopting parameters that are not used in your features. For example, you should not try to hyperopt rolling window lengths in the feature creation, or any part of the FreqAI config which changes predictions. In order to efficiently hyperopt the FreqAI strategy, FreqAI stores predictions as dataframes and reuses them. Hence the requirement to hyperopt entry/exit thresholds/criteria only.
|
||||||
|
|
||||||
|
A good example of a hyperoptable parameter in FreqAI is a threshold for the [Dissimilarity Index (DI)](freqai-feature-engineering.md#identifying-outliers-with-the-dissimilarity-index-di) `DI_values` beyond which we consider data points as outliers:
|
||||||
|
|
||||||
|
```python
|
||||||
|
di_max = IntParameter(low=1, high=20, default=10, space='buy', optimize=True, load=True)
|
||||||
|
dataframe['outlier'] = np.where(dataframe['DI_values'] > self.di_max.value/10, 1, 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
This specific hyperopt would help you understand the appropriate `DI_values` for your particular parameter space.
|
||||||
|
|
||||||
|
## Setting up a follower
|
||||||
|
|
||||||
|
You can indicate to the bot that it should not train models, but instead should look for models trained by a leader with a specific `identifier` by defining:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"freqai": {
|
||||||
|
"follow_mode": true,
|
||||||
|
"identifier": "example"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, the user has a leader bot with the `"identifier": "example"`. The leader bot is already running or is launched simultaneously with the follower. The follower will load models created by the leader and inference them to obtain predictions instead of training its own models.
|
785
docs/freqai.md
785
docs/freqai.md
@ -1,797 +1,100 @@
|
|||||||
![freqai-logo](assets/freqai_doc_logo.svg)
|
![freqai-logo](assets/freqai_doc_logo.svg)
|
||||||
|
|
||||||
# FreqAI
|
# `FreqAI`
|
||||||
|
|
||||||
FreqAI is a module designed to automate a variety of tasks associated with training a predictive machine learning model to generate market forecasts given a set of input features.
|
## Introduction
|
||||||
|
|
||||||
|
`FreqAI` is a software designed to automate a variety of tasks associated with training a predictive machine learning model to generate market forecasts given a set of input features.
|
||||||
|
|
||||||
Features include:
|
Features include:
|
||||||
|
|
||||||
* **Self-adaptive retraining**: retrain models during [live deployments](#running-the-model-live) to self-adapt to the market in an unsupervised manner.
|
* **Self-adaptive retraining** - Retrain models during [live deployments](freqai-running.md#live-deployments) to self-adapt to the market in a supervised manner
|
||||||
* **Rapid feature engineering**: create large rich [feature sets](#feature-engineering) (10k+ features) based on simple user-created strategies.
|
* **Rapid feature engineering** - Create large rich [feature sets](freqai-feature-engineering.md#feature-engineering) (10k+ features) based on simple user-created strategies
|
||||||
* **High performance**: adaptive retraining occurs on a separate thread (or on GPU if available) from inferencing and bot trade operations. Newest models and data are kept in memory for rapid inferencing.
|
* **High performance** - Threading allows for adaptive model retraining on a separate thread (or on GPU if available) from model inferencing (prediction) and bot trade operations. Newest models and data are kept in RAM for rapid inferencing
|
||||||
* **Realistic backtesting**: emulate self-adaptive retraining with a [backtesting module](#backtesting) that automates past retraining.
|
* **Realistic backtesting** - Emulate self-adaptive training on historic data with a [backtesting module](freqai-running.md#backtesting) that automates retraining
|
||||||
* **Modifiability**: use the generalized and robust architecture for incorporating any [machine learning library/method](#building-a-custom-prediction-model) available in Python. Eight examples are currently available, including classifiers, regressors, and a convolutional neural network.
|
* **Extensibility** - The generalized and robust architecture allows for incorporating any [machine learning library/method](freqai-configuration.md#using-different-prediction-models) available in Python. Eight examples are currently available, including classifiers, regressors, and a convolutional neural network
|
||||||
* **Smart outlier removal**: remove outliers from training and prediction data sets using a variety of [outlier detection techniques](#outlier-removal).
|
* **Smart outlier removal** - Remove outliers from training and prediction data sets using a variety of [outlier detection techniques](freqai-feature-engineering.md#outlier-detection)
|
||||||
* **Crash resilience**: store model to disk to make reloading from a crash fast and easy, and [purge obsolete files](#purging-old-model-data) for sustained dry/live runs.
|
* **Crash resilience** - Store trained models to disk to make reloading from a crash fast and easy, and [purge obsolete files](freqai-running.md#purging-old-model-data) for sustained dry/live runs
|
||||||
* **Automatic data normalization**: [normalize the data](#feature-normalization) in a smart and statistically safe way.
|
* **Automatic data normalization** - [Normalize the data](freqai-feature-engineering.md#feature-normalization) in a smart and statistically safe way
|
||||||
* **Automatic data download**: compute the data download timerange and update historic data (in live deployments).
|
* **Automatic data download** - Compute timeranges for data downloads and update historic data (in live deployments)
|
||||||
* **Cleaning of incoming data**: handle NaNs safely before training and prediction.
|
* **Cleaning of incoming data** - Handle NaNs safely before training and model inferencing
|
||||||
* **Dimensionality reduction**: reduce the size of the training data via [Principal Component Analysis](#reducing-data-dimensionality-with-principal-component-analysis).
|
* **Dimensionality reduction** - Reduce the size of the training data via [Principal Component Analysis](freqai-feature-engineering.md#data-dimensionality-reduction-with-principal-component-analysis)
|
||||||
* **Deploying bot fleets**: set one bot to train models while a fleet of [follower bots](#setting-up-a-follower) inference the models and handle trades.
|
* **Deploying bot fleets** - Set one bot to train models while a fleet of [follower bots](freqai-running.md#setting-up-a-follower) inference the models and handle trades
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
The easiest way to quickly test FreqAI is to run it in dry mode with the following command
|
The easiest way to quickly test `FreqAI` is to run it in dry mode with the following command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates
|
freqtrade trade --config config_examples/config_freqai.example.json --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates
|
||||||
```
|
```
|
||||||
|
|
||||||
The user will see the boot-up process of automatic data downloading, followed by simultaneous training and trading.
|
You will see the boot-up process of automatic data downloading, followed by simultaneous training and trading.
|
||||||
|
|
||||||
The example strategy, example prediction model, and example config can be found in
|
An example strategy, prediction model, and config to use as a starting points can be found in
|
||||||
`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, and
|
`freqtrade/templates/FreqaiExampleStrategy.py`, `freqtrade/freqai/prediction_models/LightGBMRegressor.py`, and
|
||||||
`config_examples/config_freqai.example.json`, respectively.
|
`config_examples/config_freqai.example.json`, respectively.
|
||||||
|
|
||||||
## General approach
|
## General approach
|
||||||
|
|
||||||
The user provides FreqAI with a set of custom *base* indicators (the same way as in a typical Freqtrade strategy) as well as target values (*labels*).
|
You provide `FreqAI` with a set of custom *base indicators* (the same way as in a [typical Freqtrade strategy](strategy-customization.md)) as well as target values (*labels*). For each pair in the whitelist, `FreqAI` trains a model to predict the target values based on the input of custom indicators. The models are then consistently retrained, with a predetermined frequency, to adapt to market conditions. `FreqAI` offers the ability to both backtest strategies (emulating reality with periodic retraining on historic data) and deploy dry/live runs. In dry/live conditions, `FreqAI` can be set to constant retraining in a background thread to keep models as up to date as possible.
|
||||||
FreqAI trains a model to predict the target values based on the input of custom indicators, for each pair in the whitelist. These models are consistently retrained to adapt to market conditions. FreqAI offers the ability to both backtest strategies (emulating reality with periodic retraining) and deploy dry/live runs. In dry/live conditions, FreqAI can be set to constant retraining in a background thread in an effort to keep models as up to date as possible.
|
|
||||||
|
|
||||||
An overview of the algorithm is shown below, explaining the data processing pipeline and the model usage.
|
An overview of the algorithm, explaining the data processing pipeline and model usage, is shown below.
|
||||||
|
|
||||||
![freqai-algo](assets/freqai_algo.jpg)
|
![freqai-algo](assets/freqai_algo.jpg)
|
||||||
|
|
||||||
### Important machine learning vocabulary
|
### Important machine learning vocabulary
|
||||||
|
|
||||||
**Features** - the quantities with which a model is trained. All features for a single candle is stored as a vector. In FreqAI, the user
|
**Features** - the parameters, based on historic data, on which a model is trained. All features for a single candle is stored as a vector. In `FreqAI`, you build a feature data sets from anything you can construct in the strategy.
|
||||||
builds the feature sets from anything they can construct in the strategy.
|
|
||||||
|
|
||||||
**Labels** - the target values that a model is trained
|
**Labels** - the target values that a model is trained toward. Each feature vector is associated with a single label that is defined by you within the strategy. These labels intentionally look into the future, and are not available to the model during dry/live/backtesting.
|
||||||
toward. Each set of features is associated with a single label that is
|
|
||||||
defined by the user within the strategy. These labels intentionally look into the
|
|
||||||
future, and are not available to the model during dry/live/backtesting.
|
|
||||||
|
|
||||||
**Training** - the process of feeding individual feature sets, composed of historic data, with associated labels into the
|
**Training** - the process of "teaching" the model to match the feature sets to the associated labels. Different types of models "learn" in different ways. More information about the different models can be found [here](freqai-configuration.md#using-different-prediction-models).
|
||||||
model with the goal of matching input feature sets to associated labels.
|
|
||||||
|
|
||||||
**Train data** - a subset of the historic data that is fed to the model during
|
**Train data** - a subset of the feature data set that is fed to the model during training. This data directly influences weight connections in the model.
|
||||||
training. This data directly influences weight connections in the model.
|
|
||||||
|
|
||||||
**Test data** - a subset of the historic data that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model.
|
**Test data** - a subset of the feature data set that is used to evaluate the performance of the model after training. This data does not influence nodal weights within the model.
|
||||||
|
|
||||||
|
**Inferencing** - the process of feeding a trained model new data on which it will make a prediction.
|
||||||
|
|
||||||
## Install prerequisites
|
## Install prerequisites
|
||||||
|
|
||||||
The normal Freqtrade install process will ask the user if they wish to install FreqAI dependencies. The user should reply "yes" to this question if they wish to use FreqAI. If the user did not reply yes, they can manually install these dependencies after the install with:
|
The normal Freqtrade install process will ask if you wish to install `FreqAI` dependencies. You should reply "yes" to this question if you wish to use `FreqAI`. If you did not reply yes, you can manually install these dependencies after the install with:
|
||||||
|
|
||||||
``` bash
|
``` bash
|
||||||
pip install -r requirements-freqai.txt
|
pip install -r requirements-freqai.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
!!! Note
|
!!! Note
|
||||||
Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since Catboost does not provide wheels for this platform.
|
Catboost will not be installed on arm devices (raspberry, Mac M1, ARM based VPS, ...), since it does not provide wheels for this platform.
|
||||||
|
|
||||||
### Usage with docker
|
### Usage with docker
|
||||||
|
|
||||||
For docker users, a dedicated tag with freqAI dependencies is available as `:freqai`.
|
If you are using docker, a dedicated tag with `FreqAI` dependencies is available as `:freqai`. As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`. This image contains the regular `FreqAI` dependencies. Similar to native installs, Catboost will not be available on ARM based devices.
|
||||||
As such - you can replace the image line in your docker-compose file with `image: freqtradeorg/freqtrade:develop_freqai`.
|
|
||||||
This image contains the regular freqAI dependencies. Similar to native installs, Catboost will not be available on ARM based devices.
|
|
||||||
|
|
||||||
## Setting up FreqAI
|
## Common pitfalls
|
||||||
|
|
||||||
### Parameter table
|
`FreqAI` cannot be combined with dynamic `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically).
|
||||||
|
This is for performance reasons - `FreqAI` relies on making quick predictions/retrains. To do this effectively,
|
||||||
The table below will list all configuration parameters available for FreqAI, presented in the same order as `config_examples/config_freqai.example.json`.
|
it needs to download all the training data at the beginning of a dry/live instance. `FreqAI` stores and appends
|
||||||
|
new candles automatically for future retrains. This means that if new pairs arrive later in the dry run due to a volume pairlist, it will not have the data ready. However, `FreqAI` does work with the `ShufflePairlist` or a `VolumePairlist` which keeps the total pairlist constant (but reorders the pairs according to volume).
|
||||||
Mandatory parameters are marked as **Required**, which means that they are required to be set in one of the possible ways.
|
|
||||||
|
|
||||||
| Parameter | Description |
|
|
||||||
|------------|-------------|
|
|
||||||
| | **General configuration parameters**
|
|
||||||
| `freqai` | **Required.** <br> The parent dictionary containing all the parameters for controlling FreqAI. <br> **Datatype:** Dictionary.
|
|
||||||
| `purge_old_models` | Delete obsolete models (otherwise, all historic models will remain on disk). <br> **Datatype:** Boolean. Default: `False`.
|
|
||||||
| `train_period_days` | **Required.** <br> Number of days to use for the training data (width of the sliding window). <br> **Datatype:** Positive integer.
|
|
||||||
| `backtest_period_days` | **Required.** <br> Number of days to inference from the trained model before sliding the window defined above, and retraining the model. This can be fractional days, but beware that the user-provided `timerange` will be divided by this number to yield the number of trainings necessary to complete the backtest. <br> **Datatype:** Float.
|
|
||||||
| `save_backtest_models` | Backtesting operates most efficiently by saving the prediction data and reusing them directly for subsequent runs (when users wish to tune entry/exit parameters). If a user wishes to save models to disk when running backtesting, they should activate `save_backtest_models`. A user may wish to do this if they plan to use the same model files for starting a dry/live instance with the same `identifier`. <br> **Datatype:** Boolean. Default: `False`.
|
|
||||||
| `identifier` | **Required.** <br> A unique name for the current model. This can be reused to reload pre-trained models/data. <br> **Datatype:** String.
|
|
||||||
| `live_retrain_hours` | Frequency of retraining during dry/live runs. <br> Default set to 0, which means the model will retrain as often as possible. <br> **Datatype:** Float > 0.
|
|
||||||
| `expiration_hours` | Avoid making predictions if a model is more than `expiration_hours` old. <br> Defaults set to 0, which means models never expire. <br> **Datatype:** Positive integer.
|
|
||||||
| `fit_live_predictions_candles` | Number of historical candles to use for computing target (label) statistics from prediction data, instead of from the training data set. <br> **Datatype:** Positive integer.
|
|
||||||
| `follow_mode` | If true, this instance of FreqAI will look for models associated with `identifier` and load those for inferencing. A `follower` will **not** train new models. <br> **Datatype:** Boolean. Default: `False`.
|
|
||||||
| `continual_learning` | If true, FreqAI will start training new models from the final state of the most recently trained model. <br> **Datatype:** Boolean. Default: `False`.
|
|
||||||
| | **Feature parameters**
|
|
||||||
| `feature_parameters` | A dictionary containing the parameters used to engineer the feature set. Details and examples are shown [here](#feature-engineering). <br> **Datatype:** Dictionary.
|
|
||||||
| `include_timeframes` | A list of timeframes that all indicators in `populate_any_indicators` will be created for. The list is added as features to the base asset feature set. <br> **Datatype:** List of timeframes (strings).
|
|
||||||
| `include_corr_pairlist` | A list of correlated coins that FreqAI will add as additional features to all `pair_whitelist` coins. All indicators set in `populate_any_indicators` during feature engineering (see details [here](#feature-engineering)) will be created for each coin in this list, and that set of features is added to the base asset feature set. <br> **Datatype:** List of assets (strings).
|
|
||||||
| `label_period_candles` | Number of candles into the future that the labels are created for. This is used in `populate_any_indicators` (see `templates/FreqaiExampleStrategy.py` for detailed usage). The user can create custom labels, making use of this parameter or not. <br> **Datatype:** Positive integer.
|
|
||||||
| `include_shifted_candles` | Add features from previous candles to subsequent candles to add historical information. FreqAI takes all features from the `include_shifted_candles` previous candles, duplicates and shifts them so that the information is available for the subsequent candle. <br> **Datatype:** Positive integer.
|
|
||||||
| `weight_factor` | Used to set weights for training data points according to their recency. See details about how it works [here](#controlling-the-model-learning-process). <br> **Datatype:** Positive float (typically < 1).
|
|
||||||
| `indicator_max_period_candles` | **No longer used**. User must use the strategy set `startup_candle_count` which defines the maximum *period* used in `populate_any_indicators()` for indicator creation (timeframe independent). FreqAI uses this information in combination with the maximum timeframe to calculate how many data points it should download so that the first data point does not have a NaN <br> **Datatype:** positive integer.
|
|
||||||
| `indicator_periods_candles` | Calculate indicators for `indicator_periods_candles` time periods and add them to the feature set. <br> **Datatype:** List of positive integers.
|
|
||||||
| `stratify_training_data` | This value is used to indicate the grouping of the data. For example, 2 would set every 2nd data point into a separate dataset to be pulled from during training/testing. See details about how it works [here](#stratifying-the-data-for-training-and-testing-the-model) <br> **Datatype:** Positive integer.
|
|
||||||
| `principal_component_analysis` | Automatically reduce the dimensionality of the data set using Principal Component Analysis. See details about how it works [here](#reducing-data-dimensionality-with-principal-component-analysis) <br> **Datatype:** Boolean. defaults to `false`.
|
|
||||||
| `plot_feature_importances` | Create a feature importance plot for each model for the top/bottom `plot_feature_importances` number of features.<br> **Datatype:** Integer, defaults to `0`.
|
|
||||||
| `DI_threshold` | Activates the Dissimilarity Index for outlier detection when > 0. See details about how it works [here](#removing-outliers-with-the-dissimilarity-index). <br> **Datatype:** Positive float (typically < 1).
|
|
||||||
| `use_SVM_to_remove_outliers` | Train a support vector machine to detect and remove outliers from the training data set, as well as from incoming data points. See details about how it works [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Boolean.
|
|
||||||
| `svm_params` | All parameters available in Sklearn's `SGDOneClassSVM()`. See details about some select parameters [here](#removing-outliers-using-a-support-vector-machine-svm). <br> **Datatype:** Dictionary.
|
|
||||||
| `use_DBSCAN_to_remove_outliers` | Cluster data using DBSCAN to identify and remove outliers from training and prediction data. See details about how it works [here](#removing-outliers-with-dbscan). <br> **Datatype:** Boolean.
|
|
||||||
| `inlier_metric_window` | If set, FreqAI will add the `inlier_metric` to the training feature set and set the lookback to be the `inlier_metric_window`. Details of how the `inlier_metric` is computed can be found [here](#using-the-inliermetric) <br> **Datatype:** int. Default: 0
|
|
||||||
| `noise_standard_deviation` | If > 0, FreqAI adds noise to the training features. FreqAI generates random deviates from a gaussian distribution with a standard deviation of `noise_standard_deviation` and adds them to all data points. Value should be kept relative to the normalized space between -1 and 1). In other words, since data is always normalized between -1 and 1 in FreqAI, the user can expect a `noise_standard_deviation: 0.05` to see 32% of data randomly increased/decreased by more than 2.5% (i.e. the percent of data falling within the first standard deviation). Good for preventing overfitting. <br> **Datatype:** int. Default: 0
|
|
||||||
| `outlier_protection_percentage` | If more than `outlier_protection_percentage` % of points are detected as outliers by the SVM or DBSCAN, FreqAI will log a warning message and ignore outlier detection while keeping the original dataset intact. If the outlier protection is triggered, no predictions will be made based on the training data. <br> **Datatype:** Float. Default: `30`
|
|
||||||
| `reverse_train_test_order` | If true, FreqAI will train on the latest data split and test on historical split of the data. This allows the model to be trained up to the most recent data point, while avoiding overfitting. However, users should be careful to understand unorthodox nature of this parameter before employing it. <br> **Datatype:** Boolean. Default: False
|
|
||||||
| | **Data split parameters**
|
|
||||||
| `data_split_parameters` | Include any additional parameters available from Scikit-learn `test_train_split()`, which are shown [here](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) (external website). <br> **Datatype:** Dictionary.
|
|
||||||
| `test_size` | Fraction of data that should be used for testing instead of training. <br> **Datatype:** Positive float < 1.
|
|
||||||
| `shuffle` | Shuffle the training data points during training. Typically, for time-series forecasting, this is set to `False`. <br> **Datatype:** Boolean.
|
|
||||||
| | **Model training parameters**
|
|
||||||
| `model_training_parameters` | A flexible dictionary that includes all parameters available by the user selected model library. For example, if the user uses `LightGBMRegressor`, this dictionary can contain any parameter available by the `LightGBMRegressor` [here](https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.LGBMRegressor.html) (external website). If the user selects a different model, this dictionary can contain any parameter from that model. <br> **Datatype:** Dictionary.
|
|
||||||
| `n_estimators` | The number of boosted trees to fit in regression. <br> **Datatype:** Integer.
|
|
||||||
| `learning_rate` | Boosting learning rate during regression. <br> **Datatype:** Float.
|
|
||||||
| `n_jobs`, `thread_count`, `task_type` | Set the number of threads for parallel processing and the `task_type` (`gpu` or `cpu`). Different model libraries use different parameter names. <br> **Datatype:** Float.
|
|
||||||
| | **Extraneous parameters**
|
|
||||||
| `keras` | If your model makes use of Keras (typical for Tensorflow-based prediction models), activate this flag so that the model save/loading follows Keras standards. <br> **Datatype:** Boolean. Default: `False`.
|
|
||||||
| `conv_width` | The width of a convolutional neural network input tensor. This replaces the need for shifting candles (`include_shifted_candles`) by feeding in historical data points as the second dimension of the tensor. Technically, this parameter can also be used for regressors, but it only adds computational overhead and does not change the model training/prediction. <br> **Datatype:** Integer. Default: 2.
|
|
||||||
|
|
||||||
### Important dataframe key patterns
|
|
||||||
|
|
||||||
Below are the values the user can expect to include/use inside a typical strategy dataframe (`df[]`):
|
|
||||||
|
|
||||||
| DataFrame Key | Description |
|
|
||||||
|------------|-------------|
|
|
||||||
| `df['&*']` | Any dataframe column prepended with `&` in `populate_any_indicators()` is treated as a training target (label) inside FreqAI (typically following the naming convention `&-s*`). The names of these dataframe columns are fed back to the user as the predictions. For example, if the user wishes to predict the price change in the next 40 candles (similar to `templates/FreqaiExampleStrategy.py`), they set `df['&-s_close']`. FreqAI makes the predictions and gives them back under the same key (`df['&-s_close']`) to be used in `populate_entry/exit_trend()`. <br> **Datatype:** Depends on the output of the model.
|
|
||||||
| `df['&*_std/mean']` | Standard deviation and mean values of the user-defined labels during training (or live tracking with `fit_live_predictions_candles`). Commonly used to understand the rarity of a prediction (use the z-score as shown in `templates/FreqaiExampleStrategy.py` to evaluate how often a particular prediction was observed during training or historically with `fit_live_predictions_candles`). <br> **Datatype:** Float.
|
|
||||||
| `df['do_predict']` | Indication of an outlier data point. The return value is integer between -1 and 2, which lets the user know if the prediction is trustworthy or not. `do_predict==1` means the prediction is trustworthy. If the Dissimilarity Index (DI, see details [here](#removing-outliers-with-the-dissimilarity-index)) of the input data point is above the user-defined threshold, FreqAI will subtract 1 from `do_predict`, resulting in `do_predict==0`. If `use_SVM_to_remove_outliers()` is active, the Support Vector Machine (SVM) may also detect outliers in training and prediction data. In this case, the SVM will also subtract 1 from `do_predict`. If the input data point was considered an outlier by the SVM but not by the DI, the result will be `do_predict==0`. If both the DI and the SVM considers the input data point to be an outlier, the result will be `do_predict==-1`. A particular case is when `do_predict == 2`, which means that the model has expired due to exceeding `expired_hours`. <br> **Datatype:** Integer between -1 and 2.
|
|
||||||
| `df['DI_values']` | Dissimilarity Index values are proxies to the level of confidence FreqAI has in the prediction. A lower DI means the prediction is close to the training data, i.e., higher prediction confidence. <br> **Datatype:** Float.
|
|
||||||
| `df['%*']` | Any dataframe column prepended with `%` in `populate_any_indicators()` is treated as a training feature. For example, the user can include the RSI in the training feature set (similar to in `templates/FreqaiExampleStrategy.py`) by setting `df['%-rsi']`. See more details on how this is done [here](#feature-engineering). <br> **Note**: Since the number of features prepended with `%` can multiply very quickly (10s of thousands of features is easily engineered using the multiplictative functionality described in the `feature_parameters` table shown above), these features are removed from the dataframe upon return from FreqAI. If the user wishes to keep a particular type of feature for plotting purposes, they can prepend it with `%%`. <br> **Datatype:** Depends on the output of the model.
|
|
||||||
|
|
||||||
### File structure
|
|
||||||
|
|
||||||
`user_data_dir/models/` contains all the data associated with the trainings and backtests.
|
|
||||||
This file structure is heavily controlled and inferenced by the `FreqaiDataKitchen()`
|
|
||||||
and should therefore not be modified.
|
|
||||||
|
|
||||||
### Example config file
|
|
||||||
|
|
||||||
The user interface is isolated to the typical Freqtrade config file. A FreqAI config should include:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"enabled": true,
|
|
||||||
"startup_candles": 10000,
|
|
||||||
"purge_old_models": true,
|
|
||||||
"train_period_days": 30,
|
|
||||||
"backtest_period_days": 7,
|
|
||||||
"identifier" : "unique-id",
|
|
||||||
"feature_parameters" : {
|
|
||||||
"include_timeframes": ["5m","15m","4h"],
|
|
||||||
"include_corr_pairlist": [
|
|
||||||
"ETH/USD",
|
|
||||||
"LINK/USD",
|
|
||||||
"BNB/USD"
|
|
||||||
],
|
|
||||||
"label_period_candles": 24,
|
|
||||||
"include_shifted_candles": 2,
|
|
||||||
"indicator_periods_candles": [10, 20]
|
|
||||||
},
|
|
||||||
"data_split_parameters" : {
|
|
||||||
"test_size": 0.25
|
|
||||||
},
|
|
||||||
"model_training_parameters" : {
|
|
||||||
"n_estimators": 100
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Building a FreqAI strategy
|
|
||||||
|
|
||||||
The FreqAI strategy requires the user to include the following lines of code in the standard Freqtrade strategy:
|
|
||||||
|
|
||||||
```python
|
|
||||||
# user should define the maximum startup candle count (the largest number of candles
|
|
||||||
# passed to any single indicator)
|
|
||||||
startup_candle_count: int = 20
|
|
||||||
|
|
||||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
|
||||||
|
|
||||||
# the model will return all labels created by user in `populate_any_indicators`
|
|
||||||
# (& appended targets), an indication of whether or not the prediction should be accepted,
|
|
||||||
# the target mean/std values for each of the labels created by user in
|
|
||||||
# `populate_any_indicators()` for each training period.
|
|
||||||
|
|
||||||
dataframe = self.freqai.start(dataframe, metadata, self)
|
|
||||||
|
|
||||||
return dataframe
|
|
||||||
|
|
||||||
def populate_any_indicators(
|
|
||||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Function designed to automatically generate, name and merge features
|
|
||||||
from user indicated timeframes in the configuration file. User controls the indicators
|
|
||||||
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
|
||||||
(see convention below). I.e. user should not prepend any supporting metrics
|
|
||||||
(e.g. bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
|
||||||
model.
|
|
||||||
:param pair: pair to be used as informative
|
|
||||||
:param df: strategy dataframe which will receive merges from informatives
|
|
||||||
:param tf: timeframe of the dataframe which will modify the feature names
|
|
||||||
:param informative: the dataframe associated with the informative pair
|
|
||||||
:param coin: the name of the coin which will modify the feature names.
|
|
||||||
"""
|
|
||||||
|
|
||||||
coin = pair.split('/')[0]
|
|
||||||
|
|
||||||
if informative is None:
|
|
||||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
|
||||||
|
|
||||||
# first loop is automatically duplicating indicators for time periods
|
|
||||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
|
||||||
t = int(t)
|
|
||||||
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
|
||||||
|
|
||||||
indicators = [col for col in informative if col.startswith("%")]
|
|
||||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
|
||||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
|
||||||
if n == 0:
|
|
||||||
continue
|
|
||||||
informative_shift = informative[indicators].shift(n)
|
|
||||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
|
||||||
informative = pd.concat((informative, informative_shift), axis=1)
|
|
||||||
|
|
||||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
|
||||||
skip_columns = [
|
|
||||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
|
||||||
]
|
|
||||||
df = df.drop(columns=skip_columns)
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call this
|
|
||||||
# function to populate indicators during training). Notice how we ensure not to
|
|
||||||
# add them multiple times
|
|
||||||
if set_generalized_indicators:
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
|
|
||||||
return df
|
|
||||||
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
Notice how the `populate_any_indicators()` is where the user adds their own features ([more information](#feature-engineering)) and labels ([more information](#setting-classifier-targets)). See a full example at `templates/FreqaiExampleStrategy.py`.
|
|
||||||
|
|
||||||
*Important*: The `self.freqai.start()` function cannot be called outside the `populate_indicators()`.
|
|
||||||
|
|
||||||
### Setting the `startup_candle_count`
|
|
||||||
Users need to take care to set the `startup_candle_count` in their strategy the same way they would for any normal Freqtrade strategy (see details [here](strategy-customization.md#strategy-startup-period)). This value is used by Freqtrade to ensure that a sufficient amount of data is provided when calling on the `dataprovider` to avoid any NaNs at the beginning of the first training. Users can easily set this value by identifying the longest period (in candle units) that they pass to their indicator creation functions (e.g. talib functions). In the present example, the user would pass 20 to as this value (since it is the maximum value in their `indicators_periods_candles`).
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Typically it is best for users to be safe and multiply their expected `startup_candle_count` by 2. There are instances where the talib functions actually require more data than just the passed `period`. Anecdotally, multiplying the `startup_candle_count` by 2 always leads to a fully NaN free training dataset. Look out for this log message to confirm that your data is clean:
|
|
||||||
|
|
||||||
```
|
|
||||||
2022-08-31 15:14:04 - freqtrade.freqai.data_kitchen - INFO - dropped 0 training points due to NaNs in populated dataset 4319.
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Creating a dynamic target
|
|
||||||
|
|
||||||
The `&*_std/mean` return values describe the statistical fit of the user defined label *during the most recent training*. This value allows the user to know the rarity of a given prediction. For example, `templates/FreqaiExampleStrategy.py`, creates a `target_roi` which is based on filtering out predictions that are below a given z-score of 1.25.
|
|
||||||
|
|
||||||
```python
|
|
||||||
dataframe["target_roi"] = dataframe["&-s_close_mean"] + dataframe["&-s_close_std"] * 1.25
|
|
||||||
dataframe["sell_roi"] = dataframe["&-s_close_mean"] - dataframe["&-s_close_std"] * 1.25
|
|
||||||
```
|
|
||||||
|
|
||||||
If the user wishes to consider the population
|
|
||||||
of *historical predictions* for creating the dynamic target instead of the trained labels, (as discussed above) the user
|
|
||||||
can do so by setting `fit_live_prediction_candles` in the config to the number of historical prediction candles
|
|
||||||
the user wishes to use to generate target statistics.
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"fit_live_prediction_candles": 300,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
If the user sets this value, FreqAI will initially use the predictions from the training data
|
|
||||||
and subsequently begin introducing real prediction data as it is generated. FreqAI will save
|
|
||||||
this historical data to be reloaded if the user stops and restarts a model with the same `identifier`.
|
|
||||||
|
|
||||||
## Building a custom prediction model
|
|
||||||
|
|
||||||
FreqAI has multiple example prediction model libraries, such as `Catboost` regression (`freqai/prediction_models/CatboostRegressor.py`) and `LightGBM` regression.
|
|
||||||
However, the user can customize and create their own prediction models using the `IFreqaiModel` class.
|
|
||||||
The user is encouraged to inherit `train()` and `predict()` to let them customize various aspects of their training procedures.
|
|
||||||
|
|
||||||
## Feature engineering
|
|
||||||
|
|
||||||
Features are added by the user inside the `populate_any_indicators()` method of the strategy
|
|
||||||
by prepending indicators with `%`, and labels with `&`.
|
|
||||||
|
|
||||||
There are some important components/structures that the user *must* include when building their feature set; the use of these is shown below:
|
|
||||||
|
|
||||||
```python
|
|
||||||
def populate_any_indicators(
|
|
||||||
self, pair, df, tf, informative=None, set_generalized_indicators=False
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Function designed to automatically generate, name, and merge features
|
|
||||||
from user-indicated timeframes in the configuration file. The user controls the indicators
|
|
||||||
passed to the training/prediction by prepending indicators with `'%-' + coin `
|
|
||||||
(see convention below). I.e., the user should not prepend any supporting metrics
|
|
||||||
(e.g., bb_lowerband below) with % unless they explicitly want to pass that metric to the
|
|
||||||
model.
|
|
||||||
:param pair: pair to be used as informative
|
|
||||||
:param df: strategy dataframe which will receive merges from informatives
|
|
||||||
:param tf: timeframe of the dataframe which will modify the feature names
|
|
||||||
:param informative: the dataframe associated with the informative pair
|
|
||||||
:param coin: the name of the coin which will modify the feature names.
|
|
||||||
"""
|
|
||||||
|
|
||||||
coin = pair.split('/')[0]
|
|
||||||
|
|
||||||
if informative is None:
|
|
||||||
informative = self.dp.get_pair_dataframe(pair, tf)
|
|
||||||
|
|
||||||
# first loop is automatically duplicating indicators for time periods
|
|
||||||
for t in self.freqai_info["feature_parameters"]["indicator_periods_candles"]:
|
|
||||||
t = int(t)
|
|
||||||
informative[f"%-{coin}rsi-period_{t}"] = ta.RSI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{coin}mfi-period_{t}"] = ta.MFI(informative, timeperiod=t)
|
|
||||||
informative[f"%-{coin}adx-period_{t}"] = ta.ADX(informative, window=t)
|
|
||||||
|
|
||||||
bollinger = qtpylib.bollinger_bands(
|
|
||||||
qtpylib.typical_price(informative), window=t, stds=2.2
|
|
||||||
)
|
|
||||||
informative[f"{coin}bb_lowerband-period_{t}"] = bollinger["lower"]
|
|
||||||
informative[f"{coin}bb_middleband-period_{t}"] = bollinger["mid"]
|
|
||||||
informative[f"{coin}bb_upperband-period_{t}"] = bollinger["upper"]
|
|
||||||
|
|
||||||
informative[f"%-{coin}bb_width-period_{t}"] = (
|
|
||||||
informative[f"{coin}bb_upperband-period_{t}"]
|
|
||||||
- informative[f"{coin}bb_lowerband-period_{t}"]
|
|
||||||
) / informative[f"{coin}bb_middleband-period_{t}"]
|
|
||||||
informative[f"%-{coin}close-bb_lower-period_{t}"] = (
|
|
||||||
informative["close"] / informative[f"{coin}bb_lowerband-period_{t}"]
|
|
||||||
)
|
|
||||||
|
|
||||||
informative[f"%-{coin}relative_volume-period_{t}"] = (
|
|
||||||
informative["volume"] / informative["volume"].rolling(t).mean()
|
|
||||||
)
|
|
||||||
|
|
||||||
indicators = [col for col in informative if col.startswith("%")]
|
|
||||||
# This loop duplicates and shifts all indicators to add a sense of recency to data
|
|
||||||
for n in range(self.freqai_info["feature_parameters"]["include_shifted_candles"] + 1):
|
|
||||||
if n == 0:
|
|
||||||
continue
|
|
||||||
informative_shift = informative[indicators].shift(n)
|
|
||||||
informative_shift = informative_shift.add_suffix("_shift-" + str(n))
|
|
||||||
informative = pd.concat((informative, informative_shift), axis=1)
|
|
||||||
|
|
||||||
df = merge_informative_pair(df, informative, self.config["timeframe"], tf, ffill=True)
|
|
||||||
skip_columns = [
|
|
||||||
(s + "_" + tf) for s in ["date", "open", "high", "low", "close", "volume"]
|
|
||||||
]
|
|
||||||
df = df.drop(columns=skip_columns)
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call this
|
|
||||||
# function to populate indicators during training). Notice how we ensure not to
|
|
||||||
# add them multiple times
|
|
||||||
if set_generalized_indicators:
|
|
||||||
df["%-day_of_week"] = (df["date"].dt.dayofweek + 1) / 7
|
|
||||||
df["%-hour_of_day"] = (df["date"].dt.hour + 1) / 25
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
|
|
||||||
return df
|
|
||||||
```
|
|
||||||
|
|
||||||
In the presented example strategy, the user does not wish to pass the `bb_lowerband` as a feature to the model,
|
|
||||||
and has therefore not prepended it with `%`. The user does, however, wish to pass `bb_width` to the
|
|
||||||
model for training/prediction and has therefore prepended it with `%`.
|
|
||||||
|
|
||||||
The `include_timeframes` in the example config above are the timeframes (`tf`) of each call to `populate_any_indicators()` in the strategy. In the present case, the user is asking for the
|
|
||||||
`5m`, `15m`, and `4h` timeframes of the `rsi`, `mfi`, `roc`, and `bb_width` to be included in the feature set.
|
|
||||||
|
|
||||||
The user can ask for each of the defined features to be included also from
|
|
||||||
informative pairs using the `include_corr_pairlist`. This means that the feature
|
|
||||||
set will include all the features from `populate_any_indicators` on all the `include_timeframes` for each of the correlated pairs defined in the config (`ETH/USD`, `LINK/USD`, and `BNB/USD`).
|
|
||||||
|
|
||||||
`include_shifted_candles` indicates the number of previous
|
|
||||||
candles to include in the feature set. For example, `include_shifted_candles: 2` tells
|
|
||||||
FreqAI to include the past 2 candles for each of the features in the feature set.
|
|
||||||
|
|
||||||
In total, the number of features the user of the presented example strat has created is:
|
|
||||||
length of `include_timeframes` * no. features in `populate_any_indicators()` * length of `include_corr_pairlist` * no. `include_shifted_candles` * length of `indicator_periods_candles`
|
|
||||||
$= 3 * 3 * 3 * 2 * 2 = 108$.
|
|
||||||
|
|
||||||
Another structure to consider is the location of the labels at the bottom of the example function (below `if set_generalized_indicators:`).
|
|
||||||
This is where the user will add single features and labels to their feature set to avoid duplication of them from
|
|
||||||
various configuration parameters that multiply the feature set, such as `include_timeframes`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Features **must** be defined in `populate_any_indicators()`. Definining FreqAI features in `populate_indicators()`
|
|
||||||
will cause the algorithm to fail in live/dry mode. If the user wishes to add generalized features that are not associated with
|
|
||||||
a specific pair or timeframe, they should use the following structure inside `populate_any_indicators()`
|
|
||||||
(as exemplified in `freqtrade/templates/FreqaiExampleStrategy.py`):
|
|
||||||
|
|
||||||
```python
|
|
||||||
def populate_any_indicators(self, metadata, pair, df, tf, informative=None, coin="", set_generalized_indicators=False):
|
|
||||||
|
|
||||||
...
|
|
||||||
|
|
||||||
# Add generalized indicators here (because in live, it will call only this function to populate
|
|
||||||
# indicators for retraining). Notice how we ensure not to add them multiple times by associating
|
|
||||||
# these generalized indicators to the basepair/timeframe
|
|
||||||
if set_generalized_indicators:
|
|
||||||
df['%-day_of_week'] = (df["date"].dt.dayofweek + 1) / 7
|
|
||||||
df['%-hour_of_day'] = (df['date'].dt.hour + 1) / 25
|
|
||||||
|
|
||||||
# user adds targets here by prepending them with &- (see convention below)
|
|
||||||
# If user wishes to use multiple targets, a multioutput prediction model
|
|
||||||
# needs to be used such as templates/CatboostPredictionMultiModel.py
|
|
||||||
df["&-s_close"] = (
|
|
||||||
df["close"]
|
|
||||||
.shift(-self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.rolling(self.freqai_info["feature_parameters"]["label_period_candles"])
|
|
||||||
.mean()
|
|
||||||
/ df["close"]
|
|
||||||
- 1
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
(Please see the example script located in `freqtrade/templates/FreqaiExampleStrategy.py` for a full example of `populate_any_indicators()`.)
|
|
||||||
|
|
||||||
## Setting classifier targets
|
|
||||||
|
|
||||||
FreqAI includes the `CatboostClassifier` via the flag `--freqaimodel CatboostClassifier`. The user should take care to set the classes using strings:
|
|
||||||
|
|
||||||
```python
|
|
||||||
df['&s-up_or_down'] = np.where( df["close"].shift(-100) > df["close"], 'up', 'down')
|
|
||||||
```
|
|
||||||
|
|
||||||
Additionally, the example classifier models do not accommodate multiple labels, but they do allow multi-class classification within a single label column.
|
|
||||||
|
|
||||||
## Running FreqAI
|
|
||||||
|
|
||||||
There are two ways to train and deploy an adaptive machine learning model. FreqAI enables live deployment as well as backtesting analyses. In both cases, a model is trained periodically, as shown in the following figure.
|
|
||||||
|
|
||||||
![freqai-window](assets/freqai_moving-window.jpg)
|
|
||||||
|
|
||||||
### Running the model live
|
|
||||||
|
|
||||||
FreqAI can be run dry/live using the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade trade --strategy FreqaiExampleStrategy --config config_freqai.example.json --freqaimodel LightGBMRegressor
|
|
||||||
```
|
|
||||||
|
|
||||||
By default, FreqAI will not find any existing models and will start by training a new one
|
|
||||||
based on the user's configuration settings. Following training, the model will be used to make predictions on incoming candles until a new model is available. New models are typically generated as often as possible, with FreqAI managing an internal queue of the coin pairs to try to keep all models equally up to date. FreqAI will always use the most recently trained model to make predictions on incoming live data. If the user does not want FreqAI to retrain new models as often as possible, they can set `live_retrain_hours` to tell FreqAI to wait at least that number of hours before training a new model. Additionally, the user can set `expired_hours` to tell FreqAI to avoid making predictions on models that are older than that number of hours.
|
|
||||||
|
|
||||||
If the user wishes to start a dry/live run from a saved backtest model (or from a previously crashed dry/live session), the user only needs to reuse
|
|
||||||
the same `identifier` parameter:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"identifier": "example",
|
|
||||||
"live_retrain_hours": 0.5
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In this case, although FreqAI will initiate with a
|
|
||||||
pre-trained model, it will still check to see how much time has elapsed since the model was trained,
|
|
||||||
and if a full `live_retrain_hours` has elapsed since the end of the loaded model, FreqAI will retrain.
|
|
||||||
|
|
||||||
### Backtesting
|
|
||||||
|
|
||||||
The FreqAI backtesting module can be executed with the following command:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade backtesting --strategy FreqaiExampleStrategy --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --freqaimodel LightGBMRegressor --timerange 20210501-20210701
|
|
||||||
```
|
|
||||||
|
|
||||||
Backtesting mode requires the user to have the data [pre-downloaded](#downloading-data-for-backtesting) (unlike in dry/live mode where FreqAI automatically downloads the necessary data). The user should be careful to consider that the time range of the downloaded data is more than the backtesting time range. This is because FreqAI needs data prior to the desired backtesting time range in order to train a model to be ready to make predictions on the first candle of the user-set backtesting time range. More details on how to calculate the data to download can be found [here](#deciding-the-sliding-training-window-and-backtesting-duration).
|
|
||||||
|
|
||||||
If this command has never been executed with the existing config file, it will train a new model
|
|
||||||
for each pair, for each backtesting window within the expanded `--timerange`.
|
|
||||||
|
|
||||||
!!! Note "Model reuse"
|
|
||||||
Once the training is completed, the user can execute the backtesting again with the same config file and
|
|
||||||
FreqAI will find the trained models and load them instead of spending time training. This is useful
|
|
||||||
if the user wants to tweak (or even hyperopt) buy and sell criteria inside the strategy. If the user
|
|
||||||
*wants* to retrain a new model with the same config file, then they should simply change the `identifier`.
|
|
||||||
This way, the user can return to using any model they wish by simply specifying the `identifier`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Hyperopt
|
|
||||||
|
|
||||||
Users can hyperopt using the same command as typical [hyperopt](hyperopt.md):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
freqtrade hyperopt --hyperopt-loss SharpeHyperOptLoss --strategy FreqaiExampleStrategy --freqaimodel LightGBMRegressor --strategy-path freqtrade/templates --config config_examples/config_freqai.example.json --timerange 20220428-20220507
|
|
||||||
```
|
|
||||||
|
|
||||||
Users need to have the data pre-downloaded in the same fashion as if they were doing a FreqAI [backtest](#backtesting). In addition, users must consider some restrictions when trying to [Hyperopt](hyperopt.md) FreqAI strategies:
|
|
||||||
|
|
||||||
- The `--analyze-per-epoch` hyperopt parameter is not compatible with FreqAI.
|
|
||||||
- It's not possible to hyperopt indicators in `populate_any_indicators()` function. This means that the user cannot optimize model parameters using hyperopt. Apart from this exception, it is possible to optimize all other [spaces](hyperopt.md#running-hyperopt-with-smaller-search-space).
|
|
||||||
- The [Backtesting](#backtesting) instructions also apply to Hyperopt.
|
|
||||||
|
|
||||||
The best method for combining hyperopt and FreqAI is to focus on hyperopting entry/exit thresholds/criteria. Users need to focus on hyperopting parameters that are not used in their FreqAI features. For example, users should not try to hyperopt rolling window lengths in their feature creation, or any of their FreqAI config which changes predictions. In order to efficiently hyperopt the FreqAI strategy, FreqAI stores predictions as dataframes and reuses them. Hence the requirement to hyperopt entry/exit thresholds/criteria only.
|
|
||||||
|
|
||||||
A good example of a hyperoptable parameter in FreqAI is a value for `DI_values` beyond which we consider outliers and below which we consider inliers:
|
|
||||||
|
|
||||||
```python
|
|
||||||
di_max = IntParameter(low=1, high=20, default=10, space='buy', optimize=True, load=True)
|
|
||||||
dataframe['outlier'] = np.where(dataframe['DI_values'] > self.di_max.value/10, 1, 0)
|
|
||||||
```
|
|
||||||
|
|
||||||
Which would help the user understand the appropriate Dissimilarity Index values for their particular parameter space.
|
|
||||||
|
|
||||||
### Deciding the size of the sliding training window and backtesting duration
|
|
||||||
|
|
||||||
The user defines the backtesting timerange with the typical `--timerange` parameter in the
|
|
||||||
configuration file. The duration of the sliding training window is set by `train_period_days`, whilst
|
|
||||||
`backtest_period_days` is the sliding backtesting window, both in number of days (`backtest_period_days` can be
|
|
||||||
a float to indicate sub-daily retraining in live/dry mode). In the presented example config,
|
|
||||||
the user is asking FreqAI to use a training period of 30 days and backtest on the subsequent 7 days.
|
|
||||||
This means that if the user sets `--timerange 20210501-20210701`,
|
|
||||||
FreqAI will train have trained 8 separate models at the end of `--timerange` (because the full range comprises 8 weeks). After the training of the model, FreqAI will backtest the subsequent 7 days. The "sliding window" then moves one week forward (emulating FreqAI retraining once per week in live mode) and the new model uses the previous 30 days (including the 7 days used for backtesting by the previous model) to train. This is repeated until the end of `--timerange`.
|
|
||||||
|
|
||||||
!!! Note
|
|
||||||
Although fractional `backtest_period_days` is allowed, the user should be aware that the `--timerange` is divided by this value to determine the number of models that FreqAI will need to train in order to backtest the full range. For example, if the user wants to set a `--timerange` of 10 days, and asks for a `backtest_period_days` of 0.1, FreqAI will need to train 100 models per pair to complete the full backtest. Because of this, a true backtest of FreqAI adaptive training would take a *very* long time. The best way to fully test a model is to run it dry and let it constantly train. In this case, backtesting would take the exact same amount of time as a dry run.
|
|
||||||
|
|
||||||
### Downloading data for backtesting
|
|
||||||
Live/dry instances will download the data automatically for the user, but users who wish to use backtesting functionality still need to download the necessary data using `download-data` (details [here](data-download.md#data-downloading)). FreqAI users need to pay careful attention to understanding how much *additional* data needs to be downloaded to ensure that they have a sufficient amount of training data *before* the start of their backtesting timerange. The amount of additional data can be roughly estimated by moving the start date of the timerange backwards by `train_period_days` and the `startup_candle_count` ([details](#setting-the-startupcandlecount)) from the beginning of the desired backtesting timerange.
|
|
||||||
|
|
||||||
As an example, if we wish to backtest the `--timerange` above of `20210501-20210701`, and we use the example config which sets `train_period_days` to 15. The startup candle count is 40 on a maximum `include_timeframes` of 1h. We would need 20210501 - 15 days - 40 * 1h / 24 hours = 20210414 (16.7 days earlier than the start of the desired training timerange).
|
|
||||||
|
|
||||||
### Defining model expirations
|
|
||||||
|
|
||||||
During dry/live mode, FreqAI trains each coin pair sequentially (on separate threads/GPU from the main Freqtrade bot). This means that there is always an age discrepancy between models. If a user is training on 50 pairs, and each pair requires 5 minutes to train, the oldest model will be over 4 hours old. This may be undesirable if the characteristic time scale (the trade duration target) for a strategy is less than 4 hours. The user can decide to only make trade entries if the model is less than
|
|
||||||
a certain number of hours old by setting the `expiration_hours` in the config file:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"expiration_hours": 0.5,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
In the presented example config, the user will only allow predictions on models that are less than 1/2 hours old.
|
|
||||||
|
|
||||||
### Purging old model data
|
|
||||||
|
|
||||||
FreqAI stores new model files each time it retrains. These files become obsolete as new models are trained and FreqAI adapts to new market conditions. Users planning to leave FreqAI running for extended periods of time with high frequency retraining should enable `purge_old_models` in their config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"purge_old_models": true,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will automatically purge all models older than the two most recently trained ones.
|
|
||||||
|
|
||||||
### Returning additional info from training
|
|
||||||
|
|
||||||
The user may find that there are some important metrics that they'd like to return to the strategy at the end of each model training.
|
|
||||||
The user can include these metrics by assigning them to `dk.data['extra_returns_per_train']['my_new_value'] = XYZ` inside their custom prediction model class. FreqAI takes the `my_new_value` assigned in this dictionary and expands it to fit the return dataframe to the strategy.
|
|
||||||
The user can then use the value in the strategy with `dataframe['my_new_value']`. An example of how this is already used in FreqAI is
|
|
||||||
the `&*_mean` and `&*_std` values, which indicate the mean and standard deviation of the particular target (label) during the most recent training.
|
|
||||||
An example, where the user wants to use live metrics from the trade database, is shown below:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"extra_returns_per_train": {"total_profit": 4}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
The user needs to set the standard dictionary in the config so that FreqAI can return proper dataframe shapes. These values will likely be overridden by the prediction model, but in the case where the model has yet to set them, or needs a default initial value, this is the value that will be returned.
|
|
||||||
|
|
||||||
### Setting up a follower
|
|
||||||
|
|
||||||
The user can define:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"follow_mode": true,
|
|
||||||
"identifier": "example"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
to indicate to the bot that it should not train models, but instead should look for models trained by a leader with the same `identifier`. In this example, the user has a leader bot with the `identifier: "example"`. The leader bot is already running or launching simultaneously as the follower.
|
|
||||||
The follower will load models created by the leader and inference them to obtain predictions.
|
|
||||||
|
|
||||||
## Data manipulation techniques
|
|
||||||
|
|
||||||
### Feature normalization
|
|
||||||
|
|
||||||
The feature set created by the user is automatically normalized to the training data. This includes all test data and unseen prediction data (dry/live/backtest).
|
|
||||||
|
|
||||||
### Reducing data dimensionality with Principal Component Analysis
|
|
||||||
|
|
||||||
Users can reduce the dimensionality of their features by activating the `principal_component_analysis` in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"principal_component_analysis": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will perform PCA on the features and reduce the dimensionality of the data so that the explained variance of the data set is >= 0.999.
|
|
||||||
|
|
||||||
### Stratifying the data for training and testing the model
|
|
||||||
|
|
||||||
The user can stratify (group) the training/testing data using:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"stratify_training_data": 3
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
This will split the data chronologically so that every Xth data point is used to test the model after training. In the
|
|
||||||
example above, the user is asking for every third data point in the dataframe to be used for
|
|
||||||
testing; the other points are used for training.
|
|
||||||
|
|
||||||
The test data is used to evaluate the performance of the model after training. If the test score is high, the model is able to capture the behavior of the data well. If the test score is low, either the model either does not capture the complexity of the data, the test data is significantly different from the train data, or a different model should be used.
|
|
||||||
|
|
||||||
### Using the `inlier_metric`
|
|
||||||
|
|
||||||
The `inlier_metric` is a metric aimed at quantifying how different a prediction data point is from the most recent historic data points.
|
|
||||||
|
|
||||||
User can set `inlier_metric_window` to set the look back window. FreqAI will compute the distance between the present prediction point and each of the previous data points (total of `inlier_metric_window` points).
|
|
||||||
|
|
||||||
This function goes one step further - during training, it computes the `inlier_metric` for all training data points and builds weibull distributions for each each lookback point. The cumulative distribution function for the weibull distribution is used to produce a quantile for each of the data points. The quantiles for each lookback point are averaged to create the `inlier_metric`.
|
|
||||||
|
|
||||||
FreqAI adds this `inlier_metric` score to the training features! In other words, your model is trained to recognize how this temporal inlier metric is related to the user set labels.
|
|
||||||
|
|
||||||
This function does **not** remove outliers from the data set.
|
|
||||||
|
|
||||||
### Controlling the model learning process
|
|
||||||
|
|
||||||
Model training parameters are unique to the machine learning library selected by the user. FreqAI allows the user to set any parameter for any library using the `model_training_parameters` dictionary in the user configuration file. The example configuration file (found in `config_examples/config_freqai.example.json`) show some of the example parameters associated with `Catboost` and `LightGBM`, but the user can add any parameters available in those libraries.
|
|
||||||
|
|
||||||
Data split parameters are defined in `data_split_parameters` which can be any parameters associated with `Sklearn`'s `train_test_split()` function.
|
|
||||||
|
|
||||||
FreqAI includes some additional parameters such as `weight_factor`, which allows the user to weight more recent data more strongly
|
|
||||||
than past data via an exponential function:
|
|
||||||
|
|
||||||
$$ W_i = \exp(\frac{-i}{\alpha*n}) $$
|
|
||||||
|
|
||||||
where $W_i$ is the weight of data point $i$ in a total set of $n$ data points. Below is a figure showing the effect of different weight factors on the data points (candles) in a feature set.
|
|
||||||
|
|
||||||
![weight-factor](assets/freqai_weight-factor.jpg)
|
|
||||||
|
|
||||||
`train_test_split()` has a parameters called `shuffle` that allows the user to keep the data unshuffled. This is particularly useful to avoid biasing training with temporally auto-correlated data.
|
|
||||||
|
|
||||||
Finally, `label_period_candles` defines the offset (number of candles into the future) used for the `labels`. In the presented example config,
|
|
||||||
the user is asking for `labels` that are 24 candles in the future.
|
|
||||||
|
|
||||||
### Outlier removal
|
|
||||||
|
|
||||||
#### Removing outliers with the Dissimilarity Index
|
|
||||||
|
|
||||||
The user can tell FreqAI to remove outlier data points from the training/test data sets using a Dissimilarity Index by including the following statement in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"DI_threshold": 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Equity and crypto markets suffer from a high level of non-patterned noise in the form of outlier data points. The Dissimilarity Index (DI) aims to quantify the uncertainty associated with each prediction made by the model. The DI allows predictions which are outliers (not existent in the model feature space) to be thrown out due to low levels of certainty.
|
|
||||||
|
|
||||||
To do so, FreqAI measures the distance between each training data point (feature vector), $X_{a}$, and all other training data points:
|
|
||||||
|
|
||||||
$$ d_{ab} = \sqrt{\sum_{j=1}^p(X_{a,j}-X_{b,j})^2} $$
|
|
||||||
|
|
||||||
where $d_{ab}$ is the distance between the normalized points $a$ and $b$. $p$ is the number of features, i.e., the length of the vector $X$. The characteristic distance, $\overline{d}$ for a set of training data points is simply the mean of the average distances:
|
|
||||||
|
|
||||||
$$ \overline{d} = \sum_{a=1}^n(\sum_{b=1}^n(d_{ab}/n)/n) $$
|
|
||||||
|
|
||||||
$\overline{d}$ quantifies the spread of the training data, which is compared to the distance between a new prediction feature vectors, $X_k$ and all the training data:
|
|
||||||
|
|
||||||
$$ d_k = \arg \min d_{k,i} $$
|
|
||||||
|
|
||||||
which enables the estimation of the Dissimilarity Index as:
|
|
||||||
|
|
||||||
$$ DI_k = d_k/\overline{d} $$
|
|
||||||
|
|
||||||
The user can tweak the DI through the `DI_threshold` to increase or decrease the extrapolation of the trained model.
|
|
||||||
|
|
||||||
Below is a figure that describes the DI for a 3D data set.
|
|
||||||
|
|
||||||
![DI](assets/freqai_DI.jpg)
|
|
||||||
|
|
||||||
#### Removing outliers using a Support Vector Machine (SVM)
|
|
||||||
|
|
||||||
The user can tell FreqAI to remove outlier data points from the training/test data sets using a SVM by setting:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"use_SVM_to_remove_outliers": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
FreqAI will train an SVM on the training data (or components of it if the user activated
|
|
||||||
`principal_component_analysis`) and remove any data point that the SVM deems to be beyond the feature space.
|
|
||||||
|
|
||||||
The parameter `shuffle` is by default set to `False` to ensure consistent results. If it is set to `True`, running the SVM multiple times on the same data set might result in different outcomes due to `max_iter` being to low for the algorithm to reach the demanded `tol`. Increasing `max_iter` solves this issue but causes the procedure to take longer time.
|
|
||||||
|
|
||||||
The parameter `nu`, *very* broadly, is the amount of data points that should be considered outliers.
|
|
||||||
|
|
||||||
#### Removing outliers with DBSCAN
|
|
||||||
|
|
||||||
The user can configure FreqAI to use DBSCAN to cluster and remove outliers from the training/test data set or incoming outliers from predictions, by activating `use_DBSCAN_to_remove_outliers` in the config:
|
|
||||||
|
|
||||||
```json
|
|
||||||
"freqai": {
|
|
||||||
"feature_parameters" : {
|
|
||||||
"use_DBSCAN_to_remove_outliers": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
DBSCAN is an unsupervised machine learning algorithm that clusters data without needing to know how many clusters there should be.
|
|
||||||
|
|
||||||
Given a number of data points $N$, and a distance $\varepsilon$, DBSCAN clusters the data set by setting all data points that have $N-1$ other data points within a distance of $\varepsilon$ as *core points*. A data point that is within a distance of $\varepsilon$ from a *core point* but that does not have $N-1$ other data points within a distance of $\varepsilon$ from itself is considered an *edge point*. A cluster is then the collection of *core points* and *edge points*. Data points that have no other data points at a distance $<\varepsilon$ are considered outliers. The figure below shows a cluster with $N = 3$.
|
|
||||||
|
|
||||||
![dbscan](assets/freqai_dbscan.jpg)
|
|
||||||
|
|
||||||
FreqAI uses `sklearn.cluster.DBSCAN` (details are available on scikit-learn's webpage [here](#https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html)) with `min_samples` ($N$) taken as 1/4 of the no. of time points in the feature set, and `eps` ($\varepsilon$) taken as the elbow point in the *k-distance graph* computed from the nearest neighbors in the pairwise distances of all data points in the feature set.
|
|
||||||
|
|
||||||
## Additional information
|
|
||||||
|
|
||||||
### Common pitfalls
|
|
||||||
|
|
||||||
FreqAI cannot be combined with dynamic `VolumePairlists` (or any pairlist filter that adds and removes pairs dynamically).
|
|
||||||
This is for performance reasons - FreqAI relies on making quick predictions/retrains. To do this effectively,
|
|
||||||
it needs to download all the training data at the beginning of a dry/live instance. FreqAI stores and appends
|
|
||||||
new candles automatically for future retrains. This means that if new pairs arrive later in the dry run due to a volume pairlist, it will not have the data ready. However, FreqAI does work with the `ShufflePairlist` or a `VolumePairlist` which keeps the total pairlist constant (but reorders the pairs according to volume).
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
FreqAI was developed by a group of individuals who all contributed specific skillsets to the project.
|
`FreqAI` is developed by a group of individuals who all contribute specific skillsets to the project.
|
||||||
|
|
||||||
Conception and software development:
|
Conception and software development:
|
||||||
Robert Caulk @robcaulk
|
Robert Caulk @robcaulk
|
||||||
|
|
||||||
Theoretical brainstorming, data analysis:
|
Theoretical brainstorming and data analysis:
|
||||||
Elin Törnquist @th0rntwig
|
Elin Törnquist @th0rntwig
|
||||||
|
|
||||||
Code review, software architecture brainstorming:
|
Code review and software architecture brainstorming:
|
||||||
@xmatthias
|
@xmatthias
|
||||||
|
|
||||||
|
Software development:
|
||||||
|
Wagner Costa @wagnercosta
|
||||||
|
|
||||||
Beta testing and bug reporting:
|
Beta testing and bug reporting:
|
||||||
@bloodhunter4rc, Salah Lamkadem @ikonx, @ken11o2, @longyu, @paranoidandy, @smidelis, @smarm,
|
Stefan Gehring @bloodhunter4rc, @longyu, Andrew Robert Lawless @paranoidandy, Pascal Schmidt @smidelis, Ryan McMullan @smarmau,
|
||||||
Juha Nykänen @suikula, Wagner Costa @wagnercosta
|
Juha Nykänen @suikula, Johan van der Vlugt @jooopiert, Richárd Józsa @richardjosza
|
||||||
|
@ -23,6 +23,13 @@ nav:
|
|||||||
- Data Downloading: data-download.md
|
- Data Downloading: data-download.md
|
||||||
- Backtesting: backtesting.md
|
- Backtesting: backtesting.md
|
||||||
- Hyperopt: hyperopt.md
|
- Hyperopt: hyperopt.md
|
||||||
|
- FreqAI:
|
||||||
|
- Introduction: freqai.md
|
||||||
|
- Configuration: freqai-configuration.md
|
||||||
|
- Parameter table: freqai-parameter-table.md
|
||||||
|
- Feature engineering: freqai-feature-engineering.md
|
||||||
|
- Running FreqAI: freqai-running.md
|
||||||
|
- Developer guide: freqai-developers.md
|
||||||
- Short / Leverage: leverage.md
|
- Short / Leverage: leverage.md
|
||||||
- Utility Sub-commands: utils.md
|
- Utility Sub-commands: utils.md
|
||||||
- Plotting: plotting.md
|
- Plotting: plotting.md
|
||||||
@ -36,7 +43,6 @@ nav:
|
|||||||
- Advanced Strategy: strategy-advanced.md
|
- Advanced Strategy: strategy-advanced.md
|
||||||
- Advanced Hyperopt: advanced-hyperopt.md
|
- Advanced Hyperopt: advanced-hyperopt.md
|
||||||
- Producer/Consumer mode: producer-consumer.md
|
- Producer/Consumer mode: producer-consumer.md
|
||||||
- FreqAI: freqai.md
|
|
||||||
- Edge Positioning: edge.md
|
- Edge Positioning: edge.md
|
||||||
- Sandbox Testing: sandbox-testing.md
|
- Sandbox Testing: sandbox-testing.md
|
||||||
- FAQ: faq.md
|
- FAQ: faq.md
|
||||||
|
Loading…
Reference in New Issue
Block a user