Genetic Algorithms in Elixir: Ch 4 portfolio example pp66

The average stock in a portfolio will have ROI of 5 and RISK of 5 (:rand.uniform(10)) and a portfolio size of 100 stocks.

This would give a weighted sum of 2 * ROI - RISK * 100, or an average fitness for each Chromosome portfolio of 500.

A terminate function that checks for a portfolio fitness of exactly 20 is probably going to find one, but there will be many, more profitable portfolios, that will be missed.

If the portfolio size is reduced to 10 stocks (max fitness 190), then a terminate that checks for fitness >180 should find a suitable candidate.

The terminate code should also be changed to

Enum.max_by(population, &Portfolio.fitness_fn/1).fitness > my limit

Important to add the check on the fitness attribute.

1 Like

Also since genetic.ex is already doing the sort by fitness why not stick with
def terminate?(population, _generation, _temperature),
do: hd(population).fitness > @target_fitness

For me a portfolio with @target_fitness 1600 was easily found with an age between 800-1100 on average.

also by this point in the book my terminate?() callback specification has three arguments, but book only shows two (missing _temperature).

1 Like

Hey thanks for pointing these out! I just updated the example in the book. Also, there’s a small blurb in the same chapter about how evolve will only take on generations after that chapter. I didn’t make that very clear, and you’re not the only one who was confused by that. I need to update that.