Skip to content

Instantly share code, notes, and snippets.

@janusson
Last active September 24, 2025 00:20
Show Gist options
  • Select an option

  • Save janusson/f2425a6f1966a607e5a1731925d215e6 to your computer and use it in GitHub Desktop.

Select an option

Save janusson/f2425a6f1966a607e5a1731925d215e6 to your computer and use it in GitHub Desktop.
Export securities data with yfinance
import yfinance as yf
import json
import os
import pandas as pd
ticker_symbol = 'MSFT'
class SecurityDataCollector:
"""Retrieves 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(f"{ticker_symbol}")
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()
@janusson
Copy link
Author

janusson commented Dec 8, 2024

Security Data Collector Description

This Python script uses the yfinance library to fetch and manage financial and stock market data for a given ticker symbol from Yahoo Finance. It can retrieve company information, news, options, earnings dates, recommendations, holders, financial statements, and historical price data. The script handles errors for robust data retrieval and exports the collected data in JSON and CSV formats for analysis.

security_data_collector.py

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