|
| 1 | +import matplotlib.pyplot as plt |
| 2 | +import numpy as np |
| 3 | +import yfinance as yf |
| 4 | +from approximate_entropy import ApproximateEntropyAlgorithm |
| 5 | +from bubble_entropy import BubbleEntropyAlgorithm |
| 6 | +from sample_entropy import SampleEntropyAlgorithm |
| 7 | +from shannon_entropy import ShannonEntropyAlgorithm |
| 8 | +from slope_entropy import SlopeEntropyAlgorithm |
| 9 | + |
| 10 | +tickers = {"KO": "Coca-Cola (KO)", "^GSPC": "S&P 500 (^GSPC)"} |
| 11 | + |
| 12 | +t = np.linspace(0, 10, 500) |
| 13 | +ecg_series = np.sin(2 * np.pi * 1.5 * t) + 0.1 * np.random.randn(len(t)) |
| 14 | +health_series = 100 + 5 * np.sin(0.5 * t) + np.random.randn(len(t)) |
| 15 | +router_series = np.random.choice([0, 1], size=500, p=[0.3, 0.7]) |
| 16 | + |
| 17 | +time_series_list = {} |
| 18 | +for symbol, full_name in tickers.items(): |
| 19 | + stock_data = yf.download(symbol, start="2023-01-01", end="2025-07-01") |
| 20 | + stock_series = stock_data["Close"].ffill().values |
| 21 | + time_series_list[full_name] = stock_series |
| 22 | + |
| 23 | +time_series_list["ECG"] = ecg_series |
| 24 | +time_series_list["Health"] = health_series |
| 25 | +time_series_list["Router Signal"] = router_series |
| 26 | + |
| 27 | +algorithms = [ |
| 28 | + BubbleEntropyAlgorithm(window_size=30, embedding_dimension=3, threshold=0.05), |
| 29 | + ApproximateEntropyAlgorithm(window_size=30, m=2, r=0.2, threshold=0.05), |
| 30 | + SampleEntropyAlgorithm(window_size=30, m=2, threshold=0.05), |
| 31 | + ShannonEntropyAlgorithm(window_size=30, threshold=0.05), |
| 32 | + SlopeEntropyAlgorithm(window_size=20, threshold=0.05), |
| 33 | +] |
| 34 | + |
| 35 | + |
| 36 | +def analyze_series(name, series): |
| 37 | + print(f"\n=== Анализ серии: {name} ===") |
| 38 | + for algo in algorithms: |
| 39 | + if hasattr(algo, "reset"): |
| 40 | + algo.reset() |
| 41 | + |
| 42 | + change_points = [] |
| 43 | + for i, value in enumerate(series): |
| 44 | + if algo.detect(value): |
| 45 | + cp = algo.localize(value) |
| 46 | + if cp is not None and cp < len(series): |
| 47 | + change_points.append(cp) |
| 48 | + |
| 49 | + print(f"{algo.__class__.__name__}: Обнаруженные change points: {change_points}") |
| 50 | + plot_series_with_cps(name, series, change_points, algo.__class__.__name__) |
| 51 | + |
| 52 | + |
| 53 | +def plot_series_with_cps(series_name, series, cps, algo_name): |
| 54 | + plt.figure(figsize=(12, 3)) |
| 55 | + plt.plot(series, label=f"{series_name}") |
| 56 | + if cps: |
| 57 | + plt.scatter(cps, series[cps], color="red", marker="x", s=50, label="Change points") |
| 58 | + plt.title(f"{series_name} - {algo_name}") |
| 59 | + plt.xlabel("Time") |
| 60 | + plt.ylabel("Value") |
| 61 | + plt.legend() |
| 62 | + plt.tight_layout() |
| 63 | + plt.show() |
| 64 | + |
| 65 | + |
| 66 | +for name, series_data in time_series_list.items(): |
| 67 | + analyze_series(name, series_data) |
0 commit comments