secmap 0.1.0
Fast, cached SEC company data lookups by ticker, CIK, or company name
Requires Python: >=3.7
Keywords: SEC, CIK, ticker, finance, company, lookup, cache

# secmap

⚡ **Fast SEC company lookup by ticker, CIK, or name — with smart caching and auto updates.**

A lightweight Python package for fast, cached lookups of SEC company data — including ticker symbols, CIK identifiers, and company names — using the official SEC `company_tickers.json` dataset.

**secmap** automatically downloads and caches the latest SEC company mapping data, allowing you to:
- 🔍 Look up by **ticker**, **CIK**, or **company name**  
- ⚡ Get **instant in-memory** lookups with optional SQLite persistence  
- 🔄 **Auto-refresh** when new SEC data is available  
- 🧩 Integrate easily into any financial, compliance, or data analysis project

## Quick Start

```python
from secmap import get_company, update_data

# Download the latest SEC data (first time setup)
update_data()

# Look up by ticker
company = get_company("AAPL")
print(company)
# {'cik': 320193, 'ticker': 'AAPL', 'name': 'Apple Inc.'}

# Look up by CIK
company = get_company(320193)
print(company)
# {'cik': 320193, 'ticker': 'AAPL', 'name': 'Apple Inc.'}

# Look up by company name (with fuzzy matching)
company = get_company("Apple")
print(company)
# {'cik': 320193, 'ticker': 'AAPL', 'name': 'Apple Inc.'}
```

## Installation

```bash
pip install secmap
```

## Features

### 🚀 Fast Lookups
- **In-memory caching** with LRU cache for instant repeated lookups
- **SQLite persistence** for cross-session caching
- **Smart identifier detection** - automatically determines if input is ticker, CIK, or company name

### 📊 Comprehensive Data
- **All public companies** from the official SEC database
- **Real-time updates** from https://www.sec.gov/files/company_tickers.json
- **Complete mapping** between tickers, CIKs, and company names

### 🛠 Developer Friendly
- **Simple API** - one function does it all
- **Type hints** and comprehensive documentation
- **Error handling** for network issues and invalid inputs
- **Batch operations** support

## API Reference

### Core Functions

#### `get_company(identifier)`
Smart lookup that auto-detects identifier type.
```python
# Works with tickers, CIKs, or company names
get_company("AAPL")           # Ticker
get_company(320193)           # CIK as int
get_company("320193")         # CIK as string
get_company("Apple Inc.")     # Company name
```

#### `get_company_by_ticker(ticker)`
Look up by stock ticker symbol.
```python
company = get_company_by_ticker("MSFT")
# {'cik': 789019, 'ticker': 'MSFT', 'name': 'Microsoft Corporation'}
```

#### `get_company_by_cik(cik)`
Look up by SEC CIK identifier.
```python
company = get_company_by_cik(789019)
# {'cik': 789019, 'ticker': 'MSFT', 'name': 'Microsoft Corporation'}
```

#### `get_company_by_name(name, fuzzy=False)`
Look up by company name with optional fuzzy matching.
```python
# Exact match
company = get_company_by_name("Microsoft Corporation")

# Fuzzy matching
company = get_company_by_name("Microsoft", fuzzy=True)
```

### Utility Functions

#### `search_companies(query, limit=10)`
Search for companies by partial name or ticker.
```python
results = search_companies("Apple", limit=5)
for company in results:
    print(f"{company['ticker']}: {company['name']}")
```

#### `update_data()`
Download and cache the latest SEC data.
```python
success = update_data()
print(f"Update successful: {success}")
```

#### `get_cache_info()`
Get information about cache status and performance.
```python
info = get_cache_info()
print(f"Companies cached: {info['companies_cached']}")
print(f"Cache age: {info['cache_age_hours']:.1f} hours")
```

#### `clear_cache()`
Clear all cached data.
```python
clear_cache()  # Forces fresh download on next lookup
```

## Usage Examples

### Basic Usage
```python
from secmap import get_company, update_data

# Initial setup - download SEC data
update_data()

# Look up companies
companies = ["AAPL", "MSFT", "GOOGL", "AMZN"]
for ticker in companies:
    company = get_company(ticker)
    if company:
        print(f"{ticker}: {company['name']} (CIK: {company['cik']})")
```

### Data Analysis Workflow
```python
from secmap import get_company

# Process mixed identifiers
portfolio = ["AAPL", "789019", "Tesla, Inc.", "320193"]
enriched_data = []

for identifier in portfolio:
    company = get_company(identifier)
    if company:
        enriched_data.append({
            'input': identifier,
            'ticker': company['ticker'],
            'cik': company['cik'],
            'name': company['name']
        })

print(f"Processed {len(enriched_data)} companies")
```

### Compliance/Regulatory Use
```python
from secmap import get_company_by_cik

# Convert CIK identifiers from regulatory filings
filing_ciks = [320193, 789019, 1652044]

for cik in filing_ciks:
    company = get_company_by_cik(cik)
    if company:
        print(f"CIK {cik}: {company['ticker']} - {company['name']}")
```

## Performance

**secmap** is designed for speed:

- **Initial lookup**: ~1ms (from memory cache)
- **Repeated lookups**: ~0.01ms (LRU cache)
- **Cold start**: ~100ms (includes data loading)
- **Memory usage**: ~10MB for complete SEC dataset

### Benchmarks
```python
import time
from secmap import get_company

# Warm up
get_company("AAPL")

# Time 1000 lookups
start = time.time()
for _ in range(1000):
    get_company("AAPL")
end = time.time()

print(f"Average lookup time: {(end-start)*1000/1000:.3f} ms")
# Average lookup time: 0.008 ms
```

## Caching

**secmap** uses a multi-tier caching strategy:

1. **LRU Cache**: In-memory cache for the fastest lookups
2. **Memory Cache**: Full dataset loaded in memory
3. **SQLite Cache**: Persistent storage across sessions
4. **File Cache**: Raw JSON data backup

### Cache Management
```python
from secmap import get_cache_info, clear_cache

# Check cache status
info = get_cache_info()
if info['cache_expired']:
    print("Cache is stale, updating...")
    update_data()

# Clear cache if needed
clear_cache()
```

## Error Handling

**secmap** gracefully handles various error conditions:

```python
from secmap import get_company

# Invalid inputs return None
result = get_company("INVALID_TICKER")  # Returns None
result = get_company("")                # Returns None
result = get_company(None)              # Returns None

# Network errors fall back to cached data
# If no cache exists, raises RuntimeError with helpful message
```

## Requirements

- Python 3.7+
- `requests` >= 2.25.0

## Development

```bash
# Clone the repository
git clone https://github.com/JNewman-cell/secmap.git
cd secmap

# Install in development mode
pip install -e .

# Install development dependencies
pip install -e .[dev]

# Run tests
pytest

# Format code
black secmap/

# Type checking
mypy secmap/
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Data provided by the [U.S. Securities and Exchange Commission](https://www.sec.gov/)
- Dataset: https://www.sec.gov/files/company_tickers.json

---

**secmap** makes it easy to bridge SEC CIK identifiers and stock tickers in any data pipeline — fast, reliable, and developer-friendly.