Last active
May 25, 2025 01:36
-
-
Save janusson/f2425a6f1966a607e5a1731925d215e6 to your computer and use it in GitHub Desktop.
Fetches stock data with yfinance. Exports JSON & CSV.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import yfinance as yf | |
import json | |
import os | |
import pandas as pd | |
# Setup logging | |
logging.basicConfig(filename='security_data_collector.log', level=logging.ERROR, | |
format='%(asctime)s - %(levelname)s - %(message)s') | |
logger = logging.getLogger() | |
class SecurityDataCollector: | |
"""Gets financial and company information from Yahoo Finance for a given ticker.""" | |
def __init__(self, ticker: str): | |
self.ticker = ticker | |
self.yf_ticker = yf.Ticker(ticker) | |
self.company_info = self.yf_ticker.info | |
def get_company_name(self) -> str: | |
"""Fetch company name, prioritizing shortName.""" | |
return self.company_info.get('shortName', self.company_info.get('longName', 'Unknown')) | |
def get_news(self) -> list: | |
"""Fetch company news.""" | |
return getattr(self.yf_ticker, 'news', []) | |
def get_financials(self) -> pd.DataFrame: | |
"""Fetch financial data as a DataFrame.""" | |
financial_data = {key: getattr(self.yf_ticker, key, pd.DataFrame()) for key in [ | |
'financials', 'quarterly_financials', 'balance_sheet', 'quarterly_balance_sheet', | |
'cashflow', 'quarterly_cashflow']} | |
return pd.concat(financial_data, axis=1) if financial_data else pd.DataFrame() | |
def download_info(self): | |
"""Download company info as JSON.""" | |
os.makedirs('./data/info', exist_ok=True) | |
with open(f'./data/info/{self.get_company_name()}_summary.json', 'w', encoding='utf-8') as outfile: | |
json.dump(self.company_info, outfile, indent=4, ensure_ascii=False) | |
def download_price_hist(self): | |
"""Download historical price data as CSV.""" | |
os.makedirs('./data/price_hist', exist_ok=True) | |
self.yf_ticker.history(period="max").to_csv(f'./data/price_hist/{self.ticker}_hist.csv') | |
# Example usage | |
if __name__ == "__main__": | |
collector = SecurityDataCollector("MSFT") | |
print(f"Company Name: {collector.get_company_name()}") | |
print("News:", collector.get_news()) | |
print("Financials:", collector.get_financials()) | |
collector.download_info() | |
collector.download_price_hist() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Security Data Collector Description
This Python script utilizes the
yfinance
library to collect and manage various types of financial and stock market data for a given ticker symbol from Yahoo Finance. The script provides functionalities to fetch and store company information, news, options, earnings dates, recommendations, holders, financial statements, and historical price data. It also includes error handling for robust data retrieval. The collected data can be exported in JSON and CSV formats for further analysis.security_data_collector.py