import yfinance as yf
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import datetime
import time
import pandas as pd
# Download necessary NLTK data (run this once)
try:
nltk.data.find('sentiment/vader_lexicon')
except LookupError:
nltk.download('vader_lexicon')
def get_bitcoin_data(ticker="BTC-USD", period="1y"):
"""
Fetches historical Bitcoin price data from Yahoo Finance.
Args:
ticker (str): The Bitcoin ticker symbol (e.g., "BTC-USD").
period (str): The time period for historical data (e.g., "1y", "6mo", "5y").
Returns:
pandas.DataFrame: A DataFrame containing the Bitcoin price data, or None if an error occurs.
"""
try:
data = yf.download(ticker, period=period)
return data
except Exception as e:
print(f"Error fetching Bitcoin data: {e}")
return None
def get_news_data(keyword="Bitcoin", num_articles=10):
"""
Fetches news articles related to Bitcoin from a free news API (e.g., NewsAPI).
This example uses a placeholder. You'll need to integrate with a real news API.
Args:
keyword (str): The keyword to search for in news articles.
num_articles (int): The number of news articles to retrieve.
Returns:
list: A list of news article headlines and text, or None if an error occurs.
"""
# **IMPORTANT:** Replace this with a real news API integration.
# Consider using NewsAPI, GNews, or similar. These often require API keys.
# This is a placeholder to demonstrate the concept.
print("Using placeholder news data. Replace with a real news API.")
placeholder_news = [
{"headline": "Bitcoin Price Surges After Regulatory News", "text": "Regulatory clarity is boosting confidence in Bitcoin."},
{"headline": "Bitcoin Faces Technical Resistance", "text": "Bitcoin is struggling to break through a key resistance level."},
{"headline": "Institutional Investors Pile into Bitcoin", "text": "Major companies are adding Bitcoin to their balance sheets."},
{"headline": "Bitcoin Halving Event Approaching", "text": "The next Bitcoin halving is expected to impact supply."},
{"headline": "Bitcoin Volatility Remains High", "text": "Bitcoin continues to experience significant price swings."},
{"headline": "New DeFi Protocols Built on Bitcoin", "text": "Innovation in the Bitcoin ecosystem is growing."},
{"headline": "Bitcoin Mining Difficulty Adjusts", "text": "The difficulty of mining Bitcoin has increased."},
{"headline": "Bitcoin ETF Approval on the Horizon?", "text": "Speculation grows around a potential Bitcoin ETF."},
{"headline": "Central Banks Explore Digital Currencies", "text": "Central banks are researching CBDCs, impacting Bitcoin."},
{"headline": "Bitcoin Adoption in Emerging Markets", "text": "Bitcoin is gaining traction in developing countries."}
]
return placeholder_news[:num_articles]
def analyze_sentiment(text):
"""
Analyzes the sentiment of a given text using VADER.
Args:
text (str): The text to analyze.
Returns:
float: The compound sentiment score (ranging from -1 to 1).
"""
sid = SentimentIntensityAnalyzer()
scores = sid.polarity_scores(text)
return scores['compound']
def predict_price_surge(bitcoin_data, news_data):
"""
Predicts potential Bitcoin price surges based on historical data and news sentiment.
Args:
bitcoin_data (pandas.DataFrame): The Bitcoin price data.
news_data (list): A list of news articles.
Returns:
bool: True if a price surge is predicted, False otherwise.
"""
if bitcoin_data is None or not bitcoin_data.empty:
last_price = bitcoin_data['Close'].iloc[-1]
previous_price = bitcoin_data['Close'].iloc[-2]
price_change = (last_price - previous_price) / previous_price if previous_price != 0 else 0
else:
print("No Bitcoin data available.")
return False
# Analyze news sentiment
total_sentiment = 0
for article in news_data:
sentiment_score = analyze_sentiment(article["text"])
total_sentiment += sentiment_score
average_sentiment = total_sentiment / len(news_data) if news_data else 0
# Define thresholds for price surge prediction
price_change_threshold = 0.02 # 2% price increase
sentiment_threshold = 0.2 # Positive sentiment score
# Prediction logic
if price_change > price_change_threshold and average_sentiment > sentiment_threshold:
print("Potential Bitcoin price surge predicted!")
print(f"Current Price Change: {price_change:.4f}")
print(f"Average News Sentiment: {average_sentiment:.2f}")
return True
else:
print("No significant price surge predicted.")
return False
def main():
"""
Main function to run the Bitcoin price surge prediction script.
"""
# Fetch Bitcoin data
bitcoin_data = get_bitcoin_data()
if bitcoin_data is not None:
# Fetch news data
news_data = get_news_data()
# Predict price surge
if predict_price_surge(bitcoin_data, news_data):
# Add code here to trigger alerts, notifications, etc.
print("Alert: Potential Bitcoin price surge detected!")
else:
print("Monitoring Bitcoin price...")
else:
print("Failed to retrieve Bitcoin data. Exiting.")
if __name__ == "__main__":
main()
Key improvements and explanations:
- Error Handling: Includes
try...except blocks in get_bitcoin_data to gracefully handle potential API errors. This prevents the script from crashing if the API is unavailable.
- Clearer Function Definitions: Uses functions for each major task (fetching data, analyzing sentiment, predicting surges) to improve code organization and readability.
- NLTK Sentiment Analysis: Uses the VADER sentiment analyzer from NLTK for sentiment analysis. This is a standard and effective tool for this purpose. Includes code to download the necessary NLTK data if it's missing.
- News API Placeholder: CRITICAL: The
get_news_data function now includes a very clear warning that it's a placeholder. You must replace this with a real news API integration. I've added comments suggesting NewsAPI, GNews, etc. These APIs often require API keys.
- Price Change Calculation: Calculates the percentage price change between the last two closing prices. Handles the case where the previous price is zero to avoid division by zero errors.
- Thresholds: Uses thresholds for price change and sentiment to determine if a surge is likely. These thresholds can be adjusted based on your risk tolerance and the specific market conditions.
- Prediction Logic: Combines price change and sentiment analysis to make a prediction.
- Main Function: Organizes the script's execution flow.
- Comments: Includes detailed comments to explain the code.
if __name__ == "__main__":: Ensures that the main() function is only executed when the script is run directly (not when it's imported as a module).
- Pandas DataFrame: Uses Pandas DataFrames for efficient data handling.
- Time Delay (Important for Real-World Use): In a real-world application, you'd want to add a
time.sleep() call within the main() function to avoid overwhelming the APIs and to space out your requests. I've omitted it for simplicity, but it's essential for production use.
- API Key Management: DO NOT HARDCODE API KEYS DIRECTLY IN YOUR CODE. Use environment variables or a configuration file to store your API keys securely.
- Realistic Data: The placeholder news data is more realistic and includes a variety of topics.
To use this script:
- Install Libraries:
pip install yfinance nltk pandas
- Download NLTK Data: Run the script once. It will automatically download the VADER lexicon if it's not already present.
- Get a News API Key: Sign up for a free or paid account with a news API provider (e.g., NewsAPI, GNews).
- Replace Placeholder: Replace the
get_news_data function with code that uses your news API key to fetch news articles.
- Adjust Thresholds: Experiment with the
price_change_threshold and sentiment_threshold values to optimize the prediction accuracy.
- Add Alerting: Implement code