Interface Streamlit

CryptoAnalyticsPro

Cette application web interactive offre une suite complète d’outils pour l’analyse et la prédiction du prix du Bitcoin, intégrant:

  1. Système d’authentification sécurisé

  2. Utilisation données en temps réel

  3. Calcul des indicateurs techniques

  4. Importation de son dataset CSV

  5. Prédiction du prix du lendemain

  6. Assistant trading intelligent

  7. Système d’alertes personnalisées

  8. Espace communautaire collaboratif

Aperçu de l'interface

Fonctionnalités Détailées avec Code

1. Authentification Utilisateur

Système complet de création de compte et connexion avec base SQLite.

 1# Initialisation BDD
 2conn = sqlite3.connect('users.db')
 3c = conn.cursor()
 4c.execute('''CREATE TABLE IF NOT EXISTS users
 5             (id INTEGER PRIMARY KEY AUTOINCREMENT,
 6              username TEXT UNIQUE,
 7              password TEXT)''')
 8
 9# Fonctions d'authentification
10def create_user(username, password):
11    try:
12        c.execute('INSERT INTO users (username, password) VALUES (?, ?)',
13                 (username, password))
14        conn.commit()
15        return True
16    except sqlite3.IntegrityError:
17        return False
18
19def verify_user(username, password):
20    c.execute('SELECT * FROM users WHERE username=? AND password=?',
21             (username, password))
22    return c.fetchone() is not None

2. Tableau de Bord Analytique

Visualisation interactive avec Plotly et calculs d’indicateurs techniques.

 1def fetch_real_data():
 2    btc = yf.Ticker("BTC-USD")
 3    hist = btc.history(period="2y")
 4
 5    # Fear & Greed Index
 6    response = requests.get("https://api.alternative.me/fng/?limit=730")
 7    fng_data = pd.DataFrame(response.json()['data'])
 8    fng_data['timestamp'] = pd.to_datetime(fng_data['timestamp'], unit='s')
 9
10    return hist.merge(fng_data, how='left').ffill()
11
12def plot_close_with_details(data):
13    fig = go.Figure()
14    fig.add_trace(go.Scatter(
15        x=data.index,
16        y=data['Close'],
17        name='Close',
18        line=dict(color='#d62728'),
19        hovertemplate="<b>%{x|%d %B %Y}</b><br>Close: %{y:.2f} USD<br>"
20    ))
21    fig.update_layout(height=500, xaxis_rangeslider_visible=True)
22    return fig

3. Assistant Trading Intelligent

Chatbot avec analyse de marché et conseils automatisés.

 1class BitcoinChatbot:
 2    def __init__(self, model, processor):
 3        self.model = model
 4        self.processor = processor
 5        self.thresholds = {
 6            "rsi_buy": 30,
 7            "rsi_sell": 70,
 8            "fear_greed_buy": 25,
 9            "fear_greed_sell": 75
10        }
11
12    def get_market_data(self):
13        btc = yf.Ticker("BTC-USD")
14        hist = btc.history(period="7d", interval="1h")
15        return {
16            "price": hist["Close"].iloc[-1],
17            "rsi": self.calculate_rsi(hist["Close"]),
18            "fear_greed": self.get_fear_greed_index()
19        }
20
21    def generate_advice(self):
22        data = self.get_market_data()
23        advice = []
24        if data['rsi'] < self.thresholds['rsi_buy']:
25            advice.append("✅ **RSI bas** - Bonne opportunité d'achat")
26        if data['fear_greed'] < self.thresholds['fear_greed_buy']:
27            advice.append("✅ **Peur extrême** - Signal d'achat")
28        return advice
29
30    def generate_response(self, query):
31        if "prix demain" in query.lower():
32            price = self.predict_tomorrow_price()
33            return f"Prévision pour demain: ${price:.2f}"
34        elif "conseil" in query.lower():
35            return "\n".join(self.generate_advice())

4. Prédiction Temps Réel

Modèle LSTM pour la prédiction des prix avec indicateurs de confiance.

 1class CryptoDataProcessor:
 2    def __init__(self):
 3        self.scaler = RobustScaler()
 4        self.target_idx = 0
 5
 6    def fit_transform(self, data):
 7        return self.scaler.fit_transform(data)
 8
 9    def inverse_transform(self, scaled_data):
10        return self.scaler.inverse_transform(scaled_data)[:, self.target_idx]
11
12def predict_next_day(model, processor, data):
13    scaled = processor.transform(data)
14    sequence = scaled[-SEQ_LENGTH:]
15    prediction = model.predict(np.array([sequence]))
16    return processor.inverse_transform(prediction)[0]

5. Système d’Alertes Personnalisées

Création et gestion d’alertes basées sur des conditions de marché.

 1# Table BDD
 2c.execute('''CREATE TABLE IF NOT EXISTS alerts
 3             (id INTEGER PRIMARY KEY AUTOINCREMENT,
 4              user_id INTEGER,
 5              condition TEXT,
 6              value REAL,
 7              created_at DATETIME)''')
 8
 9# Interface utilisateur
10condition = st.selectbox("Condition", ["Prix >", "Prix <", "RSI >", "RSI <"])
11value = st.number_input("Valeur seuil")
12if st.button("Créer alerte"):
13    c.execute('''INSERT INTO alerts (user_id, condition, value, created_at)
14                 VALUES (?, ?, ?, ?)''',
15              (user_id, condition, value, datetime.now()))
16
17# Vérification des alertes
18alerts = c.execute('''SELECT condition, value FROM alerts
19                      WHERE user_id = ?''', (user_id,)).fetchall()
20for cond, val in alerts:
21    st.sidebar.info(f"Alerte: {cond} {val}")

6. Espace Communautaire

Système de commentaires et interactions entre utilisateurs.

 1# Table BDD
 2c.execute('''CREATE TABLE IF NOT EXISTS comments
 3             (id INTEGER PRIMARY KEY AUTOINCREMENT,
 4              username TEXT,
 5              comment TEXT,
 6              timestamp DATETIME)''')
 7
 8# Publication
 9comment = st.text_area("Votre commentaire")
10if st.button("Publier"):
11    c.execute('''INSERT INTO comments (username, comment, timestamp)
12                 VALUES (?, ?, ?)''',
13              (username, comment, datetime.now()))
14
15# Affichage
16comments = c.execute('''SELECT username, comment, timestamp
17                        FROM comments ORDER BY timestamp DESC''').fetchall()
18for user, cmt, time in comments:
19    st.markdown(f"**{user}** - {time.strftime('%d/%m/%Y %H:%M')}: {cmt}")

7. Analyse Technique Avancée

Calcul et visualisation des indicateurs techniques.

 1def calculate_rsi(prices, period=14):
 2    delta = prices.diff().dropna()
 3    gain = delta.where(delta > 0, 0)
 4    loss = -delta.where(delta < 0, 0)
 5
 6    avg_gain = gain.rolling(period).mean()
 7    avg_loss = loss.rolling(period).mean()
 8
 9    rs = avg_gain / avg_loss
10    return 100 - (100 / (1 + rs))
11
12def calculate_macd(prices, slow=26, fast=12):
13    ema_slow = prices.ewm(span=slow).mean()
14    ema_fast = prices.ewm(span=fast).mean()
15    return ema_fast - ema_slow

Architecture principale

Diagramme de Cas d'Utilisation