Genetic Algorithms (Trading & Investing Applications)

Contributor Image
Written By
Contributor Image
Written By
Dan Buckley
Dan Buckley is an US-based trader, consultant, and part-time writer with a background in macroeconomics and mathematical finance. He trades and writes about a variety of asset classes, including equities, fixed income, commodities, currencies, and interest rates. As a writer, his goal is to explain trading and finance concepts in levels of detail that could appeal to a range of audiences, from novice traders to those with more experienced backgrounds.
Updated

Genetic algorithms (GAs) are adaptive heuristic search algorithms premised on the evolutionary ideas of natural selection and genetics.

They represent an exploitation of a random search within a defined search space to solve optimization problems.

In trading and investing, GAs have been used in portfolio optimization, trading rule creation, and market prediction models.

 


Key Takeaways – Genetic Algorithms

  • Adaptive Optimization – Genetic algorithms can help in evolving solutions to find optimal trading rules and parameters.
  • Robustness to Market Changes – By simulating natural selection, these algorithms continuously adapt, potentially improving resilience against market volatility, shifts, etc.
  • Diverse Solution Exploration – They explore a wide range of solutions. They avoid local optima to uncover new trading strategies and asset allocations.
  • Coding Example – We provide a coding example toward the end of this article on GAs’ application toward portfolio optimization.

 

1. Standard Genetic Algorithms

Standard genetic algorithms start with a randomly generated population of individuals, each representing a potential solution.

The fitness of each individual, which indicates how good the solution is, is evaluated based on a predefined fitness function.

In trading, this could be the maximization of return or minimization of risk.

The GA then applies operators such as selection, crossover, and mutation to evolve the population toward better solutions.

Application in Trading and Investing

  • Portfolio Optimization – Standard GAs can optimize asset allocation by maximizing return for a given level of risk.
  • Rule-Based Trading Systems – They can evolve sets of trading rules or parameters to maximize profitability based on the data it’s given.

 

2. Multi-Objective Genetic Algorithms (MOGAs)

MOGAs extend the idea of standard GAs by optimizing more than one objective simultaneously.

In the financial context, this could mean maximizing returns while simultaneously minimizing risk and trading costs.

Application in Trading and Investing

  • Efficient Frontier Construction – MOGAs can be used to generate the efficient frontier in portfolio management. This offers a set of optimal portfolios with varying levels of risk and return.
  • Multi-Factor Model Optimization – They can optimize multiple factors in trading models.

 

3. Constrained Genetic Algorithms

Constrained GAs are designed to handle problems with specific constraints.

In trading, these constraints could be risk limits, budget limits, or regulatory requirements that the solutions must adhere to.

Application in Trading and Investing

  • Risk Management – Constrained GAs can optimize portfolios while strictly adhering to risk exposure limits or, e.g., Value-at-Risk (VaR) constraints.
  • Regulatory Compliance – They can ensure that the trading strategies or portfolio allocations comply with industry regulations and restrictions.
  • Real-World Constraints – This could be liquidity, budget, or other factors that have to be factored into the model so the algorithm isn’t suggesting solutions that aren’t feasible.

 

4. Co-Evolutionary Genetic Algorithms

Co-evolutionary GAs involve multiple interacting populations that evolve simultaneously.

This approach can model complex market dynamics where the success of a trading strategy is dependent on the strategies of others.

For example, markets are essentially self-learning in that market participants learn new things over time, which in turn changes the trajectory of future data.

And traders’ actions are the product of the actions of others.

Application in Trading and Investing

 

5. Hybrid Genetic Algorithms

Hybrid GAs combine the principles of genetic algorithms with other optimization techniques, such as neural networks or fuzzy logic.

This combination often results in improved performance by leveraging the strengths of each approach.

Application in Trading and Investing

  • Enhanced Market Prediction Models – Hybrid GAs can combine with neural networks to create market prediction models.
  • Complex Strategy Development – They can develop trading strategies that adapt to market conditions by integrating rule-based systems with predictive models.
  • Combination of Approaches – Develop models for predicting market trends, optimizing investment portfolios, and managing risk by leveraging the strengths of each approach:
    • genetic algorithms for global optimization
    • neural networks for pattern recognition, and
    • fuzzy logic for handling uncertainty and imprecision in financial data

 

6. Particle Swarm Optimization (PSO)

This algorithm is inspired by the social behavior of bird flocking or fish schooling.

Mechanism

In PSO, each “particle” (potential solution) moves within the search space, influenced by its own best-known position and the best-known positions of other particles.

The collective movement of the swarm leads to the discovery of optimal or near-optimal solutions.

Application

PSO is used in optimization problems where a best solution is discovered by moving around in the search space, such as neural network training or function optimization.

 

7. Ant Colony Optimization (ACO)

Based on the foraging behavior of ants, particularly their ability to find the shortest path to food sources.

Mechanism

