HI. hope you are well. Please write me an advanced code that i can run in the morning before market opens and have it search the internet for latest breaking news on different stocks and then, either by itself or by training a model if need be, determine if the news is significant enough that it will affect market prices that day and then output/print to console as well as save to a .csv file, the results it finds. (the results being, the market or markets that it found that could be affected by the news, the percent chance that it has of actually affecting it, and have it timestamped so i can review it later if i wish. Im running windows 10 and i use visual studio code and the python extension in vscode.
Assistant
Certainly! Below is a Python script that you can run before the market opens to fetch the latest breaking news on different stocks, analyze the significance of the news, and output the results to both the console and a CSV file. This script uses the NewsAPI to fetch news articles and performs sentiment analysis using the TextBlob library to estimate the potential impact on the stock prices.
Please note:
You will need to obtain an API key from NewsAPI.org (it's free for basic usage).
Ensure you have Python installed, along with the necessary libraries (requests, pandas, TextBlob).
python
import requests
import pandas as pd
from textblob import TextBlob
from datetime import datetime
import time
# Replace 'YOUR_NEWSAPI_KEY' with your actual NewsAPI key
NEWS_API_KEY = 'YOUR_NEWSAPI_KEY'
# List of stock symbols to monitor
stock_symbols = ['AAPL', 'GOOGL', 'AMZN', 'MSFT', 'TSLA'] # You can add more symbols as needed
# Function to fetch news articles for a given stock symbol
def fetch_news(stock_symbol):
url = ('https://newsapi.org/v2/everything?'
'q={}&'
'language=en&'
'sortBy=publishedAt&'
'apiKey={}'.format(stock_symbol, NEWS_API_KEY))
response = requests.get(url)
data = response.json()
return data['articles']
# Function to analyze the sentiment of an article's title and description
def analyze_sentiment(text):
analysis = TextBlob(text)
return analysis.sentiment.polarity # Returns a value between -1.0 (negative) and 1.0 (positive)
# Main function to process news and evaluate significance
def process_news():
results = []
for symbol in stock_symbols:
print(f"\nFetching news for {symbol}...")
articles = fetch_news(symbol)
for article in articles:
title = article['title']
description = article['description'] or ''
content = article['content'] or ''
combined_text = ' '.join([title, description, content])
# Perform sentiment analysis
sentiment_score = analyze_sentiment(combined_text)
# Determine the significance based on sentiment_score magnitude
significance = abs(sentiment_score) # Higher absolute value indicates more significant news
# Estimate the percent chance of affecting the stock (for simplicity, scale significance)
percent_chance = min(100, significance * 100)
# Timestamp
timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
# Save the result
result = {
'Timestamp': timestamp,
'Stock Symbol': symbol,
'News Title': title,
'Sentiment Score': sentiment_score,
'Percent Chance of Impact': percent_chance,
'News URL': article['url']
}
results.append(result)
# Print to console
print(f"[{timestamp}] {symbol} - Sentiment: {sentiment_score:.2f}, "
f"Impact Chance: {percent_chance:.2f}%\nTitle: {title}\n")
# Pause briefly to comply with API rate limits
time.sleep(0.1)
# Save results to CSV
df = pd.DataFrame(results)
output_filename = f"stock_news_analysis_{datetime.utcnow().strftime('%Y%m%d')}.csv"
df.to_csv(output_filename, index=False)
print(f"\nResults saved to {output_filename}")
if __name__ == "__main__":
process_news()
Instructions to Run the Script:
Install Required Libraries:
Open your command prompt or terminal and run:
bash
pip install requests pandas textblob
For the TextBlob library, you also need to download the necessary NLTK corpora: