Metadata-Version: 2.5
Name: strategy-genome
Version: 0.1.0
Summary: Typed genetic-algorithm / genetic-programming optimizer (NSGA-II, island model, adaptive operators) with an Optuna sampler. Carved out of srfm-lab.
Project-URL: Homepage, https://github.com/Mattbusel/strategy-genome
Project-URL: Repository, https://github.com/Mattbusel/strategy-genome
Project-URL: Documentation, https://github.com/Mattbusel/strategy-genome/tree/main/docs
Project-URL: Changelog, https://github.com/Mattbusel/strategy-genome/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/Mattbusel/strategy-genome/issues
Project-URL: Upstream (srfm-lab), https://github.com/Mattbusel/srfm-lab
Author: Matthew Busel
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
Keywords: evolutionary-algorithm,freqtrade,genetic-algorithm,genetic-programming,hyperopt,hyperparameter-optimization,multi-objective-optimization,nsga-ii,optuna,quantitative-finance,sampler,trading-strategy
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.22
Provides-Extra: optuna
Requires-Dist: optuna>=3.4; extra == 'optuna'
Provides-Extra: scipy
Requires-Dist: scipy>=1.8; extra == 'scipy'
Provides-Extra: test
Requires-Dist: optuna>=3.4; extra == 'test'
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# strategy-genome

A typed genetic algorithm (GA) and genetic programming (GP) optimizer for
Python, with an Optuna sampler so any Optuna study can use it.

- **You bring the fitness function.** `evolve(fitness, space)` calls
  `fitness(genome)` and expects a float, or a tuple of floats for
  multi-objective runs. Nothing about trading is built in.
- **Mixed search spaces:** floats (optionally on a step grid), integers,
  log-scale floats, categoricals and booleans.
- **Real GA machinery:** elitism, tournament selection, SBX / arithmetic /
  uniform / one- and two-point crossover, gaussian / polynomial / creep /
  boundary mutation, adaptive mutation rate and adaptive operator choice,
  NSGA-II for multiple objectives, an island model, stagnation restarts, and a
  hall of fame.
- **Reproducible:** the same seed and the same fitness give the same run.
- **Light:** the GA core is pure standard-library Python. numpy is used by
  the GP submodule and the trading examples. Optuna is an optional extra.

Carved out of [srfm-lab](https://github.com/Mattbusel/srfm-lab)
(`ml/genetic`), MIT licensed. See [provenance](https://github.com/Mattbusel/strategy-genome/blob/main/docs/provenance.md) for what was
changed and which upstream bugs were fixed on the way out.

## Install

```bash
pip install strategy-genome            # GA core + GP (numpy)
pip install "strategy-genome[optuna]"  # adds the Optuna sampler
```

Python 3.10 or newer.

## Quickstart

```python
from strategy_genome import evolve, space as sp

def fitness(g):
    # g["name"] reads one parameter; g.params is the whole dict
    return (g["x"] - 3.0) ** 2 + (g["y"] + 1.0) ** 2

result = evolve(
    fitness,
    {"x": sp.Float(-10, 10), "y": sp.Float(-10, 10)},
    population=40,
    generations=80,
    seed=7,
    direction="minimize",
)

result.best_params        # {'x': 3.00..., 'y': -0.99...}
result.best_value         # what your function returned for the best genome
result.hall_of_fame       # best unique genomes seen, best first
result.diversity_history  # mean pairwise parameter distance per generation
```

### Search spaces

```python
space = {
    "fast":  sp.Int(2, 50),
    "slow":  sp.Int(10, 200, step=5),
    "stop":  sp.Float(0.005, 0.10),
    "lr":    sp.LogFloat(1e-5, 1e-1),
    "kind":  sp.Categorical(["ema", "sma", "wma"]),
    "short": sp.Bool(),
}
```

Shorthand also works: `(0, 10)` is an integer range, `(0.0, 1.0)` a float
range, and a list is a categorical.

### Several objectives

Return a tuple and give one direction per objective. The run switches to
NSGA-II and `result.pareto_front` holds the non-dominated genomes.

```python
def fitness(g):
    returns = backtest(g.params)
    return sharpe(returns), max_drawdown(returns)

result = evolve(fitness, space, population=60, generations=100, seed=1,
                directions=["maximize", "minimize"])
for g in result.pareto_front:
    print(g.values, g.params)
```

### Failures

If `fitness` raises or returns NaN, that genome scores `-inf` and the run
continues. `result.n_failed_evaluations` counts them. Pass
`raise_errors=True` to stop on the first error instead.

## Use it from Optuna (and freqtrade)

```python
import optuna
from strategy_genome.optuna import GeneticStrategySampler

study = optuna.create_study(sampler=GeneticStrategySampler(population_size=30, seed=1))
study.optimize(objective, n_trials=500)
```

freqtrade's hyperopt runs on Optuna and lets a strategy return any
`optuna.samplers.BaseSampler` from `HyperOpt.generate_estimator`, so the
sampler drops straight in. See [Optuna and freqtrade](https://github.com/Mattbusel/strategy-genome/blob/main/docs/optuna-and-freqtrade.md),
including a benchmark against Random, NSGA-II and TPE.

## More

- [API reference](https://github.com/Mattbusel/strategy-genome/blob/main/docs/api.md)
- [Optuna and freqtrade](https://github.com/Mattbusel/strategy-genome/blob/main/docs/optuna-and-freqtrade.md)
- [Genetic programming (`strategy_genome.gp`)](https://github.com/Mattbusel/strategy-genome/blob/main/docs/gp.md)
- [Trading examples (`strategy_genome.trading`)](https://github.com/Mattbusel/strategy-genome/blob/main/docs/trading-examples.md)
- [Provenance and upstream fixes](https://github.com/Mattbusel/strategy-genome/blob/main/docs/provenance.md)
- [Ecosystem plan (OptunaHub)](https://github.com/Mattbusel/strategy-genome/blob/main/docs/ecosystem.md)
- Examples: [`examples/`](https://github.com/Mattbusel/strategy-genome/tree/main/examples)

## License

MIT. Copyright (c) 2026 Matthew Busel. See `LICENSE` and `NOTICE`.