ACO uses a probabilistic technique for solving computational problems that can be reduced to finding good paths through graphs.

Ants (simulated agents) traverse the graph, depositing pheromones and preferring paths marked by strong pheromone concentrations, and collectively find the optimal path.

Application

ACO’s ability to adapt and discover paths could potentially help design dynamic trade order execution strategies considering factors like liquidity and price impact.

Outside of finance, ACO is effective in routing, network topology optimization, and scheduling problems.

 

8. Evolutionary-Inspired Algorithms

Differential Evolution

It involves mutation and crossover.

Solutions are iteratively improved by combining the differences between randomly selected pairs of solutions from the population, followed by selection to move the population toward the optimal region.

Application

Differential Evolution is used in multidimensional real-valued functions and is often applied in optimization problems.

Evolutionary Programming

Focuses on evolving the structure of the program itself, not just parameter values.

It uses mechanisms like mutation and selection to evolve programs or strategies.

Application

It’s used in symbolic regression, automated programming, and other areas where the structure of the solution is complex and not well-defined.

 

9. Biological-Inspired Algorithms

Bee Algorithm

Mimics the food-foraging behavior of honey bees.

Mechanism

Bees in the algorithm search for solutions and communicate with each other about the quality and location of the food sources (solutions) – favoring areas with better sources while still exploring new areas (i.e., exploration vs. exploitation).

Application

Used for optimization tasks, particularly those requiring a balance between exploration (searching for new solutions) and exploitation (refining existing solutions).

Some forms of algorithmic trading navigate the balance between “exploration” for potentially better strategies and “exploitation” of proven ones, which aims for optimal returns in changing markets.

In other games like chess, it involves exploiting known lines (move orders) versus exploring new ones where better solutions could potentially be found.

Based on the brood parasitism of cuckoo species by laying eggs in the nests of other host birds.

Mechanism

Each cuckoo lays one egg (new solution) and dumps it in a randomly chosen nest (existing solution).

The best nests with high-quality eggs (good solutions) carry over to the next generations.

Application

Effective in global optimization problems, especially with heavy-tailed distributions.

 

10. Physical-Inspired Algorithms

Firefly Algorithm

Imitates the flashing behavior of fireflies.

Mechanism

The attractiveness of a firefly is proportional to its brightness, and less bright ones will move towards brighter ones, thus exploring and exploiting the search space.

Application

Works well in multimodal optimization problems where the goal is to find multiple solutions.

For example, if a company wants to have multiple good solutions to a project it’s considering, then multimodal optimization would be a consideration.

Gravitational Search Algorithm

Based on the law of gravity and mass interactions.

Mechanism

Every agent is considered as an object with mass, and objects with heavier masses (better solutions) attract others.

Over time, agents move toward the heaviest mass, leading to convergence on optimal solutions.

Application

Useful in systems where the collective behavior of simple agents leads to complex behavior, like resource allocation and clustering.

 

11. Social-Inspired Algorithms

Bacterial Foraging Optimization

Mimics the foraging behavior of bacteria.

Mechanism

Bacteria move via chemotaxis, swimming or tumbling, attracted by nutrients (better solutions) and repelled by noxious substances.

They also communicate with each other through signaling, which leads to complex swarm dynamics.

Application

It’s used in optimization problems, especially those involving multiple agents and dynamic environments.

Social Spider Optimization

Based on the cooperative behavior of social spiders.

Mechanism

Spiders communicate via vibrations on their web, which attracts each other toward prey or potential mates.

This leads to a collective behavior where individual and group strategies are aligned.

Application

Suitable for problems where the solution involves cooperative strategies or dynamic changes in the environment.

 

Coding Example – Genetic Algorithm in Finance

As we’ve used in other articles, let’s say we wanted to optimize this portfolio among these 4 assets given this information:

  • Stocks: +6% forward return, 15% annualized volatility using standard deviation
  • Bonds: +4% forward return, 10% annualized volatility using standard deviation
  • Commodities: +3% forward return, 15% annualized volatility using standard deviation
  • Gold: +3% forward return, 15% annualized volatility using standard deviation

We’ll provide a conceptual approach to how you might use a genetic algorithm to optimize the given portfolio based on the specified forward returns and volatilities for stocks, bonds, commodities, and gold.

The goal could be to maximize the portfolio’s expected return for a given level of risk (e.g., targeting a specific portfolio volatility) or to maximize the Sharpe ratio, which balances the expected return against volatility.

Here’s an outline of how you could approach this with a genetic algorithm:

Define the fitness function

This could be the Sharpe ratio, where you calculate the expected return of the portfolio (weighted sum of the assets’ returns) divided by the portfolio’s standard deviation (considering the assets’ volatilities and assuming some correlation structure, or simplifying to treat assets as uncorrelated for an initial approach).

Initialize your population

Start with a set of randomly generated portfolios (where each portfolio is a set of weights representing the allocation to each asset).

Ensure that each portfolio’s weights sum to 1.

