Create a python script the takes in market data and news from free/delayed sources and uses that information to predict potential price surges for bitcoin
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python script that collects market data and news from free/delayed sources to predict potential price surges for Bitcoin. The script uses technical indicators and sentiment analysis to make predictions.
python
import requests
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from textblob import TextBlob
import talib
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Configuration
API_KEYS = {
'coinmarketcap': 'YOUR_COINMARKETCAP_API_KEY', # Get from https://coinmarketcap.com/api/
'newsapi': 'YOUR_NEWS_API_KEY' # Get from https://newsapi.org/
}
# Constants
BTC_ID = '1' # Bitcoin's ID on CoinMarketCap
LOOKBACK_DAYS = 30 # Number of days to look back for historical data
PREDICTION_HORIZON = 3 # Days ahead to predict
SURGE_THRESHOLD = 0.05 # 5% price increase considered a surge
def fetch_market_data():
"""Fetch Bitcoin market data from CoinMarketCap API"""
url = f"https://pro-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical"
parameters = {
'symbol': 'BTC',
'time_start': (datetime.now() - timedelta(days=LOOKBACK_DAYS)).isoformat(),
'time_end': datetime.now().isoformat(),
'interval': 'daily'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': API_KEYS['coinmarketcap']
}
try:
response = requests.get(url, headers=headers, params=parameters)
data = response.json()
df = pd.DataFrame(data['data']['quotes'])
# Convert to datetime and set as index
df['time_open'] = pd.to_datetime(df['time_open'], unit='ms')
df.set_index('time_open', inplace=True)
# Calculate daily returns
df['close'] = df['quote.USD.close']
df['returns'] = df['close'].pct_change()
return df
except Exception as e:
print(f"Error fetching market data: {e}")
return None
def fetch_news_sentiment():
"""Fetch Bitcoin-related news and analyze sentiment"""
url = 'https://newsapi.org/v2/everything'
parameters = {
'q': 'bitcoin OR crypto OR cryptocurrency',
'from': (datetime.now() - timedelta(days=LOOKBACK_DAYS)).strftime('%Y-%m-%d'),
'sortBy': 'publishedAt',
'pageSize': 100,
'apiKey': API_KEYS['newsapi']
}
try:
response = requests.get(url, params=parameters)
data = response.json()
articles = data['articles']
sentiments = []
for article in articles:
analysis = TextBlob(article['title'] + " " + article['description'])
sentiments.append(analysis.sentiment.polarity)
# Calculate average sentiment
avg_sentiment = np.mean(sentiments) if sentiments else 0
return avg_sentiment
except Exception as e:
print(f"Error fetching news data: {e}")
return 0
def calculate_technical_indicators(df):
"""Calculate technical indicators for price prediction"""
# Simple Moving Averages
df['SMA_5'] = talib.SMA(df['close'], timeperiod=5)
df['SMA_20'] = talib.SMA(df['close'], timeperiod=20)
# Relative Strength Index
df['RSI'] = talib.RSI(df['close'], timeperiod=14)
# Moving Average Convergence Divergence
df['MACD'], df['MACD_signal'], _ = talib.MACD(df['close'])
# Bollinger Bands
df['upper_band'], df['middle_band'], df['lower_band'] = talib.BBANDS(df['close'])
# Stochastic Oscillator
df['slowk'], df['slowd'] = talib.STOCH(df['high'], df['low'], df['close'])
# Price Rate of Change
df['ROC'] = talib.ROC(df['close'], timeperiod=10)
return df
def create_features(df, sentiment):
"""Create features for machine learning model"""
# Shift features to align with prediction horizon
df['target'] = (df['close'].shift(-PREDICTION_HORIZON) / df['close'] - 1) > SURGE_THRESHOLD
# Drop rows with NaN values (from shifting)
df = df.dropna()
# Features
features = [
'SMA_5', 'SMA_20', 'RSI', 'MACD', 'MACD_signal',
'upper_band', 'middle_band', 'lower_band',
'slowk', 'slowd', 'ROC', 'returns', 'sentiment'
]
X = df[features]
y = df['target']
return X, y
def train_model(X, y):
"""Train a Random Forest classifier for price surge prediction"""
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Evaluate model
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.2f}")
return model
def predict_surge(model, df, sentiment):
"""Make a prediction for the next period"""
# Get the most recent data point
latest_data = df.iloc[-1].copy()
latest_data['sentiment'] = sentiment
# Reshape for prediction
X_pred = latest_data[model.feature_importances_.index].values.reshape(1, -1)
# Make prediction
prediction = model.predict(X_pred)
probability = model.predict_proba(X_pred)
return prediction[0], probability[0][1] # Return prediction and probability
def plot_results(df, prediction, probability):
"""Plot historical data and prediction"""
plt.figure(figsize=(12, 6))
# Plot price
plt.plot(df.index, df['close'], label='BTC Price', color='blue')
# Plot moving averages
plt.plot(df.index, df['SMA_5'], label='5-day SMA', linestyle='--', color='green')
plt.plot(df.index, df['SMA_20'], label='20-day SMA', linestyle='--', color='red')
# Highlight prediction period
last_date = df.index[-1]
prediction_date = last_date + timedelta(days=PREDICTION_HORIZON)
plt.axvspan(last_date, prediction_date, color='gray', alpha=0.2, label='Prediction Window')
# Add prediction annotation
if prediction:
plt.annotate(
f"Surge Predicted ({probability:.0%})",
xy=(prediction_date, df['close'].iloc[-1] * 1.05),
xytext=(prediction_date, df['close'].iloc[-1] * 1.1),
arrowprops=dict(facecolor='green', shrink=0.05),
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5)
)
else:
plt.annotate(
f"No Surge Predicted ({1-probability:.0%})",
xy=(prediction_date, df['close'].iloc[-1] * 1.05),
xytext=(prediction_date, df['close'].iloc[-1] * 1.1),
arrowprops=dict(facecolor='red', shrink=0.05),
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5)
)
plt.title('Bitcoin Price with Technical Indicators and Prediction')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()
def main():
print("Fetching market data...")
market_data = fetch_market_data()
if market_data is None:
print("Failed to fetch market data. Exiting.")
return
print("Calculating technical indicators...")
market_data = calculate_technical_indicators(market_data)
print("Fetching news sentiment...")
sentiment = fetch_news_sentiment()
print("Creating features for model...")
X, y = create_features(market_data, sentiment)
print("Training model...")
model = train_model(X, y)
print("Making prediction...")
prediction, probability = predict_surge(model, market_data, sentiment)
print("\nPrediction Results:")
print(f"Surge Prediction: {'Yes' if prediction else 'No'}")
print(f"Probability of Surge: {probability:.2%}")
plot_results(market_data, prediction, probability)
if __name__ == "__main__":
main()
How This Script Works:
Data Collection:
Fetches historical Bitcoin price data from CoinMarketCap API
Collects Bitcoin-related news articles from NewsAPI and analyzes sentiment
Technical Analysis:
Calculates various technical indicators:
Simple Moving Averages (5-day and 20-day)
Relative Strength Index (RSI)
Moving Average Convergence Divergence (MACD)
Bollinger Bands
Stochastic Oscillator
Rate of Change (ROC)
Machine Learning Model:
Uses a Random Forest classifier to predict price surges
Defines a surge as a 5% price increase over the next 3 days
Uses historical data to train the model
Prediction:
Makes a prediction based on current market conditions and news sentiment