Spaces:
Build error
Build error
| import streamlit as st | |
| import requests | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| from datetime import datetime, timedelta | |
| from sklearn.metrics import mean_squared_error | |
| # Fonction pour récupérer les prix historiques | |
| def get_crypto_prices(coins, start_time, end_time, interval='m15'): | |
| prices = {} | |
| for coin, coin_id in coins.items(): | |
| url = f'https://api.coincap.io/v2/assets/{coin_id}/history' | |
| params = { | |
| 'interval': interval, | |
| 'start': int(start_time.timestamp() * 1000), | |
| 'end': int(end_time.timestamp() * 1000) | |
| } | |
| response = requests.get(url, params=params) | |
| if response.status_code == 200: | |
| data = response.json().get('data', []) | |
| prices[coin] = [[int(item['time']), float(item['priceUsd'])] for item in data] | |
| if data: | |
| prices[coin].append([int(end_time.timestamp() * 1000), float(data[-1]['priceUsd'])]) | |
| else: | |
| st.error(f"Erreur lors de la récupération des prix pour {coin}: {response.status_code}") | |
| st.write(response.text) # Debug pour afficher l'erreur complète | |
| return prices | |
| # Fonction pour prédire les tendances basées sur les patterns | |
| def predict_patterns(data, future_hours=24): | |
| df = pd.DataFrame(data, columns=["timestamp", "price"]) | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms") | |
| df.set_index("timestamp", inplace=True) | |
| last_timestamp = df.index[-1] | |
| future_timestamps = [last_timestamp + timedelta(hours=i) for i in range(1, future_hours + 1)] | |
| last_price = df["price"].iloc[-1] | |
| trend = (df["price"].iloc[-1] - df["price"].iloc[0]) / len(df) | |
| sma = df["price"].rolling(window=10).mean().iloc[-1] | |
| ema = df["price"].ewm(span=10, adjust=False).mean().iloc[-1] | |
| cycle_amplitude = (df["price"].max() - df["price"].min()) / 2 | |
| mean_price = df["price"].mean() | |
| # Prédictions initiales (Courbe jaune) | |
| predictions = { | |
| "Trend": [last_price + i * trend for i in range(1, len(future_timestamps) + 1)], | |
| "SMA": [sma] * len(future_timestamps), | |
| "EMA": [ema] * len(future_timestamps), | |
| "Cycle": [ | |
| last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps)) | |
| for i in range(len(future_timestamps)) | |
| ] | |
| } | |
| return predictions, future_timestamps | |
| # Fonction pour rechercher un pattern similaire | |
| def find_similar_pattern(df, prediction, future_hours=24): | |
| # Calculer la similarité entre la courbe prédite et les patterns passés | |
| mse_scores = {} | |
| for i in range(len(df) - future_hours): # Exclure la dernière période pour éviter la correspondance avec elle-même | |
| past_pattern = df["price"].iloc[i:i + future_hours].values | |
| mse = mean_squared_error(past_pattern, prediction[:len(past_pattern)]) | |
| mse_scores[i] = mse | |
| # Trouver l'indice du pattern le plus similaire | |
| best_match_index = min(mse_scores, key=mse_scores.get) | |
| similar_pattern = df["price"].iloc[best_match_index:best_match_index + future_hours].values | |
| return similar_pattern | |
| # Fonction pour générer une prédiction dynamique (Courbe verte) | |
| def generate_dynamic_prediction(df, initial_prediction, future_hours=24): | |
| green_prediction = [] | |
| # Première prédiction | |
| green_prediction.extend(initial_prediction) | |
| # Boucle pour ajuster la prédiction à chaque étape | |
| for i in range(future_hours // 5): # Prédiction par segments de 5 heures | |
| start_idx = i * 5 | |
| end_idx = (i + 1) * 5 | |
| # Prendre les 5 dernières valeurs et chercher un pattern similaire | |
| similar_pattern = find_similar_pattern(df, green_prediction[start_idx:end_idx], future_hours=5) | |
| # Ajouter le pattern similaire à la prédiction | |
| green_prediction.extend(similar_pattern) | |
| # Création des timestamps de prévision pour la courbe verte | |
| future_timestamps = pd.date_range(start=df.index[-1], periods=len(green_prediction) + 1, freq='H')[1:] | |
| return green_prediction, future_timestamps | |
| # Configuration des dates | |
| end_time = datetime.now() | |
| start_time = end_time - timedelta(days=7) # Plage sur les 7 derniers jours | |
| # Liste des cryptos avec leurs IDs corrects sur CoinCap | |
| coins = { | |
| "Bitcoin": "bitcoin", | |
| "Ripple": "xrp", | |
| "Ethereum": "ethereum", | |
| "Tether": "tether", | |
| "Stellar": "stellar" | |
| } | |
| # Récupération des prix | |
| crypto_prices = get_crypto_prices(coins, start_time, end_time) | |
| # Affichage des graphiques | |
| st.title("Analyse et Prédictions des Cryptos avec Patterns") | |
| for coin, price_data in crypto_prices.items(): | |
| if price_data: | |
| df = pd.DataFrame(price_data, columns=["timestamp", "price"]) | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms") | |
| # Générer les prédictions initiales (jaune) | |
| predictions, future_timestamps = predict_patterns(price_data, future_hours=24) | |
| # Sélectionner une prédiction (par exemple Trend) | |
| initial_prediction = predictions["Trend"] | |
| # Générer la prédiction dynamique (verte) | |
| green_prediction, green_future_timestamps = generate_dynamic_prediction(df, initial_prediction, future_hours=24) | |
| # Affichage des résultats | |
| st.write(f"#### {coin} - Prix et Prédictions") | |
| fig, ax = plt.subplots(figsize=(12, 6)) | |
| ax.plot(df["timestamp"], df["price"], label="Prix réel", color="blue") | |
| # Courbe de prédiction initiale (jaune) | |
| ax.plot(future_timestamps, initial_prediction, label="Prédiction initiale (jaune)", linestyle="--", color="yellow") | |
| # Courbe de prédiction dynamique (verte) | |
| ax.plot(green_future_timestamps, green_prediction, label="Prédiction dynamique (verte)", linestyle="--", color="green") | |
| ax.set_title(f"{coin} - Prix (7 derniers jours + 24h prévus)") | |
| ax.set_xlabel("Date") | |
| ax.set_ylabel("Prix (USD)") | |
| ax.legend() | |
| st.pyplot(fig) | |