Genetic Algorithm Optimization for Trading Strategies
Genetic Algorithm Optimization for Trading Strategies
Automated trading strategies face challenges in optimizing performance due to chaotic and non-stationary market dynamics. This project implements a Genetic Algorithm (GA) to optimize trading strategy parameters and trading pair selection, offering a more robust and adaptive solution compared to conventional methods. By integrating GA with the Freqtrade framework, I aim to:
Scope: this project searches for strategy parameters and reports what it finds. It does not place trades and does not deploy anything to a live bot — taking a candidate to production is a manual step outside this repository.
This project leverage GA to explore parameter spaces and improve profitability.
This project implements a genetic algorithm to optimize trading strategy parameters and trading pair selection. It supports multi-process parallel computation, dynamic generation of strategies, and saving the best strategy from each generation.
--resumeClone the repository:
git clone https://github.com/imsatoshi/GeneTrader.git
cd GeneTraderInstall dependencies:
pip install -r requirements.txtCreate a configuration file:
cp ga.json.example ga.jsonEdit ga.json to configure the genetic algorithm parameters and other settings according to your needs.
Edit ga.json (or your custom config file) to configure:
population_size: Number of individuals in each generationgenerations: Total number of generations to runtournament_size: Number of individuals in tournament selectioncrossover_prob: Probability of crossover (0.0 to 1.0)mutation_prob: Probability of mutation (0.0 to 1.0)| Parameter Name | Description |
|---|---|
proxy |
Proxy settings, including addresses for HTTP and SOCKS5 proxies. |
freqtrade_path |
Path to the freqtrade executable. |
strategy_dir |
Directory where strategy files are located. |
user_dir |
User data directory. |
data_dir |
Data storage directory, typically used for market data. |
results_dir |
Results storage directory, used for storing backtest results, etc. |
config_file |
Path to the configuration file. |
population_size |
Size of the population in the genetic algorithm. |
generations |
Number of generations in the genetic algorithm. |
crossover_prob |
Probability of crossover in the genetic algorithm. |
mutation_prob |
Probability of mutation in the genetic algorithm. |
backtest_timerange_weeks |
Time range for backtesting, in weeks. |
tournament_size |
Size of the tournament selection in the genetic algorithm. |
pool_processes |
Number of processes for parallel processing. |
max_retries |
Maximum number of retries. |
retry_delay |
Delay time between retries. |
add_max_open_trades |
Whether to add a limit on the maximum number of open trades. |
add_dynamic_timeframes |
Whether to add dynamic timeframes. |
checkpoint_frequency |
Frequency of saving checkpoints. |
project_dir |
Project directory. |
best_generations_dir |
Directory for storing the best generations. |
base_strategy_file |
Path to the base strategy file. |
fix_pairs |
Whether to fix trading pairs. |
num_pairs |
Number of trading pairs. |
diversity_threshold |
Diversity threshold for controlling population diversity. |
max_mutation_prob |
Maximum mutation probability. |
local_file |
Name of the local configuration file. |
hostname |
Hostname or IP address of the remote server. |
username |
Username for the remote server. |
port |
SSH port of the remote server. |
key_path |
Path to the SSH key file. |
bark_endpoint |
Endpoint URL for the Bark service. |
bark_key |
Key for the Bark service. |
remote_datadir |
Data directory on the remote server. |
remote_strategydir |
Strategy directory on the remote server. |
api_url |
URL of the API. |
freqtrade_username |
Username for Freqtrade. |
freqtrade_password |
Password for Freqtrade. |
Note: The proxy setting is used when configuring a VPN. Ensure that the proxy settings include the necessary addresses for HTTP and SOCKS5 proxies to route traffic through the VPN.
Example configuration:
{
// ... other settings ...
"max_open_trades": 3,
"timeframe": "5m",
// ... other settings ...
}Tips for Parameter Selection:
For max_open_trades:
For timeframe:
You can dynamically update the trading pairs in your configuration using the get_pairs.py script:
python scripts/get_pairs.py [--mode {volume,all}]Options:
--mode volume: Get top 100 pairs sorted by USDT trading volume--mode all: Get all available USDT trading pairs (default)The script will:
user_data/config.jsonExample usage:
# Get top 100 pairs by trading volume
python scripts/get_pairs.py --mode volume
# Get all available USDT pairs
python scripts/get_pairs.py --mode allRun the optimization script with the following command:
python main.py [options]Available options:
--config CONFIG_FILE: Specify a custom configuration file (default is 'ga.json')--download: Download data before running the algorithm--start-date YYYYMMDD: Start date for data download (default is '20240101')Examples:
Run with default settings:
python main.pyUse a custom configuration file:
python main.py --config my_custom_config.jsonDownload data before running the algorithm:
python main.py --downloadDownload data for a specific date range:
python main.py --download --start-date 20230101main.py: Main script to run the optimizationconfig/settings.py: Settings class to load and validate configurationutils/: Utility functions for logging and file operationsgenetic_algorithm/: Individuals, population, crossover, mutation, selectionoptimization/: GA and Optuna drivers, checkpointing, walk-forward foldsstrategy/: Backtesting, fitness, template generation, walk-forward, selection barscripts/: Reporting and maintenance tools (selection_bar.py, get_pairs.py, ...)data/: Data handling, including the downloader module--resume is passed.checkpoint_frequency generations.A long optimization run writes its population, generation counter, best
individual, and RNG state to checkpoint_dir. If the run is killed, restart it
with the same config and add --resume:
python main.py --config ga.json --resumeThe checkpoint is discarded when a run completes, and ignored if
population_size changed. --resume applies to the genetic optimizer only;
Optuna runs always start fresh.
Set enable_walk_forward: true to train each fold on its own historical window
and score it on the following out-of-sample window, instead of optimizing
against one recent window. This is slower — each fold runs a full GA — but it is
the only guard here against fitting the most recent noise.
Contributions are welcome! Please submit issues or pull requests.
This project is licensed under the MIT License.
This project is for educational and research purposes only. It does not constitute investment advice. Users are responsible for any risks associated with using this project for actual trading.
For questions or suggestions, please open an issue on GitHub.
Below is an example of optimization progress over 20 generations: | Generation | Trades | Avg Profit % | Tot Profit % | Win Draw Loss | Drawdown % |
No open issues yet, or sync has not completed.