Skip to content

Instantly share code, notes, and snippets.

@nbk2000
Created December 24, 2024 23:36
Show Gist options
  • Save nbk2000/535e5e6e51fceab9c2d31bc7964b80d0 to your computer and use it in GitHub Desktop.
Save nbk2000/535e5e6e51fceab9c2d31bc7964b80d0 to your computer and use it in GitHub Desktop.
Get Subsidiaries of a Company from SEC API
import requests
import sys
API_KEY = 'API-KEY-GOES-HERE'
# ANSI color codes
BLUE = '\033[94m'
RED = '\033[91m'
PURPLE = '\033[95m'
GREEN = '\033[92m'
RESET = '\033[0m'
def get_subsidiaries(ticker):
"""Get subsidiaries for a given ticker using direct API call."""
url = 'https://api.sec-api.io/subsidiaries'
headers = {'Authorization': API_KEY}
query = {
"query": f"ticker:{ticker}",
"from": "0",
"size": "50",
"sort": [{"filedAt": {"order": "desc"}}]
}
# Use backoff strategy to handle "too many requests" error
for attempt in range(3):
try:
response = requests.post(url, headers=headers, json=query)
if response.status_code == 200:
return response.json()
elif response.status_code == 429:
# wait 500 * (attempt + 1) milliseconds and try again
time.sleep(0.5 * (attempt + 1))
continue
else:
raise Exception(f"API error: {response.status_code} - {response.text}")
except Exception as e:
if attempt == 2: # Last attempt
raise Exception(f"Failed to get subsidiaries: {str(e)}")
return None
def main():
if len(sys.argv) != 2:
print(f"{RED}Usage: python {sys.argv[0]} 'company name'{RESET}")
sys.exit(1)
company_name = sys.argv[1]
yfinance = "https://query2.finance.yahoo.com/v1/finance/search"
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
params = {"q": company_name, "quotes_count": 0, "country": "United States"}
res = requests.get(url=yfinance, params=params, headers={'User-Agent': user_agent})
data = res.json()
# Filter out results that either have no longname or contain '.'
valid_results = [(q['longname'], q['symbol']) for q in data['quotes']
if q.get('longname') is not None and '.' not in q['symbol']]
chosen_name, chosen_symbol = None, None
if len(valid_results) == 1:
# If there's only one choice, just pick it
chosen_name, chosen_symbol = valid_results[0]
print(f"{BLUE}You chose this company:{RESET} {PURPLE}{chosen_name} ({chosen_symbol}){RESET}\n")
elif len(valid_results) > 1:
# Multiple choices: prompt user
print(f"{BLUE}Multiple companies found:{RESET}")
for i, (name, symbol) in enumerate(valid_results, start=1):
print(f"{i}. {name} ({symbol})")
choice = None
while choice is None:
try:
user_input = input(f"{BLUE}Please choose a company: {RESET}")
idx = int(user_input)
if 1 <= idx <= len(valid_results):
choice = idx
else:
print(f"{RED}Invalid choice. Please try again.{RESET}")
except ValueError:
print(f"{RED}Invalid input. Please enter a number.{RESET}")
chosen_name, chosen_symbol = valid_results[choice - 1]
print(f"{BLUE}You chose this company:{RESET} {PURPLE}{chosen_name} ({chosen_symbol}){RESET}\n")
else:
# No valid results
print(f"{RED}No matching companies found.{RESET}")
return
# If we have chosen a company, get its subsidiaries
if chosen_symbol:
try:
subsidiaries = get_subsidiaries(chosen_symbol)
# Check if we have data and subsidiaries
if subsidiaries and 'data' in subsidiaries and len(subsidiaries['data']) > 0:
data_entry = subsidiaries['data'][0]
if 'subsidiaries' in data_entry and len(data_entry['subsidiaries']) > 0:
print(f"{GREEN}The following subsidiaries were found:{RESET}")
for sub in data_entry['subsidiaries']:
print(sub.get('name', 'No subsidiary name found'))
else:
print(f"{RED}No subsidiaries found{RESET}")
else:
print(f"{RED}No subsidiaries found{RESET}")
except Exception as e:
print(f"{RED}Error getting subsidiaries: {str(e)}{RESET}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment