Enoder commited on
Commit
ff6a5f3
·
verified ·
1 Parent(s): 17a2bc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -47
app.py CHANGED
@@ -2,54 +2,81 @@ 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
- # Récupération des données via l'API CoinGecko
9
- def get_crypto_data(crypto_id="bitcoin", currency="usd"):
10
- url = f"https://api.coingecko.com/api/v3/coins/{crypto_id}/market_chart"
11
- params = {
12
- "vs_currency": currency,
13
- "days": "2", # Dernières 48 heures
14
- "interval": "minute"
15
- }
16
- response = requests.get(url, params=params)
17
- data = response.json()
18
- prices = data["prices"] # Liste de [timestamp, price]
19
- volumes = data["total_volumes"] # Liste de [timestamp, volume]
20
-
21
- # Conversion en DataFrame
22
- df = pd.DataFrame(prices, columns=["timestamp", "price"])
23
- df["volume"] = [v[1] for v in volumes]
24
- df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
25
- return df
26
-
27
- # Prédiction simple (Extrapolation basée sur la tendance moyenne)
28
- def predict_future(df, minutes=60):
29
- trend = (df["price"].iloc[-1] - df["price"].iloc[0]) / len(df) # Tendance par minute
30
- last_price = df["price"].iloc[-1]
31
- future_timestamps = [df["timestamp"].iloc[-1] + timedelta(minutes=i) for i in range(1, minutes + 1)]
32
- future_prices = [last_price + i * trend for i in range(1, minutes + 1)]
33
- return pd.DataFrame({"timestamp": future_timestamps, "price": future_prices})
 
 
 
 
 
 
 
 
 
 
34
 
35
  # Streamlit App
36
- st.title("Analyse et Prédiction Crypto (48h)")
37
- crypto_id = st.sidebar.text_input("Nom de la cryptomonnaie (ex : bitcoin)", "bitcoin")
38
- currency = st.sidebar.text_input("Devise (ex : usd)", "usd")
39
-
40
- # Récupération et affichage des données
41
- st.write(f"Affichage des données pour : {crypto_id} en {currency}")
42
- df = get_crypto_data(crypto_id, currency)
43
- st.line_chart(df.set_index("timestamp")[["price"]])
44
-
45
- # Prédiction
46
- minutes_future = st.slider("Minutes à prévoir", 10, 120, 60)
47
- future_df = predict_future(df, minutes=minutes_future)
48
-
49
- # Affichage des prédictions
50
- fig, ax = plt.subplots()
51
- ax.plot(df["timestamp"], df["price"], label="Historique")
52
- ax.plot(future_df["timestamp"], future_df["price"], label="Prédiction", linestyle="dashed")
53
- ax.set_title("Prix actuel et prédiction")
54
- ax.legend()
55
- st.pyplot(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import requests
3
  import pandas as pd
4
  import matplotlib.pyplot as plt
 
5
  from datetime import datetime, timedelta
6
 
7
+ # Mapping des cryptomonnaies et devises avec leurs IDs pour CoinCap
8
+ coins = {
9
+ "Bitcoin": "bitcoin",
10
+ "Ripple": "ripple",
11
+ "Ethereum": "ethereum",
12
+ "Tether": "tether",
13
+ "Stellar": "stellar"
14
+ }
15
+
16
+ currencies = {
17
+ "Dollar (USD)": "usd",
18
+ "Euro (EUR)": "eur",
19
+ "Livre (GBP)": "gbp",
20
+ "Bitcoin (BTC)": "btc",
21
+ "Tether (USDT)": "usdt"
22
+ }
23
+
24
+ # Fonction pour récupérer les données de CoinCap
25
+ def get_crypto_prices(selected_coins, selected_currency, start_time, end_time):
26
+ prices = {}
27
+ for coin, coin_id in selected_coins.items():
28
+ url = f'https://api.coincap.io/v2/assets/{coin_id}/history'
29
+ params = {
30
+ 'interval': 'm15', # Intervalle de 15 minutes
31
+ 'start': int(start_time.timestamp() * 1000), # Timestamp en millisecondes
32
+ 'end': int(end_time.timestamp() * 1000)
33
+ }
34
+ response = requests.get(url, params=params)
35
+ if response.status_code == 200:
36
+ data = response.json().get('data', [])
37
+ prices[coin] = [[int(item['time']), float(item['priceUsd'])] for item in data]
38
+ if data:
39
+ prices[coin].append([int(end_time.timestamp() * 1000), float(data[-1]['priceUsd'])])
40
+ else:
41
+ st.error(f"Erreur lors de la récupération des prix pour {coin}: {response.status_code}")
42
+ return prices
43
 
44
  # Streamlit App
45
+ st.title("Analyse Multi-Crypto avec CoinCap")
46
+ st.sidebar.header("Paramètres")
47
+
48
+ # Choix des cryptomonnaies
49
+ selected_coins = st.sidebar.multiselect(
50
+ "Choisissez les cryptomonnaies",
51
+ list(coins.keys()),
52
+ default=["Bitcoin", "Ethereum"]
53
+ )
54
+
55
+ # Choix de la devise
56
+ selected_currency = st.sidebar.selectbox(
57
+ "Choisissez la devise",
58
+ list(currencies.keys()),
59
+ index=0
60
+ )
61
+
62
+ # Période de temps
63
+ end_time = datetime.now()
64
+ start_time = end_time - timedelta(hours=48) # Dernières 48 heures
65
+
66
+ # Conversion des sélections en IDs
67
+ selected_coin_ids = {coin: coins[coin] for coin in selected_coins}
68
+ selected_currency_id = currencies[selected_currency]
69
+
70
+ # Récupération des données
71
+ st.write(f"### Données pour : {', '.join(selected_coins)} en {selected_currency}")
72
+ crypto_prices = get_crypto_prices(selected_coin_ids, selected_currency_id, start_time, end_time)
73
+
74
+ # Affichage des graphiques
75
+ for coin, price_data in crypto_prices.items():
76
+ if price_data:
77
+ df = pd.DataFrame(price_data, columns=["timestamp", "price"])
78
+ df["timestamp"] = pd.to_datetime(df["timestamp"], unit='ms')
79
+ st.write(f"#### {coin} - Prix en {selected_currency}")
80
+ st.line_chart(df.set_index("timestamp")["price"])
81
+ else:
82
+ st.warning(f"Aucune donnée disponible pour {coin}")