# Genetic Algorithms in Elixir: Ch 4 portfolio example pp66

**URL:** <https://forum.devtalk.com/t/genetic-algorithms-in-elixir-ch-4-portfolio-example-pp66/3902>\
**Category:** PragProg Customers\
**Tags:** suggestion, book-genetic-algorithms-in-elixir\
**Created:** [10 November 2020 08:44 UTC](https://forum.devtalk.com/t/genetic-algorithms-in-elixir-ch-4-portfolio-example-pp66/3902 "2020-11-10T08:44:24Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![AgFox](https://forum.devtalk.com/user_avatar/forum.devtalk.com/agfox/32/2525_2.png) [@AgFox](https://forum.devtalk.com/u/AgFox)\
**Post date:** [10 November 2020 08:44 UTC](https://forum.devtalk.com/t/genetic-algorithms-in-elixir-ch-4-portfolio-example-pp66/3902/1 "2020-11-10T08:44:24Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Archer](https://forum.devtalk.com/user_avatar/forum.devtalk.com/archer/32/1174_2.png) [@Archer](https://forum.devtalk.com/u/Archer)\
**Post date:** [10 November 2020 22:01 UTC](https://forum.devtalk.com/t/genetic-algorithms-in-elixir-ch-4-portfolio-example-pp66/3902/2 "2020-11-10T22:01:55Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![seanmor5](https://forum.devtalk.com/user_avatar/forum.devtalk.com/seanmor5/32/1169_2.png) [@seanmor5](https://forum.devtalk.com/u/seanmor5)\
**Post date:** [18 November 2020 21:43 UTC](https://forum.devtalk.com/t/genetic-algorithms-in-elixir-ch-4-portfolio-example-pp66/3902/3 "2020-11-18T21:43:49Z")

</div>

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.
