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 an example Python script that downloads free (delayed) Bitcoin market data via Yahoo Finance, pulls recent Bitcoin‐related news headlines from NewsAPI (a free news source with a limited free tier), performs simple technical and sentiment analyses, and then issues a basic “surge signal” if certain conditions are met. (Note: This is a simplified proof‐of‐concept and by no means a production-ready trading model.)
Prerequisites
Make sure you have installed the following Python packages:
You’ll also need to sign up for a (free) API key at NewsAPI.org and replace "YOUR_NEWS_API_KEY" with your actual key.
The Script
python
import yfinance as yf
import pandas as pd
import numpy as np
import requests
from datetime import datetime, timedelta
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
def fetch_market_data():
"""
Download Bitcoin price data (using Yahoo Finance’s free/delayed feed).
In this example, we fetch the last 30 days of hourly data.
"""
print("Downloading market data for BTC-USD...")
btc_data = yf.download("BTC-USD", period="30d", interval="1h")
if btc_data.empty:
raise Exception("No market data found. Please check your connection or ticker symbol.")
return btc_data
def compute_technical_indicators(df):
"""
Compute simple technical indicators:
- 20-period Simple Moving Average (SMA)
- 20-period Exponential Moving Average (EMA)
- 14-period Relative Strength Index (RSI)
"""
df['SMA_20'] = df['Close'].rolling(window=20).mean()
df['EMA_20'] = df['Close'].ewm(span=20, adjust=False).mean()
# RSI calculation function
def rsi(series, period=14):
delta = series.diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=period, min_periods=period).mean()
avg_loss = loss.rolling(window=period, min_periods=period).mean()
rs = avg_gain / avg_loss
rsi_values = 100 - (100 / (1 + rs))
return rsi_values
df['RSI'] = rsi(df['Close'], period=14)
return df
def fetch_news_articles(api_key):
"""
Retrieve recent Bitcoin news articles using the NewsAPI.
Note: The free plan may have limitations in terms of response delay, number of calls, etc.
"""
print("Fetching news articles...")
url = "https://newsapi.org/v2/everything"
# We query for "Bitcoin" and restrict to articles from the past day.
params = {
"q": "Bitcoin",
"language": "en",
"sortBy": "publishedAt",
"pageSize": 20,
"from": (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d'),
"to": datetime.now().strftime('%Y-%m-%d'),
"apiKey": api_key
}
response = requests.get(url, params=params)
if response.status_code == 200:
articles = response.json().get("articles", [])
print(f"Received {len(articles)} articles.")
return articles
else:
print("Error fetching news:", response.status_code, response.text)
return []
def analyze_sentiment(articles):
"""
Use Vader sentiment analysis on the concatenated headlines and descriptions from the news articles.
Returns the average compound score.
"""
analyzer = SentimentIntensityAnalyzer()
sentiment_scores = []
for article in articles:
title = article.get('title', '')
description = article.get('description', '')
content = f"{title}. {description}"
if content.strip():
score = analyzer.polarity_scores(content)["compound"]
sentiment_scores.append(score)
if sentiment_scores:
average_sentiment = np.mean(sentiment_scores)
else:
average_sentiment = 0.0
return average_sentiment
def predict_price_surge(market_df, news_sentiment):
"""
Issue simple surge/potential signals based on:
- Technical indicator (RSI below a threshold suggesting an oversold condition)
- Price above a simple moving average indicating upward momentum
- Positive news sentiment
These rules are basic and for demonstration purposes.
"""
latest = market_df.iloc[-1]
signals = []
# Example condition 1: Oversold condition with positive news sentiment
if latest['RSI'] < 30 and news_sentiment > 0.2:
signals.append("Surge Signal: RSI indicates oversold conditions coupled with positive news sentiment!")
# Example condition 2: Price above its 20-period SMA combined with positive sentiment
if latest['Close'] > latest['SMA_20'] and news_sentiment > 0.2:
signals.append("Momentum Signal: Price above SMA_20 with positive news sentiment.")
if not signals:
signals.append("No surge signal detected at this time.")
return signals
def main():
try:
# Step 1: Retrieve and process market data
market_data = fetch_market_data()
market_data = compute_technical_indicators(market_data)
print("\nLatest market data snapshot:")
print(market_data.tail(1))
# Step 2: Retrieve recent Bitcoin news (replace with your own NewsAPI key)
news_api_key = "YOUR_NEWS_API_KEY" # <-- Replace with your key
articles = fetch_news_articles(news_api_key)
news_sentiment = analyze_sentiment(articles)
print(f"\nAverage news sentiment score: {news_sentiment:.3f}")
# Step 3: Generate prediction signals
signals = predict_price_surge(market_data, news_sentiment)
print("\nPrediction signals:")
for signal in signals:
print(" -", signal)
except Exception as e:
print("An error occurred:", str(e))
if __name__ == "__main__":
main()
How It Works
Market Data Fetching & Technical Analysis:
The script uses the yfinance package to fetch the last 30 days of hourly Bitcoin (BTC-USD) data. It then computes:
SMA (20) and EMA (20): To get a sense of the moving average trend.
RSI (14): A momentum indicator where values below 30 may indicate an oversold market.
News Collection & Sentiment Analysis:
Using the NewsAPI, the script retrieves up to 20 recent articles related to Bitcoin. Each article’s title and description is run through VADER sentiment analysis to yield a compound sentiment score. The average compound sentiment (where scores above 0.2 are considered positive) is used as an input.
Prediction Logic:
Based on simple rules (e.g., RSI < 30 and positive news sentiment; or price above SMA combined with positive sentiment), the script prints potential surge signals.
Caveats and Next Steps
Data Source Limitations:
Yahoo Finance and NewsAPI provide free/delayed data that may not be timely enough for high-frequency trading.
Model Complexity:
In practice, you might want to incorporate more sophisticated machine learning models that ingest more features, longer historical data, order book information, etc.
Risk Management:
Any trading signal should be part of a larger risk-managed strategy.
This script is a starting point and can be extended/refined depending on your requirements and access to real-time/premium data sources.