hello. can we enhance this code somehow.. maybe using some advanced AI that no one has…
- User
hello. can we enhance this code somehow.. maybe using some advanced AI that no one has ever heard of? and i need the stock symbol and the Percent Chance of Impact much more than the acual news but i wouldnt mind having the headlines though so i somewhat know what is happening. here is the current code. please update it and then send me the full complete updated code please..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 = '003e077183a241899a8a141754ff2a48'
List of stock symbols to monitor
stock_symbols = ['KO', 'MCD', 'PG', 'NKE', 'HD', 'JNJ', 'PFE', 'MRK', 'ABT', 'LLY', 'NVDA', 'AMD', 'INTC', 'TSM', 'MGM', 'FL', 'CSCO', 'ORCL', 'SAP', 'IBM', 'RIGL', 'IONQ', 'D-WAVE', 'QUAN'] # 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) # Convert the results into a DataFrame df = pd.DataFrame(results) # Sort the DataFrame by 'Percent Chance of Impact' in descending order df_sorted = df.sort_values(by='Percent Chance of Impact', ascending=False) # Display summary of stocks sorted by 'Percent Chance of Impact' print("\n=== SUMMARY: Stocks Sorted by Impact Chance ===") for index, row in df_sorted.iterrows(): print(f"{row['Stock Symbol']}: {row['Percent Chance of Impact']:.2f}% chance, Title: {row['News Title']}") # Save the sorted DataFrame to a CSV file output_filename = f"stock_news_analysis_{datetime.utcnow().strftime('%Y%m%d')}.csv" df_sorted.to_csv(output_filename, index=False) print(f"\nResults saved to {output_filename}") - Assistant