Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

GeneTrader

> 编程语言
Open source

Genetic Algorithm Optimization for Trading Strategies

199 stars0 likes1 views
WebsiteGitHub

About

Genetic Algorithm Optimization for Trading Strategies

Genetic Algorithm for Trading Strategy Optimization

deepwiki

Background and Objective

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:

  • Enhance trading performance through hyperparameter optimization.
  • Automate strategy evaluation and ranking across large parameter spaces.
  • Provide an efficient and configurable optimization workflow for traders.

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.

Features

  • Genetic algorithm optimization for trading strategies
  • Optimization of strategy parameters and trading pair selection
  • Support for setting maximum open trades
  • Multi-process parallel computation
  • Dynamic strategy generation and evaluation
  • Saving of best individuals from each generation
  • Configurable optimization parameters
  • Optional data downloading before running the algorithm
  • Checkpointing, so a long run can resume after a crash with --resume
  • Walk-forward validation: train each fold on its own window, score it out of sample
  • Selection bar: how good the best of N candidates would have looked by luck alone

Prerequisites

  • Required libraries (specified in requirements.txt)

Installation

  1. Clone the repository:

    bash
    git clone https://github.com/imsatoshi/GeneTrader.git
    cd GeneTrader
  2. Install dependencies:

    bash
    pip install -r requirements.txt
  3. Create a configuration file:

    cp ga.json.example ga.json
  4. Edit ga.json to configure the genetic algorithm parameters and other settings according to your needs.

Configuration

Edit ga.json (or your custom config file) to configure:

Basic Parameters

  • population_size: Number of individuals in each generation
  • generations: Total number of generations to run
  • tournament_size: Number of individuals in tournament selection
  • crossover_prob: Probability of crossover (0.0 to 1.0)
  • mutation_prob: Probability of mutation (0.0 to 1.0)

Parameters for ga optimization

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:

json
{
    // ... other settings ...
    "max_open_trades": 3,
    "timeframe": "5m",
    // ... other settings ...
}

Tips for Parameter Selection:

  • For max_open_trades:

    • Start with a lower value (2-3) for testing
    • Increase gradually based on available capital and risk tolerance
    • Consider exchange limits and liquidity
  • For timeframe:

    • Lower timeframes (1m-5m): Suitable for scalping strategies
    • Medium timeframes (15m-30m): Balance between opportunities and noise
    • Higher timeframes (1h-4h): Better for trend-following strategies

Updating Trading Pairs

You can dynamically update the trading pairs in your configuration using the get_pairs.py script:

bash
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:

  1. Fetch available trading pairs from Binance
  2. Filter out pairs based on a predefined blacklist
  3. Save the pairs to a timestamped JSON file
  4. Automatically update the pair_whitelist in your user_data/config.json

Example usage:

bash
# 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 all

Usage

Run the optimization script with the following command:

bash
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:

  1. Run with default settings:

    bash
    python main.py
  2. Use a custom configuration file:

    bash
    python main.py --config my_custom_config.json
  3. Download data before running the algorithm:

    bash
    python main.py --download
  4. Download data for a specific date range:

    bash
    python main.py --download --start-date 20230101

Project Structure

  • main.py: Main script to run the optimization
  • config/settings.py: Settings class to load and validate configuration
  • utils/: Utility functions for logging and file operations
  • genetic_algorithm/: Individuals, population, crossover, mutation, selection
  • optimization/: GA and Optuna drivers, checkpointing, walk-forward folds
  • strategy/: Backtesting, fitness, template generation, walk-forward, selection bar
  • scripts/: Reporting and maintenance tools (selection_bar.py, get_pairs.py, ...)
  • data/: Data handling, including the downloader module

How It Works

  1. The script loads configuration settings from a JSON file.
  2. It generates a dynamic strategy template and extracts parameters.
  3. If requested, it downloads historical data for backtesting.
  4. The genetic algorithm creates an initial population of trading strategies, or restores the latest checkpoint when --resume is passed.
  5. For each generation:
    • Strategies are evaluated in parallel using backtesting.
    • The best strategies are selected for the next generation.
    • Crossover and mutation operations are applied to create new strategies.
    • The best individual from each generation is saved.
    • A checkpoint is written every checkpoint_frequency generations.
  6. After all generations, the overall best strategy is reported and the checkpoint is cleared.

Resuming an interrupted run

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:

bash
python main.py --config ga.json --resume

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

Walk-forward validation

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.

Contributing

Contributions are welcome! Please submit issues or pull requests.

License

This project is licensed under the MIT License.

Disclaimer

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.

Contact

For questions or suggestions, please open an issue on GitHub.

Community

Optimization Summary

Below is an example of optimization progress over 20 generations: | Generation | Trades | Avg Profit % | Tot Profit % | Win Draw Loss | Drawdown % |

Issues· 1 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Pythonfreqtradefreqtrade-strategiesgenetic-algorithmstrategies

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言