Esempio n. 1
0
def test_get_all_and_random_organisms():
    organisms = population.get_all_organisms()
    assert isinstance(organisms, Iterable)

    organisms = list(organisms)

    for organism in organisms:
        assert isinstance(organism, population.Organism)

    assert len(list(organisms)) == 4

    ids = [organism.id for organism in organisms]

    org = population.get_random_organism()
    assert org.id in ids
Esempio n. 2
0
    def _eval_exiting(self, portfolio: Portfolio) -> None:
        """Оценивает существующих."""
        tickers = tuple(portfolio.index[:-2])
        end = portfolio.date
        count = population.count()

        for step, parent in enumerate(population.get_all_organisms(), 1):
            print(f"***{end.date()}: Шаг переоценки существующих организмов - {step}/{count}***")
            population.print_stat()
            print()

            print("Родитель:")
            parent_fitness = self._eval_and_print(parent, tickers, end)
            if parent_fitness is None:
                continue
Esempio n. 3
0
    def __init__(
            self, tickers: Tuple[str, ...], date: pd.Timestamp,
    ):
        self._tickers = tickers
        self._date = date

        self._forecasts = []
        for organism in tqdm.tqdm(population.get_all_organisms(), desc="Forecasts"):
            try:
                forecast = organism.forecast(tickers, date)
            except ForecastError:
                continue
            self._forecasts.append(forecast)
        if not self._forecasts:
            raise population.ForecastError("Отсутствуют прогнозы - необходимо обучить модели")
Esempio n. 4
0
    def evolve(self, portfolio: Portfolio) -> NoReturn:
        """Осуществляет одну эпоху эволюции.

        При необходимости создается начальная популяция из организмов по умолчанию.
        """
        tickers = tuple(portfolio.index[:-2])
        end = portfolio.date

        self._setup()

        count = population.count()

        for step, parent in enumerate(population.get_all_organisms(), 1):
            print(f"***{end.date()}: Шаг эпохи - {step}/{count}***")
            population.print_stat()
            print()

            print("Родитель:")
            parent_fitness = self._eval_and_print(parent, tickers, end)
            if parent_fitness is None:
                continue

            child = parent.make_child()
            print("Потомок:")
            child_fitness = self._eval_and_print(child, tickers, end)
            if child_fitness is None:
                continue

            if population.count() <= self._max_population:
                continue

            weakest = parent
            if parent_fitness > child_fitness:
                weakest = child

            weakest = weakest.find_weaker()
            print("Более слабый и наиболее медленный - удаляю:")
            self._eval_and_print(weakest, tickers, end)
            weakest.die()
Esempio n. 5
0
    def evolve(self, portfolio: Portfolio) -> NoReturn:
        """Осуществляет одну эпоху эволюции.

        При необходимости создается начальная популяция из организмов по умолчанию.
        """
        tickers = tuple(portfolio.index[:-2])
        end = portfolio.date

        self._setup()
        self._eval_exiting(portfolio)

        count = population.count()

        factor = MUTATION_FACTOR

        for step, parent in enumerate(population.get_all_organisms(), 1):
            print(f"***{end.date()}: Шаг размножения - {step}/{count}***")
            population.print_stat()
            print(f"Фактор - {factor:.2%}")
            print()

            child = parent.make_child(factor)
            print("Потомок:")
            child_fitness = self._eval_and_print(child, tickers, end)
            if child_fitness is None:
                factor *= MUTATION_FACTOR
                continue

            if population.count() <= self._max_population:
                continue

            weakest = child.find_weaker()

            print("Наиболее слабый - удаляю:")
            self._eval_and_print(weakest, tickers, end)
            weakest.die()