
AgFox
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.
Most Liked

Archer
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).
Popular Prag Prog topics










Other popular topics










Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /rust
- /wasm
- /ruby
- /erlang
- /phoenix
- /keyboards
- /js
- /rails
- /python
- /security
- /go
- /swift
- /vim
- /clojure
- /java
- /haskell
- /emacs
- /svelte
- /onivim
- /typescript
- /crystal
- /c-plus-plus
- /tailwind
- /kotlin
- /gleam
- /react
- /flutter
- /elm
- /ocaml
- /vscode
- /opensuse
- /ash
- /centos
- /php
- /deepseek
- /zig
- /scala
- /html
- /debian
- /nixos
- /lisp
- /agda
- /sublime-text
- /textmate
- /react-native
- /kubuntu
- /arch-linux
- /ubuntu
- /revery
- /manjaro
- /spring
- /django
- /diversity
- /nodejs
- /lua
- /julia
- /slackware
- /c
- /neovim