Update app.py
Browse files
app.py
CHANGED
|
@@ -1,85 +1,97 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
def predict_patterns(data, future_hours=24):
|
| 3 |
-
# Convertir les données en DataFrame
|
| 4 |
df = pd.DataFrame(data, columns=["timestamp", "price"])
|
| 5 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
| 6 |
df.set_index("timestamp", inplace=True)
|
| 7 |
|
| 8 |
-
# Générer les futures timestamps
|
| 9 |
last_timestamp = df.index[-1]
|
| 10 |
future_timestamps = [last_timestamp + timedelta(minutes=15 * i) for i in range(1, (future_hours * 60 // 15) + 1)]
|
| 11 |
|
| 12 |
-
# Calculer des métriques utiles
|
| 13 |
last_price = df["price"].iloc[-1]
|
| 14 |
trend = (df["price"].iloc[-1] - df["price"].iloc[0]) / len(df)
|
| 15 |
-
sma = df["price"].rolling(window=10).mean().iloc[-1]
|
| 16 |
-
ema = df["price"].ewm(span=10, adjust=False).mean().iloc[-1]
|
| 17 |
|
| 18 |
-
# Liste des patterns
|
| 19 |
patterns = {}
|
| 20 |
|
| 21 |
-
# 1. Tendance linéaire
|
| 22 |
patterns["Trend"] = [last_price + i * trend for i in range(1, len(future_timestamps) + 1)]
|
| 23 |
-
|
| 24 |
-
# 2. Moyenne Mobile Simple
|
| 25 |
patterns["SMA"] = [sma] * len(future_timestamps)
|
| 26 |
-
|
| 27 |
-
# 3. Moyenne Mobile Exponentielle
|
| 28 |
patterns["EMA"] = [ema] * len(future_timestamps)
|
| 29 |
-
|
| 30 |
-
# 4. Cycle Répété
|
| 31 |
cycle_amplitude = (df["price"].max() - df["price"].min()) / 2
|
| 32 |
patterns["Cycle"] = [
|
| 33 |
last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps))
|
| 34 |
for i in range(len(future_timestamps))
|
| 35 |
]
|
| 36 |
-
|
| 37 |
-
# 5. Rebond
|
| 38 |
patterns["Rebound"] = [last_price + trend * (0.5 ** i) for i in range(len(future_timestamps))]
|
| 39 |
-
|
| 40 |
-
# 6. Effet Plateau
|
| 41 |
patterns["Plateau"] = [last_price] * len(future_timestamps)
|
| 42 |
-
|
| 43 |
-
# 7. Renversement de Tendance
|
| 44 |
-
reverse_trend = -trend
|
| 45 |
-
patterns["Reversal"] = [last_price + i * reverse_trend for i in range(len(future_timestamps))]
|
| 46 |
-
|
| 47 |
-
# 8. Récupération après Crash
|
| 48 |
mean_price = df["price"].mean()
|
| 49 |
patterns["Recovery"] = [last_price + (mean_price - last_price) * (i / len(future_timestamps)) for i in range(len(future_timestamps))]
|
| 50 |
-
|
| 51 |
-
# 9. Accélération de la Tendance
|
| 52 |
patterns["Acceleration"] = [last_price + (trend * 1.5) * i for i in range(len(future_timestamps))]
|
| 53 |
-
|
| 54 |
-
# 10. Volatilité Aléatoire
|
| 55 |
random_volatility = np.random.normal(0, trend * 0.5, len(future_timestamps))
|
| 56 |
patterns["Random"] = [last_price + sum(random_volatility[:i]) for i in range(len(future_timestamps))]
|
| 57 |
|
| 58 |
-
# Retourner les données des patterns avec leurs timestamps
|
| 59 |
pattern_dfs = {
|
| 60 |
pattern_name: pd.DataFrame({"timestamp": future_timestamps, "price": prices})
|
| 61 |
for pattern_name, prices in patterns.items()
|
| 62 |
}
|
| 63 |
return pattern_dfs
|
| 64 |
|
| 65 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
for coin, price_data in crypto_prices.items():
|
| 67 |
if price_data:
|
| 68 |
-
# Convertir les données en DataFrame
|
| 69 |
df = pd.DataFrame(price_data, columns=["timestamp", "price"])
|
| 70 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
| 71 |
|
| 72 |
-
# Générer les patterns de prédiction
|
| 73 |
patterns = predict_patterns(price_data, future_hours=24)
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
st.write(f"#### {coin} - Prix et Prédictions en {selected_currency}")
|
| 77 |
fig, ax = plt.subplots(figsize=(12, 6))
|
| 78 |
-
|
| 79 |
-
# Graphique des prix réels
|
| 80 |
ax.plot(df["timestamp"], df["price"], label="Prix réel", color="blue")
|
| 81 |
|
| 82 |
-
# Affichage des prédictions
|
| 83 |
colors = ["orange", "green", "red", "purple", "brown", "pink", "cyan", "black", "gray", "magenta"]
|
| 84 |
for i, (pattern_name, pattern_df) in enumerate(patterns.items()):
|
| 85 |
ax.plot(
|
|
@@ -90,12 +102,10 @@ for coin, price_data in crypto_prices.items():
|
|
| 90 |
color=colors[i % len(colors)]
|
| 91 |
)
|
| 92 |
|
| 93 |
-
# Ajustements
|
| 94 |
ax.set_title(f"{coin} - Prix (48h réels + 24h prévus)")
|
| 95 |
ax.set_xlabel("Temps")
|
| 96 |
-
ax.set_ylabel(
|
| 97 |
ax.legend()
|
| 98 |
-
|
| 99 |
st.pyplot(fig)
|
| 100 |
else:
|
| 101 |
st.warning(f"Aucune donnée disponible pour {coin}")
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import numpy as np
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
|
| 8 |
+
# Fonction pour récupérer les prix
|
| 9 |
+
def get_crypto_prices(coins, start_time, end_time, interval='m15', currency='usd'):
|
| 10 |
+
prices = {}
|
| 11 |
+
for coin, coin_id in coins.items():
|
| 12 |
+
url = f'https://api.coincap.io/v2/assets/{coin_id}/history'
|
| 13 |
+
params = {
|
| 14 |
+
'interval': interval,
|
| 15 |
+
'start': int(start_time.timestamp() * 1000),
|
| 16 |
+
'end': int(end_time.timestamp() * 1000)
|
| 17 |
+
}
|
| 18 |
+
response = requests.get(url, params=params)
|
| 19 |
+
if response.status_code == 200:
|
| 20 |
+
data = response.json().get('data', [])
|
| 21 |
+
prices[coin] = [[int(item['time']), float(item['priceUsd'])] for item in data]
|
| 22 |
+
if data:
|
| 23 |
+
prices[coin].append([int(end_time.timestamp() * 1000), float(data[-1]['priceUsd'])])
|
| 24 |
+
else:
|
| 25 |
+
st.error(f"Erreur lors de la récupération des prix pour {coin}: {response.status_code}")
|
| 26 |
+
return prices
|
| 27 |
+
|
| 28 |
+
# Fonction pour générer des prédictions basées sur des patterns
|
| 29 |
def predict_patterns(data, future_hours=24):
|
|
|
|
| 30 |
df = pd.DataFrame(data, columns=["timestamp", "price"])
|
| 31 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
| 32 |
df.set_index("timestamp", inplace=True)
|
| 33 |
|
|
|
|
| 34 |
last_timestamp = df.index[-1]
|
| 35 |
future_timestamps = [last_timestamp + timedelta(minutes=15 * i) for i in range(1, (future_hours * 60 // 15) + 1)]
|
| 36 |
|
|
|
|
| 37 |
last_price = df["price"].iloc[-1]
|
| 38 |
trend = (df["price"].iloc[-1] - df["price"].iloc[0]) / len(df)
|
| 39 |
+
sma = df["price"].rolling(window=10).mean().iloc[-1]
|
| 40 |
+
ema = df["price"].ewm(span=10, adjust=False).mean().iloc[-1]
|
| 41 |
|
|
|
|
| 42 |
patterns = {}
|
| 43 |
|
|
|
|
| 44 |
patterns["Trend"] = [last_price + i * trend for i in range(1, len(future_timestamps) + 1)]
|
|
|
|
|
|
|
| 45 |
patterns["SMA"] = [sma] * len(future_timestamps)
|
|
|
|
|
|
|
| 46 |
patterns["EMA"] = [ema] * len(future_timestamps)
|
|
|
|
|
|
|
| 47 |
cycle_amplitude = (df["price"].max() - df["price"].min()) / 2
|
| 48 |
patterns["Cycle"] = [
|
| 49 |
last_price + cycle_amplitude * np.sin(2 * np.pi * i / len(future_timestamps))
|
| 50 |
for i in range(len(future_timestamps))
|
| 51 |
]
|
|
|
|
|
|
|
| 52 |
patterns["Rebound"] = [last_price + trend * (0.5 ** i) for i in range(len(future_timestamps))]
|
|
|
|
|
|
|
| 53 |
patterns["Plateau"] = [last_price] * len(future_timestamps)
|
| 54 |
+
patterns["Reversal"] = [last_price + i * -trend for i in range(len(future_timestamps))]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
mean_price = df["price"].mean()
|
| 56 |
patterns["Recovery"] = [last_price + (mean_price - last_price) * (i / len(future_timestamps)) for i in range(len(future_timestamps))]
|
|
|
|
|
|
|
| 57 |
patterns["Acceleration"] = [last_price + (trend * 1.5) * i for i in range(len(future_timestamps))]
|
|
|
|
|
|
|
| 58 |
random_volatility = np.random.normal(0, trend * 0.5, len(future_timestamps))
|
| 59 |
patterns["Random"] = [last_price + sum(random_volatility[:i]) for i in range(len(future_timestamps))]
|
| 60 |
|
|
|
|
| 61 |
pattern_dfs = {
|
| 62 |
pattern_name: pd.DataFrame({"timestamp": future_timestamps, "price": prices})
|
| 63 |
for pattern_name, prices in patterns.items()
|
| 64 |
}
|
| 65 |
return pattern_dfs
|
| 66 |
|
| 67 |
+
# Configuration des dates
|
| 68 |
+
end_time = datetime.now()
|
| 69 |
+
start_time = end_time - timedelta(hours=48)
|
| 70 |
+
|
| 71 |
+
# Liste des cryptos
|
| 72 |
+
coins = {
|
| 73 |
+
"Bitcoin": "bitcoin",
|
| 74 |
+
"Ripple": "ripple",
|
| 75 |
+
"Ethereum": "ethereum",
|
| 76 |
+
"Tether": "tether",
|
| 77 |
+
"Stellar": "stellar"
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
# Récupération des prix
|
| 81 |
+
crypto_prices = get_crypto_prices(coins, start_time, end_time)
|
| 82 |
+
|
| 83 |
+
# Affichage des graphiques
|
| 84 |
for coin, price_data in crypto_prices.items():
|
| 85 |
if price_data:
|
|
|
|
| 86 |
df = pd.DataFrame(price_data, columns=["timestamp", "price"])
|
| 87 |
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
| 88 |
|
|
|
|
| 89 |
patterns = predict_patterns(price_data, future_hours=24)
|
| 90 |
|
| 91 |
+
st.write(f"#### {coin} - Prix et Prédictions")
|
|
|
|
| 92 |
fig, ax = plt.subplots(figsize=(12, 6))
|
|
|
|
|
|
|
| 93 |
ax.plot(df["timestamp"], df["price"], label="Prix réel", color="blue")
|
| 94 |
|
|
|
|
| 95 |
colors = ["orange", "green", "red", "purple", "brown", "pink", "cyan", "black", "gray", "magenta"]
|
| 96 |
for i, (pattern_name, pattern_df) in enumerate(patterns.items()):
|
| 97 |
ax.plot(
|
|
|
|
| 102 |
color=colors[i % len(colors)]
|
| 103 |
)
|
| 104 |
|
|
|
|
| 105 |
ax.set_title(f"{coin} - Prix (48h réels + 24h prévus)")
|
| 106 |
ax.set_xlabel("Temps")
|
| 107 |
+
ax.set_ylabel("Prix (USD)")
|
| 108 |
ax.legend()
|
|
|
|
| 109 |
st.pyplot(fig)
|
| 110 |
else:
|
| 111 |
st.warning(f"Aucune donnée disponible pour {coin}")
|