# modules/forecast_modeling.py
import numpy as np
def monte_carlo_forecast(pool_values, pool_weights=None, num_simulations=100000, p1=0.05, p2=0.95):
"""
Выполняет симуляцию методом Монте-Карло с учетом весов.
"""
if not pool_values:
raise ValueError("Пул значений для симуляции пуст.")
probabilities = None
if pool_weights is not None:
total_weight = sum(pool_weights)
probabilities = np.array(pool_weights) / total_weight
results = []
n = len(pool_values)
for _ in range(num_simulations):
k = np.random.randint(1, n + 1)
sample = np.random.choice(pool_values, size=k, p=probabilities)
results.append(np.sum(sample))
if not results:
return {"error": "Не удалось получить результаты симуляции."}
results_array = np.array(results)
return {
"lower_bound": float(np.percentile(results_array, p1 * 100)),
"upper_bound": float(np.percentile(results_array, p2 * 100)),
"median": float(np.median(results_array)),
"simulations": results_array.tolist()
}