Spaces:
Build error
Build error
File size: 5,984 Bytes
3308842 98e569e 3308842 2ab42d3 3308842 a594fa0 3308842 ceb5710 3308842 ceb5710 707da7e 3308842 707da7e ceb5710 707da7e ceb5710 707da7e a68f8c7 707da7e 0a070b8 a68f8c7 3308842 2ab42d3 3308842 743941e 3308842 743941e 3308842 c870c72 743941e c870c72 743941e ceb5710 707da7e 743941e ceb5710 c870c72 743941e 707da7e 743941e ceb5710 707da7e ceb5710 c870c72 743941e 8906099 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | 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)
|