Skip to content

Instantly share code, notes, and snippets.

@vitorcalvi
Created August 10, 2024 16:02
Show Gist options
  • Save vitorcalvi/225812f903529fa34cca600ab36f133e to your computer and use it in GitHub Desktop.
Save vitorcalvi/225812f903529fa34cca600ab36f133e to your computer and use it in GitHub Desktop.
import os
import logging
import requests
from alpaca.data.historical.news import NewsClient
from alpaca.data.requests import NewsRequest
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("news_data.log"), logging.StreamHandler()]
)
# Retrieve API credentials
API_KEY = os.getenv("ALPACA_API_KEY")
SECRET_KEY = os.getenv("ALPACA_SECRET_KEY")
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
def fetch_news(symbol, start_date, end_date):
try:
client = NewsClient(api_key=API_KEY, secret_key=SECRET_KEY)
request_params = NewsRequest(symbols=symbol, start=start_date, end=end_date)
df = client.get_news(request_params).df
if not df.empty:
logging.info(f"Alpaca found {len(df)} articles for {symbol}.")
return df
logging.info("No news found in Alpaca; falling back to NewsAPI.")
except Exception as e:
logging.error(f"Alpaca API error: {e}")
try:
response = requests.get(
f"https://newsapi.org/v2/everything?q={symbol}&from={start_date.strftime('%Y-%m-%d')}&to={end_date.strftime('%Y-%m-%d')}&sortBy=publishedAt&apiKey={NEWS_API_KEY}"
)
response.raise_for_status()
articles = response.json().get("articles", [])
logging.info(f"NewsAPI found {len(articles)} articles for {symbol}.")
for article in articles[:5]:
logging.info(f"{article['title']} - {article['publishedAt']} (Source: {article['source']['name']})")
return articles
except Exception as e:
logging.error(f"NewsAPI error: {e}")
return []
if __name__ == "__main__":
fetch_news("TSLA", datetime(2024, 8, 1), datetime(2024, 8, 10))
@vitorcalvi
Copy link
Author

❯ python3 news/query_news_data.py
2024-08-10 17:59:08,849 - INFO - No news found in Alpaca; falling back to NewsAPI.
2024-08-10 17:59:09,706 - INFO - NewsAPI found 100 articles for TSLA.
2024-08-10 17:59:09,706 - INFO - Market Clubhouse Morning Memo - August 9th, 2024 (Trade Strategy For SPY, QQQ, AAPL, MSFT, NVDA, GOOGL, META And TSLA) - 2024-08-09T15:06:08Z (Source: Biztoc.com)
2024-08-10 17:59:09,706 - INFO - Strategist: Why Meta looks like the 'Magnificent 7' standout right now - 2024-08-09T14:01:23Z (Source: Yahoo Entertainment)
2024-08-10 17:59:09,706 - INFO - Here’s this strategist’s top Magnificent 7 stock to buy after the rout - 2024-08-09T14:01:23Z (Source: Yahoo Entertainment)
2024-08-10 17:59:09,706 - INFO - Tesla, Inc. (NASDAQ:TSLA) Stock Position Increased by NBC Securities Inc. - 2024-08-09T13:22:42Z (Source: ETF Daily News)
2024-08-10 17:59:09,706 - INFO - Tesla (NASDAQ:TSLA) Shares Down 1% - 2024-08-09T12:30:43Z (Source: ETF Daily News)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment