def get_bitcoin_data():
"""
Utilise yfinance pour récupérer les données actuelles et historiques de Bitcoin.
code
Assistant
Returns:
dict: Contient le prix actuel, les sentiments du marché, etc.
"""
try:
btc = yf.Ticker("BTC-USD")
eth = yf.Ticker("ETH-USD")
sp500 = yf.Ticker("^GSPC")
vix = yf.Ticker("^VIX")
# Définition de la période pour les données historiques (150 jours pour une meilleure couverture)
end_date = datetime.today()
start_date = end_date - timedelta(days=150)
# Récupération des données historiques
btc_hist = btc.history(start=start_date, end=end_date)
eth_hist = eth.history(start=start_date, end=end_date)
sp500_hist = sp500.history(start=start_date, end=end_date)
vix_hist = vix.history(start=start_date, end=end_date)
# Prix actuel
current_price = btc_hist['Close'][-1] if not btc_hist.empty else BASE_PRICE
# Historique des 30 derniers jours pour calculer les tendances
btc_recent_hist = btc_hist.tail(30)
if not btc_recent_hist.empty:
mean_price = btc_recent_hist['Close'].mean()
price_trend = (current_price - mean_price) / mean_price # Normalisation
else:
price_trend = 0.0
# Sentiment basé sur les variations récentes
recent_changes = btc_recent_hist['Close'].pct_change().dropna()
sentiment_score = recent_changes.mean() # Moyenne des variations
# Adoption Institutionnelle : Utilisation des volumes
avg_volume = btc_recent_hist['Volume'].mean()
current_volume = btc_recent_hist['Volume'][-1] if not btc_recent_hist.empty else avg_volume
adoption_score = (current_volume / avg_volume) - 1 # Normalisé
# Conditions Économiques : Utilisation de l'indicateur VIX comme proxy
if not vix_hist.empty:
avg_vix = vix_hist['Close'].mean()
current_vix = vix_hist['Close'][-1]
economic_conditions = (avg_vix - current_vix) / avg_vix # Normalisé
else:
economic_conditions = 0.0
# Évolution Technologique : Utiliser la volatilité comme proxy supplémentaire
if not btc_recent_hist.empty:
volatility = btc_recent_hist['Close'].std()
tech_evolution = volatility / btc_recent_hist['Close'].mean() # Normalisé
else:
tech_evolution = 0.0
# Réglementation : Utilisation de la volatilité comme proxy
if not btc_hist.empty:
volatility = btc_hist['Close'].std()
# Comparer la volatilité actuelle avec une moyenne historique sur 3 mois
hist_extended = btc.history(start=start_date - timedelta(days=90), end=start_date)
if not hist_extended.empty:
mean_volatility = hist_extended['Close'].std()
regulation_score = (volatility - mean_volatility) / mean_volatility
else:
regulation_score = volatility / btc_hist['Close'].std() # Simplifié
else:
regulation_score = 0.0
# Concurrence : Comparer la performance avec Ethereum
if not eth_hist.empty and not btc_hist.empty:
btc_return = (btc_hist['Close'][-1] / btc_hist['Close'][0]) - 1
eth_return = (eth_hist['Close'][-1] / eth_hist['Close'][0]) - 1
concurrence_score = btc_return - eth_return # Positive si BTC performe mieux
else:
concurrence_score = 0.0
# Intégration Financière : Corrélation avec le S&P 500
if not sp500_hist.empty and not btc_hist.empty:
# Calculer les rendements journaliers
btc_returns = btc_hist['Close'].pct_change().dropna()
sp500_returns = sp500_hist['Close'].pct_change().dropna()
# Aligner les dates
btc_returns_aligned, sp500_returns_aligned = btc_returns.align(sp500_returns, join='inner')
# Vérifier qu'il y a suffisamment de points de données
if len(btc_returns_aligned) >= 30:
corr = btc_returns_aligned.corr(sp500_returns_aligned)
if pd.notnull(corr):
# Normaliser la corrélation de [-1, 1] à [0, 1]
integration_financiere = (corr + 1) / 2
else:
integration_financiere = 0.5 # Valeur neutre si corr NaN
else:
integration_financiere = 0.5 # Valeur neutre par défaut
else:
integration_financiere = 0.5 # Valeur neutre par défaut
# Facteurs Géopolitiques : Inverser le score du VIX comme proxy
if not vix_hist.empty:
geopolitiques = -economic_conditions # Plus le VIX est bas, moins d'incertitude
else:
geopolitiques = 0.0
# Événements Spéciaux : Utiliser les variations de prix soudaines
if not btc_recent_hist.empty:
daily_changes = btc_recent_hist['Close'].pct_change().abs()
# Définir un seuil, par exemple, 5% de variation en une journée
events = daily_changes > 0.05
evenements_speciaux = events.sum() # Nombre d'événements spéciaux
# Normaliser par rapport au nombre total de jours
evenements_speciaux = evenements_speciaux / len(btc_recent_hist)
else:
evenements_speciaux = 0.0
# Compilation des scores
factors = {
"Offre et Demande": price_trend,
"Sentiment du Marché": sentiment_score,
"Adoption Institutionnelle": adoption_score,
"Conditions Économiques": economic_conditions,
"Évolution Technologique": tech_evolution,
"Réglementation": regulation_score,
"Concurrence": concurrence_score,
"Intégration Financière": integration_financiere,
"Facteurs Géopolitiques": geopolitiques,
"Événements Spéciaux": evenements_speciaux
}
return factors
except Exception as e:
print(f"Erreur lors de la récupération des données via yfinance: {e}")
return {factor: 0.0 for factor in FACTORS_LIST}
def evaluate_factors():
"""
Évalue tous les facteurs en récupérant leurs scores respectifs via yfinance.
code
Returns:
dict: Dictionnaire contenant les noms des facteurs et leurs scores correspondants.
"""
factors = get_bitcoin_data()
return factors
def calculate_index(factors):
"""
Calcule l'indice global basé sur les scores des facteurs et leurs poids.
code
Args:
factors (dict): Dictionnaire des scores des facteurs.
Returns:
float: L'indice calculé.
"""
total_score = sum(score * WEIGHTS.get(factor, 1) for factor, score in factors.items())
return total_score
def plot_factors(factors):
"""
Affiche un graphique en barres horizontales des scores des facteurs.
code
Args:
factors (dict): Dictionnaire des scores des facteurs.
"""
# Effacer le graphique précédent
for widget in frame_plot.winfo_children():
widget.destroy()
factor_names = list(factors.keys())
scores = list(factors.values())
fig, ax = plt.subplots(figsize=(6, 4))
colors = ['green' if x >= 0 else 'red' for x in scores]
bars = ax.barh(factor_names, scores, color=colors)
ax.axvline(0, color='black')
ax.set_xlabel('Score')
ax.set_title('Évaluation des Facteurs')
# Ajouter les valeurs sur les barres
for bar in bars:
width = bar.get_width()
label_x = width + (0.02 if width >= 0 else -0.02)
alignment = 'left' if width >= 0 else 'right'
ax.text(label_x,
bar.get_y() + bar.get_height() / 2,
f"{width:.2f}",
va='center',
ha=alignment,
fontsize=8,
color='black')
plt.tight_layout()
canvas = FigureCanvasTkAgg(fig, master=frame_plot)
canvas.draw()
canvas.get_tk_widget().pack()
def update_results():
"""
Récupère les scores des facteurs, calcule l'indice, puis enfile les résultats pour la mise à jour de l'interface graphique.
"""
try:
factors = evaluate_factors()
index = calculate_index(factors)
# Enfiler les résultats pour que le thread principal les traite
result_queue.put((factors, index))
except Exception as e:
print(f"Erreur lors de la mise à jour des résultats: {e}")
result_queue.put(("error", str(e)))
def process_queue():
"""
Traite les éléments dans la result_queue et met à jour l'interface graphique en conséquence.
Cette fonction est programmée pour s'exécuter périodiquement à l'aide de la méthode after de Tkinter.
"""
try:
while not result_queue.empty():
result = result_queue.get_nowait()
if result[0] == "error":
# Gérer l'erreur
messagebox.showerror("Erreur", f"Une erreur est survenue lors de la mise à jour des résultats: {result[1]}")
label_result.config(text="Indice Prévisionnel : Erreur", fg="red")
else:
factors, index = result
# Afficher les scores des facteurs
for factor, score in factors.items():
tree.set(factor, "Score", f"{score:.4f}") # Augmenter la précision si nécessaire
code
# Afficher l'indice
if index > 0:
trend = "Hausse prévue 📈"
color = "green"
elif index < 0:
trend = "Baisse prévue 📉"
color = "red"
else:
trend = "Stable ➖"
color = "gray"
label_result.config(text=f"Indice Prévisionnel : {trend} (Score: {index:.2f})", fg=color)
# Afficher un graphique simple
plot_factors(factors)
except Exception as e:
print(f"Erreur lors du traitement de la file d'attente: {e}")
finally:
# Programmer la prochaine vérification de la queue
root.after(100, process_queue)
def update_results_threaded():
"""
Démarre la fonction update_results dans un thread séparé pour garder l'interface réactive.
"""
thread = threading.Thread(target=update_results)
thread.start()
Configuration de la fenêtre principale
root = tk.Tk()
root.title("Analyse du Prix du Bitcoin")
Configuration de la disposition
root.geometry("800x800") # Augmenter la taille pour mieux voir les changements
root.resizable(False, False)
Titre
title = ttk.Label(root, text="Prédicteur de Tendance Bitcoin", font=("Helvetica", 16))
title.pack(pady=10)
Appel initial à process_queue pour démarrer la vérification périodique
root.after(100, process_queue)
Exécution de la boucle principale
root.mainloop()
Your script for analyzing Bitcoin prices using Tkinter, yfinance, and various other libraries is well-structured and covers multiple aspects effectively. However, there are a few logical issues and areas for improvement that you might want to address to ensure robustness and accuracy. Below is a detailed analysis highlighting these points:
Issue: When hist_extended is empty, the fallback calculation sets regulation_score to 1.0, which might not be semantically correct.
Recommendation: Instead of defaulting to volatility / btc_hist['Close'].std(), consider setting regulation_score to a neutral value like 0.0 or another appropriate default when historical data is insufficient.
Issue: The requirement for at least 30 aligned data points might sometimes exclude valid datasets, especially if markets are closed on certain days.
Recommendation: Adjust the minimum required data points based on your specific needs or ensure that data gaps are appropriately handled.
3. Default Values and Fallbacks
BASE_PRICE Usage:
python
current_price = btc_hist['Close'][-1] if not btc_hist.empty else BASE_PRICE
Issue: Using a fixed BASE_PRICE of 50,000 when btc_hist is empty might skew the analysis, especially if actual prices deviate significantly from this base.
Recommendation: Consider alternative fallback mechanisms, such as notifying the user of data retrieval issues or using a more dynamic default based on available data.
integration_financiere Default:
python
integration_financiere = 0.5 # Valeur neutre par défaut
Issue: While setting a neutral value is generally acceptable, ensure that this aligns with your overall index calculations and interpretations.
Recommendation: Validate that default values across all factors maintain the integrity of the final index.
4. Factor Weighting and Naming Consistency
Factor Names Consistency:
Ensure that all keys in the factors dictionary precisely match those in FACTORS_LIST. Any mismatch can lead to missing scores or incorrect index calculations.
Weight Defaults:
python
total_score = sum(score * WEIGHTS.get(factor, 1) for factor, score in factors.items())
Issue: Using a default weight of 1 for unspecified factors might unintentionally include factors without intended weighting.
Recommendation: Ensure that all factors are accounted for in the WEIGHTS dictionary. If a factor is missing, it's better to raise an error or log a warning rather than assigning a default weight.
5. Thread Safety and Queue Handling
Queue Processing in process_queue:
python
while not result_queue.empty():
result = result_queue.get_nowait()
...
Issue: Rapidly processing all items in the queue without rate limiting might lead to performance issues if multiple threads enqueue data frequently.
Recommendation: Implement rate limiting or ensure that only one thread is enqueueing data at a time.
Issue: The label offset (0.02) is hard-coded and might not scale well with different score magnitudes.
Recommendation: Dynamically adjust label positions based on the plot's scale to ensure readability.
Responsive GUI Design:
Issue: Setting a fixed window size (800x800) can lead to UI elements being cramped or excessive empty space, depending on the user's screen resolution.
Recommendation: Consider making the window size responsive or allowing resizing while adjusting the layout dynamically.
7. Error Handling and User Feedback
Detailed Error Messages:
Currently, errors are printed to the console and shown in a message box. For better user experience:
Recommendation: Provide more context in error messages. For instance, specify which part of the data retrieval failed or suggest possible user actions.
Logging Mechanism:Issue: Relying solely on print statements for debugging isn't ideal for production environments.
Recommendation: Implement a logging mechanism using Python's logging module to capture and store logs systematically.
8. Performance Considerations
Thread Management:
Issue: Each time the "Évaluer" button is clicked, a new thread is spawned without any limit, which could lead to resource exhaustion if clicked rapidly.
Recommendation: Disable the button while a thread is running or implement a thread pool to manage concurrent executions.
Data Fetching Efficiency:
Issue: Fetching data for four tickers (BTC-USD, ETH-USD, ^GSPC, ^VIX) each time might be time-consuming.
Recommendation: Cache data where appropriate or implement incremental updates to reduce latency.
9. Code Maintainability and Readability
Consistent Naming Conventions:
Ensure that variable and function names are consistent and follow a clear naming convention. This improves readability and maintainability.
Modularization:
Issue: The get_bitcoin_data function is quite lengthy and handles multiple responsibilities.
Recommendation: Break it down into smaller, more focused functions. For example, separate data fetching from score calculations.
10. Sample Code Improvements
Below are specific code snippets addressing some of the aforementioned issues:
Preventing Division by Zero:
python
# Example for price_trend
if mean_price != 0:
price_trend = (current_price - mean_price) / mean_price
else:
price_trend = 0.0 # or another suitable default
Handling Empty hist_extended in Regulation:
python
if not hist_extended.empty:
mean_volatility = hist_extended['Close'].std()
if mean_volatility != 0:
regulation_score = (volatility - mean_volatility) / mean_volatility
else:
regulation_score = 0.0 # Neutral if mean_volatility is zero
else:
regulation_score = 0.0 # Neutral default instead of 1.0
Comprehensive Testing:
Conduct thorough testing, especially with edge cases such as:
No internet connection.
API rate limits being hit.
Unexpected data formats from yfinance.
Documentation:
Add docstrings and comments where necessary to explain complex logic, making the code easier to understand for others or for future maintenance.
User Interface Enhancements:
Consider adding features like:
Auto-refreshing data at set intervals.
Allowing users to select different cryptocurrencies or indices.
Providing more detailed analysis or historical trends.
By addressing these points, you can enhance the robustness, accuracy, and user experience of your Bitcoin analysis tool.