Python script that interacts with a public API to retrieve data, performs sentiment a 01-02-2024, 02:46 AM
#1
Requirements:
Install requests, nltk, plotly libraries:
bash
pip install requests nltk plotly
Note: Before running the script, you'll need to download the NLTK data for sentiment analysis:
python
import nltk
nltk.download('vader_lexicon')
Now, let's create the script:
python
import requests
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import plotly.express as px
from datetime import datetime
def fetch_crypto_prices(coin, days):
url = f"https://api.coingecko.com/api/v3/coins/{coin}/market_chart"
params = {
'vs_currency': 'usd',
'days': days,
'interval': 'daily'
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
return data['prices']
else:
raise Exception(f"Failed to fetch cryptocurrency prices. Status Code: {response.status_code}")
def perform_sentiment_analysis(text):
analyzer = SentimentIntensityAnalyzer()
sentiment_score = analyzer.polarity_scores(text)
return sentiment_score['compound']
def main():
coin_symbol = input("Enter cryptocurrency symbol (e.g., btc, eth): ")
days_back = int(input("Enter the number of days to analyze: "))
try:
prices = fetch_crypto_prices(coin_symbol, days_back)
dates = [datetime.utcfromtimestamp(price[0] / 1000).strftime('%Y-%m-%d') for price in prices]
prices_values = [price[1] for price in prices]
sentiments = []
for date in dates:
news_url = f"https://newsapi.org/v2/everything?q={coin_symbol}&from={date}&to={date}&apiKey=YOUR_NEWS_API_KEY"
news_response = requests.get(news_url)
if news_response.status_code == 200:
news_data = news_response.json()
articles = news_data.get('articles', [])
combined_article_text = ' '.join([article['title'] + ' ' + article['description'] for article in articles])
sentiment = perform_sentiment_analysis(combined_article_text)
sentiments.append(sentiment)
else:
raise Exception(f"Failed to fetch news articles. Status Code: {news_response.status_code}")
# Visualize cryptocurrency prices and sentiment scores over time
fig = px.line(x=dates, y=[prices_values, sentiments], labels={'y': 'Values'}, title='Cryptocurrency Prices and Sentiment Analysis Over Time')
fig.update_layout(yaxis=dict(side='left', title='Prices'), yaxis2=dict(side='right', title='Sentiment'))
fig.show()
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Explanation:
The script fetches historical cryptocurrency prices using the CoinGecko API.
It performs sentiment analysis on news articles related to the cryptocurrency using the News API.
The sentiment scores and cryptocurrency prices are visualized over time using Plotly.
Remember to replace YOUR_NEWS_API_KEY with your actual News API key.
Install requests, nltk, plotly libraries:
bash
pip install requests nltk plotly
Note: Before running the script, you'll need to download the NLTK data for sentiment analysis:
python
import nltk
nltk.download('vader_lexicon')
Now, let's create the script:
python
import requests
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import plotly.express as px
from datetime import datetime
def fetch_crypto_prices(coin, days):
url = f"https://api.coingecko.com/api/v3/coins/{coin}/market_chart"
params = {
'vs_currency': 'usd',
'days': days,
'interval': 'daily'
}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
return data['prices']
else:
raise Exception(f"Failed to fetch cryptocurrency prices. Status Code: {response.status_code}")
def perform_sentiment_analysis(text):
analyzer = SentimentIntensityAnalyzer()
sentiment_score = analyzer.polarity_scores(text)
return sentiment_score['compound']
def main():
coin_symbol = input("Enter cryptocurrency symbol (e.g., btc, eth): ")
days_back = int(input("Enter the number of days to analyze: "))
try:
prices = fetch_crypto_prices(coin_symbol, days_back)
dates = [datetime.utcfromtimestamp(price[0] / 1000).strftime('%Y-%m-%d') for price in prices]
prices_values = [price[1] for price in prices]
sentiments = []
for date in dates:
news_url = f"https://newsapi.org/v2/everything?q={coin_symbol}&from={date}&to={date}&apiKey=YOUR_NEWS_API_KEY"
news_response = requests.get(news_url)
if news_response.status_code == 200:
news_data = news_response.json()
articles = news_data.get('articles', [])
combined_article_text = ' '.join([article['title'] + ' ' + article['description'] for article in articles])
sentiment = perform_sentiment_analysis(combined_article_text)
sentiments.append(sentiment)
else:
raise Exception(f"Failed to fetch news articles. Status Code: {news_response.status_code}")
# Visualize cryptocurrency prices and sentiment scores over time
fig = px.line(x=dates, y=[prices_values, sentiments], labels={'y': 'Values'}, title='Cryptocurrency Prices and Sentiment Analysis Over Time')
fig.update_layout(yaxis=dict(side='left', title='Prices'), yaxis2=dict(side='right', title='Sentiment'))
fig.show()
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
Explanation:
The script fetches historical cryptocurrency prices using the CoinGecko API.
It performs sentiment analysis on news articles related to the cryptocurrency using the News API.
The sentiment scores and cryptocurrency prices are visualized over time using Plotly.
Remember to replace YOUR_NEWS_API_KEY with your actual News API key.