Enoder commited on
Commit
ceb5710
·
verified ·
1 Parent(s): 2ab42d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -66
app.py CHANGED
@@ -43,64 +43,52 @@ def predict_patterns(data, future_hours=24):
43
  cycle_amplitude = (df["price"].max() - df["price"].min()) / 2
44
  mean_price = df["price"].mean()
45
 
46
- patterns = {}
47
-
48
- patterns["Trend"] = [last_price + i * trend for i in range(1, len(future_timestamps) + 1)]
49
- patterns["Reversal"] = [last_price - i * trend for i in range(1, len(future_timestamps) + 1)]
50
- patterns["SMA"] = [sma] * len(future_timestamps)
51
- patterns["EMA"] = [ema] * len(future_timestamps)
52
- patterns["Cycle"] = [
53
- last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps))
54
- for i in range(len(future_timestamps))
55
- ]
56
- patterns["Rebound"] = [last_price + trend * (0.5 ** i) for i in range(len(future_timestamps))]
57
- patterns["Plateau"] = [last_price] * len(future_timestamps)
58
- patterns["Breakout"] = [
59
- last_price + (trend * 2 if i < len(future_timestamps) // 2 else -trend * 2)
60
- for i in range(len(future_timestamps))
61
- ]
62
- patterns["Recovery"] = [last_price + (mean_price - last_price) * (i / len(future_timestamps)) for i in range(len(future_timestamps))]
63
- patterns["Acceleration"] = [last_price + (trend * 1.5) * i for i in range(len(future_timestamps))]
64
-
65
- # Ajout des 20 autres patterns
66
- patterns["Overbought"] = [last_price + cycle_amplitude * np.cos(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
67
- patterns["Oversold"] = [last_price - cycle_amplitude * np.cos(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
68
- patterns["DoubleTop"] = [last_price + trend * 2 if i < len(future_timestamps) // 2 else last_price - trend * 2 for i in range(len(future_timestamps))]
69
- patterns["DoubleBottom"] = [last_price - trend * 2 if i < len(future_timestamps) // 2 else last_price + trend * 2 for i in range(len(future_timestamps))]
70
- patterns["HeadAndShoulders"] = [last_price + (cycle_amplitude * np.sin(2 * np.pi * i / (len(future_timestamps) // 2))) for i in range(len(future_timestamps))]
71
- patterns["InverseHeadAndShoulders"] = [last_price - (cycle_amplitude * np.sin(2 * np.pi * i / (len(future_timestamps) // 2))) for i in range(len(future_timestamps))]
72
- patterns["Parabolic"] = [last_price + (cycle_amplitude * i ** 2) for i in range(len(future_timestamps))]
73
- patterns["ExponentialGrowth"] = [last_price * (1 + 0.05) ** i for i in range(len(future_timestamps))]
74
- patterns["ExponentialDecay"] = [last_price * (1 - 0.05) ** i for i in range(len(future_timestamps))]
75
- patterns["Sinusoidal"] = [last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
76
- patterns["Flatline"] = [last_price for i in range(len(future_timestamps))]
77
- patterns["HarmonicOscillator"] = [last_price + cycle_amplitude * np.cos(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
78
- patterns["Waveform"] = [last_price + cycle_amplitude * np.sin(i) for i in range(len(future_timestamps))]
79
- patterns["SwingHigh"] = [last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
80
- patterns["SwingLow"] = [last_price - cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps)) for i in range(len(future_timestamps))]
81
- patterns["AscendingTriangle"] = [last_price + cycle_amplitude * np.exp(i / len(future_timestamps)) for i in range(len(future_timestamps))]
82
- patterns["DescendingTriangle"] = [last_price - cycle_amplitude * np.exp(i / len(future_timestamps)) for i in range(len(future_timestamps))]
83
-
84
- pattern_dfs = {
85
- pattern_name: pd.DataFrame({"timestamp": future_timestamps, "price": prices})
86
- for pattern_name, prices in patterns.items()
87
  }
88
- return pattern_dfs
89
 
90
- # Fonction pour identifier le pattern le plus ressemblant
91
- def identify_best_pattern(df, patterns):
 
 
 
92
  mse_scores = {}
93
- actual_values = df["price"].values[-len(df) // 2:] # Dernières heures
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
- for pattern_name, pattern_df in patterns.items():
96
- predicted_values = np.array(pattern_df["price"].values[:len(actual_values)])
97
- min_length = min(len(actual_values), len(predicted_values))
98
- mse = mean_squared_error(actual_values[:min_length], predicted_values[:min_length])
99
- mse_scores[pattern_name] = mse
100
 
101
- # Sélection du pattern avec la MSE la plus faible
102
- best_pattern = min(mse_scores, key=mse_scores.get)
103
- return best_pattern
 
104
 
105
  # Configuration des dates
106
  end_time = datetime.now()
@@ -125,24 +113,27 @@ for coin, price_data in crypto_prices.items():
125
  df = pd.DataFrame(price_data, columns=["timestamp", "price"])
126
  df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
127
 
128
- patterns = predict_patterns(price_data, future_hours=24)
129
- best_pattern = identify_best_pattern(df, patterns)
 
 
 
 
 
 
130
 
 
131
  st.write(f"#### {coin} - Prix et Prédictions")
132
  fig, ax = plt.subplots(figsize=(12, 6))
133
  ax.plot(df["timestamp"], df["price"], label="Prix réel", color="blue")
134
 
135
- # Affiche uniquement le meilleur pattern
136
- best_pattern_df = patterns[best_pattern]
137
- ax.plot(
138
- best_pattern_df["timestamp"],
139
- best_pattern_df["price"],
140
- label=f"Prédiction ({best_pattern})",
141
- linestyle="dashed",
142
- color="orange"
143
- )
144
-
145
- ax.set_title(f"{coin} - Prix (7 derniers jours + 24h prévus avec {best_pattern})")
146
  ax.set_xlabel("Date")
147
  ax.set_ylabel("Prix (USD)")
148
  ax.legend()
 
43
  cycle_amplitude = (df["price"].max() - df["price"].min()) / 2
44
  mean_price = df["price"].mean()
45
 
46
+ # Prédictions initiales (Courbe jaune)
47
+ predictions = {
48
+ "Trend": [last_price + i * trend for i in range(1, len(future_timestamps) + 1)],
49
+ "SMA": [sma] * len(future_timestamps),
50
+ "EMA": [ema] * len(future_timestamps),
51
+ "Cycle": [
52
+ last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps))
53
+ for i in range(len(future_timestamps))
54
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
 
56
 
57
+ return predictions, future_timestamps
58
+
59
+ # Fonction pour rechercher un pattern similaire
60
+ def find_similar_pattern(df, prediction, future_hours=24):
61
+ # Calculer la similarité entre la courbe prédite et les patterns passés
62
  mse_scores = {}
63
+ for i in range(len(df) - future_hours): # Exclure la dernière période pour éviter la correspondance avec elle-même
64
+ past_pattern = df["price"].iloc[i:i + future_hours].values
65
+ mse = mean_squared_error(past_pattern, prediction[:len(past_pattern)])
66
+ mse_scores[i] = mse
67
+
68
+ # Trouver l'indice du pattern le plus similaire
69
+ best_match_index = min(mse_scores, key=mse_scores.get)
70
+ similar_pattern = df["price"].iloc[best_match_index:best_match_index + future_hours].values
71
+ return similar_pattern
72
+
73
+ # Fonction pour générer une prédiction dynamique (Courbe verte)
74
+ def generate_dynamic_prediction(df, initial_prediction, future_hours=24):
75
+ green_prediction = []
76
+
77
+ # Première prédiction
78
+ green_prediction.extend(initial_prediction)
79
+
80
+ # Boucle pour ajuster la prédiction à chaque étape
81
+ for i in range(future_hours // 5): # Prédiction par segments de 5 heures
82
+ start_idx = i * 5
83
+ end_idx = (i + 1) * 5
84
 
85
+ # Prendre les 5 dernières valeurs et chercher un pattern similaire
86
+ similar_pattern = find_similar_pattern(df, green_prediction[start_idx:end_idx], future_hours=5)
 
 
 
87
 
88
+ # Ajouter le pattern similaire à la prédiction
89
+ green_prediction.extend(similar_pattern)
90
+
91
+ return green_prediction
92
 
93
  # Configuration des dates
94
  end_time = datetime.now()
 
113
  df = pd.DataFrame(price_data, columns=["timestamp", "price"])
114
  df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
115
 
116
+ # Générer les prédictions initiales (jaune)
117
+ predictions, future_timestamps = predict_patterns(price_data, future_hours=24)
118
+
119
+ # Sélectionner une prédiction (par exemple Trend)
120
+ initial_prediction = predictions["Trend"]
121
+
122
+ # Générer la prédiction dynamique (verte)
123
+ green_prediction = generate_dynamic_prediction(df, initial_prediction, future_hours=24)
124
 
125
+ # Affichage des résultats
126
  st.write(f"#### {coin} - Prix et Prédictions")
127
  fig, ax = plt.subplots(figsize=(12, 6))
128
  ax.plot(df["timestamp"], df["price"], label="Prix réel", color="blue")
129
 
130
+ # Courbe de prédiction initiale (jaune)
131
+ ax.plot(future_timestamps, initial_prediction, label="Prédiction initiale (jaune)", linestyle="--", color="yellow")
132
+
133
+ # Courbe de prédiction dynamique (verte)
134
+ ax.plot(future_timestamps, green_prediction, label="Prédiction dynamique (verte)", linestyle="--", color="green")
135
+
136
+ ax.set_title(f"{coin} - Prix (7 derniers jours + 24h prévus)")
 
 
 
 
137
  ax.set_xlabel("Date")
138
  ax.set_ylabel("Prix (USD)")
139
  ax.legend()