Here's error i receive, what can it be. Any ideas?
INFO: root:Fetched Bitcoin news successfully! INFO:root:Average sentiment of the latest news: 0.38 INFO:root:Raw Response from CoinMarketCap: {'status': {'timestamp': '2025-02-03T16:46:55.598Z', 'error_code': 0, 'error_message': None, 'elapsed': 40, 'credit_count': 1, 'notice': None}, 'data': {'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'quotes': [{'time_open': '2025-01-05T00:00:00.000Z', 'time_close': '2025-01-05T23:59:59.999Z', 'time_high': '2025-01-05T23:03:00.000Z', 'time_low': '2025-01-05T14:21:00.000Z', 'quote': {'USD': {'open': 98233.90577658577, 'high': 98813.30855441149, 'low': 97291.76460634715, 'close': 98314.95944363723, 'volume': 20525254824.64, 'market_cap': 1947189546143.58, 'timestamp': '2025-01-05T23:59:59.999Z'}}}, ERROR:root:Invalid response structure or no historical data found. ERROR:root:Failed to fetch historical Bitcoin data. ERROR:root:Failed to predict Bitcoin price.
import os
import requests
import numpy as np
import matplotlib.pyplot as plt
import logging
from datetime import datetime, timedelta, timezone
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from dotenv import load_dotenv, dotenv_values
# Download the vader_lexicon
nltk.download('vader_lexicon')
# Load environment variables
load_dotenv(dotenv_path="MainKeys.env")
env_vars = dotenv_values(".env") # Loads environment variables as a dictionary
print(env_vars) # For debugging: should show your API keys
# Retrieve API keys
NEWS_API_KEY = os.getenv('NEWS_API_KEY')
COINMARKETCAP_API_KEY = os.getenv('COINMARKETCAP_API_KEY')
# Set up logging
logging.basicConfig(level=logging.INFO)
def get_bitcoin_news(api_key, page_size=5):
url = ''
params = {'q': 'bitcoin', 'apiKey': api_key, 'language': 'en', 'sortBy': 'publishedAt', 'pageSize': page_size}
try:
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logging.error(f"Error fetching Bitcoin news: {e}")
return None
def get_historical_bitcoin_data(api_key, start_date, end_date):
url = ''
params = {'id': 1, 'convert': 'USD', 'time_start': start_date, 'time_end': end_date, 'interval': 'daily'}
headers = {'X-CMC_PRO_API_KEY': api_key, 'Accept': 'application/json'}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
# Debugging: print the raw API response to understand the structure
logging.info(f"Raw Response from CoinMarketCap: {response.json()}")
data = response.json()
# Check for the 'data' key and validate structure
if 'data' not in data or 'BTC' not in data['data'] or 'quotes' not in data['data']['BTC']:
logging.error("Invalid response structure or no historical data found.")
return None
return data['data']['BTC']['quotes']
except requests.exceptions.RequestException as e:
logging.error(f"Error fetching historical Bitcoin data: {e}")
return None
def analyze_sentiment(news_data):
sid = SentimentIntensityAnalyzer()
sentiments = []
for article in news_data.get('articles', []):
title = article.get('title', '')
description = article.get('description', '')
text = f"{title} {description}".strip()
sentiment_score = sid.polarity_scores(text)
sentiments.append(sentiment_score['compound']) # Only storing compound score for simplicity
return sentiments
def predict_price(api_key):
# Get the current date and calculate the start date for one month ago
end_date = datetime.now(timezone.utc)
start_date = end_date - timedelta(days=30)
# Format dates as YYYY-MM-DD strings
start_date_str = start_date.strftime('%Y-%m-%d')
end_date_str = end_date.strftime('%Y-%m-%d')
# Fetch the historical Bitcoin data for the last month
historical_data = get_historical_bitcoin_data(api_key, start_date_str, end_date_str)
if not historical_data:
logging.error("Failed to fetch historical Bitcoin data.")
return None
# Extract prices and dates
prices = [item.get('close', 0) for item in historical_data]
dates = [item.get('time_open', '').split('T')[0] for item in historical_data] # Extract only the date part
if len(prices) == 0 or len(dates) == 0:
logging.error("No historical price data available.")
return None
years = np.array([int(date.split('-')[0]) for date in dates]).reshape(-1, 1)
# Using Polynomial Regression
model = make_pipeline(PolynomialFeatures(2), LinearRegression())
model.fit(years, prices)
# Predict future Bitcoin price for 2025
future_year = np.array([[2025]])
predicted_price = model.predict(future_year)
plot_bitcoin_prices(years, prices, future_year, predicted_price)
return predicted_price[0]
def plot_bitcoin_prices(years, prices, future_year, predicted_price):
plt.figure(figsize=(8, 6))
plt.plot(years, prices, color='blue', label='Historical Prices')
plt.plot(future_year, predicted_price, 'ro', label=f'Predicted Price (2025): ${predicted_price[0]:.2f}')
plt.xlabel("Year")
plt.ylabel("Price (in USD)")
plt.title("Bitcoin Price Prediction")
plt.legend(loc="upper left")
plt.grid(True)
plt.show()
def main():
if not NEWS_API_KEY or not COINMARKETCAP_API_KEY:
logging.error("Missing API keys. Set them in the .env file.")
return
# Fetch Bitcoin news and analyze sentiment
news = get_bitcoin_news(NEWS_API_KEY)
if news and news.get('status') == 'ok':
logging.info("Fetched Bitcoin news successfully!")
sentiments = analyze_sentiment(news)
if sentiments:
avg_sentiment = np.mean(sentiments)
logging.info(f"Average sentiment of the latest news: {avg_sentiment:.2f}")
else:
logging.warning("No valid sentiment data available.")
else:
logging.error("Failed to fetch Bitcoin news")
# Predict Bitcoin price in 2025
predicted_price = predict_price(COINMARKETCAP_API_KEY)
if predicted_price is not None:
logging.info(f"Predicted Bitcoin Price in 2025: ${predicted_price:.2f}")
else:
logging.error("Failed to predict Bitcoin price.")
if __name__ == '__main__':
main()