Selection

Evaluate each portfolio in the population using the fitness function.

Select the top-performing portfolios to breed a new generation.

Crossover (breeding)

Combine the selected portfolios to create new portfolios.

For example, you might take half the weights from one parent portfolio and half from another, or mix them in some proportion.

Mutation

Introduce random changes to the portfolio weights of the new generation to explore a wider solution space and prevent premature convergence on suboptimal solutions.

Repeat

Iterate through the selection, crossover, and mutation steps for several generations, aiming to improve the overall fitness of the population with each generation.

Convergence

Continue iterating until you reach a stopping criterion, such as a maximum number of generations or a plateau in fitness improvement across generations.

Solution

The best-performing portfolio at the end of the process is your optimized allocation.

Coding

For the given portfolio with specified returns and volatilities, the fitness function would directly incorporate these values to calculate the expected return and volatility of each potential solution (portfolio) generated by the genetic algorithm.

This approach provides a framework for applying a genetic algorithm to portfolio optimization.

Implementing this in Python would require utilizing libraries such as NumPy for numerical operations and potentially could look into existing GA libraries for more sophisticated genetic algorithm functionalities.

import numpy as np

# Asset information: expected returns and volatilities
returns = np.array([0.06, 0.04, 0.03, 0.03])
volatilities = np.array([0.15, 0.10, 0.15, 0.15])

# Initialize parameters
population_size = 50
num_assets = len(returns)
num_generations = 100
selection_size = 10
mutation_rate = 0.1

# Initialize population
np.random.seed(19)
population = np.random.dirichlet(alpha=np.ones(num_assets), size=population_size)

# Define fitness function: Sharpe ratio
def sharpe_ratio(weights):
    portfolio_return = np.sum(weights * returns)
    portfolio_volatility = np.sqrt(np.dot(weights**2, volatilities**2)) # Simplified calculation
    return portfolio_return / portfolio_volatility

# Genetic Algorithm
for generation in range(num_generations):
    # Evaluate fitness
    fitness_scores = np.array([sharpe_ratio(individual) for individual in population])

    # Selection
    selected_indices = np.argsort(fitness_scores)[-selection_size:]
    mating_pool = population[selected_indices]

    # Crossover
    offspring = []
    for _ in range(int(population_size / 2)):
        parents = np.random.choice(range(selection_size), size=2, replace=False)
        cross_point = np.random.randint(1, num_assets)
        child1 = np.concatenate([mating_pool[parents[0], :cross_point], mating_pool[parents[1], cross_point:]])
        child2 = np.concatenate([mating_pool[parents[1], :cross_point], mating_pool[parents[0], cross_point:]])
        offspring.extend([child1, child2])
    offspring = np.array(offspring)

    # Mutation
    for i in range(population_size):
        if np.random.rand() < mutation_rate:
        mutation_point = np.random.randint(num_assets)
        offspring[i, mutation_point] = np.random.rand()

    # Normalize weights to sum to 1
    offspring = np.array([child / np.sum(child) for child in offspring])

# Next generation
population = offspring

# Identify best solution
best_index = np.argmax([sharpe_ratio(individual) for individual in population])
best_portfolio = population[best_index]

print("Optimal Portfolio Allocation:", best_portfolio)

Results

The simulated result for the optimal portfolio allocation, as determined by the genetic algorithm based on maximizing the Sharpe ratio with the given asset characteristics, is approximately:

  • Stocks: 8.2%
  • Bonds: 52.7%
  • Commodities: 23.1%
  • Gold: 16.0%

This allocation suggests a diversified strategy, with a significant emphasis on bonds. It aims to balance expected returns against volatility within the portfolio’s constraints.

The actual implementation of the genetic algorithm might yield different results based on the specific parameters and evolutionary process used.

Real-world applications would likely incorporate additional considerations, such as transaction costs, market impact, constraints on individual asset weights, and correlations between asset returns.

 

Conclusion

Genetic algorithms offer a flexible framework for solving complex optimization problems in trading and investing.

Their ability to adapt and evolve solutions makes them particularly suited for dynamic, self-learning situations.

As with any trading system, the effectiveness of GAs depends on their design, the quality of data, and the thoroughness of backtesting to avoid overfitting.

Properly applied, GAs can significantly enhance decision-making processes in trading and investment strategies.

 

 

Article Sources

  • https://iopscience.iop.org/article/10.1088/1469-7688/1/4/301/meta
  • https://books.google.com/books?hl=en&lr=&id=qN3cBwAAQBAJ&oi=fnd&pg=PR15&dq=genetic+algorithm&ots=nF9Trw9O5a&sig=Jniri605MifDE-Za3Ba7669tPD0

The writing and editorial team at DayTrading.com use credible sources to support their work. These include government agencies, white papers, research institutes, and engagement with industry professionals. Content is written free from bias and is fact-checked where appropriate. Learn more about why you can trust DayTrading.com