Metadata-Version: 2.4
Name: datapungibea
Version: 2.0.0
Summary: Connect to Bureau of Economic Analysis (BEA) API, enrich data output and get vintage data
Author-email: James Otterson <jjotterson@gmail.com>
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
License-File: LICENSE
Requires-Dist: requests
Requires-Dist: pandas
Requires-Dist: pytest
Requires-Dist: pytest-html
Requires-Dist: pyperclip
Requires-Dist: lxml
Requires-Dist: openpyxl
Requires-Dist: beautifulsoup4
Requires-Dist: html5lib
Requires-Dist: pyyaml
Project-URL: Home, https://github.com/jjotterson/datapungibea

[![image](https://img.shields.io/pypi/v/datapungibea.svg)](https://pypi.org/project/datapungibea/)
[![Downloads](https://pepy.tech/badge/datapungibea)](https://pepy.tech/project/datapungibea)
[![image](https://img.shields.io/pypi/pyversions/datapungibea.svg)](https://pypi.org/project/datapungibea/)

# Datapungibea

Datapungibea is a Python package that provides a simplified way to extract data from the U.S. Bureau of Economic Analysis (BEA). Its main purpose is to connect to BEA's Application Program Interface (API).

**Features:**
- Quick access to 13 BEA datasets with automatic data cleaning
- Code snippet generation for reproducible queries (standalone `requests` code)
- Enriched NIPA data with table indentations (graph structure)
- NIPA Summary tables (6 economic accounts)
- Three flexible methods for API key management
- Comprehensive test suite with HTML reporting
- Python 3.14+ compatible

## Installation

```bash
pip install datapungibea
```

## Quick Start

### 1. Get a BEA API Key

Register for a free API key at: https://apps.bea.gov/API/signup/index.cfm

### 2. Set Up Your API Key

**Option 1: Environment Variable (Recommended)**
```bash
export API_KEY_BEA=your_api_key_here
```

**Option 2: Pass Directly**
```python
import datapungibea as dpb
data = dpb.data("your_api_key_here")
```

**Option 3: Key File**
```python
import datapungibea as dpb
data = dpb.data(keyfile="/path/to/keys.yaml")
```

### 3. Query Data

```python
import datapungibea as dpb

data = dpb.data()

# Get the list of available data sets:
data.datasetlist()  # eg, 'NIPA'

# For a given data set, get the parameters specifying a data table
data.getParameterList('NIPA') # List NIPA parameters, eg TableID

# For a given parameter, get all values of that parameter
data.getParameterValues('NIPA','TableID')

# Get the data table 
table = data.NIPA('T10101')
```

## Available Datasets

Datapungibea provides access to 12 BEA datasets:

| Dataset | Description | Example |
|---------|-------------|---------|
| **NIPA** | National Income and Product Accounts | `data.NIPA('T10101')` |
| **NIUnderlyingDetail** | NI underlying detail tables | `data.NIUnderlyingDetail('U20304')` |
| **FixedAssets** | Fixed Assets tables | `data.fixedAssets('FAAt101', '2010')` |
| **ITA** | International Transactions Accounts | `data.ITA('BalCurrAcct', 'Brazil', 'A', '2010')` |
| **IIP** | International Investment Position | `data.IIP('DebtSecAssets', 'All', 'All', '2010')` |
| **GDPbyIndustry** | GDP by Industry | `data.GDPbyIndustry('211', '1', 'A', '2018')` |
| **UnderlyingGDPbyIndustry** | Underlying GDP by Industry | `data.UnderlyingGDPbyIndustry('ALL', 'ALL', 'A', '2014')` |
| **InputOutput** | Input-Output tables | `data.InputOutput('56', '2010')` |
| **IntlServTrade** | International Services Trade | `data.IntlServTrade('ALL', 'ALL', 'ALL', 'AllCountries', 'All')` |
| **IntlServSTA** | International Services Supplied Through Affiliates | `data.IntlServSTA()` |
| **Regional** | Regional economic data | `data.Regional('00000', '1', 'CAINC1', '2010')` |
| **MNE** | Multinational Enterprises | `data.MNE(...)` |

## NIPA Features

### Table Indentations

NIPA queries automatically include table indentations (graph structure) showing hierarchical relationships between line items:

```python
# With indentations (default)
data.NIPA('T10101')

# Without indentations
data.NIPA('T10101', includeIndentations=False)
```

API data  | Enriched data 
--------- | ------------- 
![](https://github.com/jjotterson/datapungibea/blob/master/docs/beaQuery.png) | ![](https://github.com/jjotterson/datapungibea/blob/master/docs/enrichIndentQuery.png)    



### NIPA Summary Tables

Get an overview of NIPA data across 6 economic accounts:

```python
# Get summary for 2020, annual frequency
data.NIPASummary('2020', 'A')

# Get summary for 2020 Q1, quarterly frequency
data.NIPASummary('2020', 'Q')
```

The summary covers:
1. Domestic Income and Product Account
2. Private Enterprise Income Account
3. Personal Income and Outlays Account
4. Government Receipts and Expenditure Account
5. Foreign Transactions Current Account
6. Domestic Capital Account

## Verbose Mode and Code Generation

Use `verbose=True` to get the full request details and a reproducible code snippet:

```python
result = data.NIPA('T10101', verbose=True)

print(result.keys())
# ['dataFrame', 'request', 'code']

# Access the cleaned DataFrame
df = result['dataFrame']

# Access the raw request
response = result['request']
print(response.status_code)  # 200

# Get reproducible code snippet
print(result['code'])
```

The generated code snippet is standalone and can be used in scripts without datapungibea:

```python
import requests
import os
import pandas as pd

url = "https://apps.bea.gov/api/data/"
key = os.getenv("API_KEY_BEA")

query = {
    "url": url,
    "params": {
        "UserID": key,
        "ResultFormat": "JSON",
        "method": "GETDATA",
        "datasetname": "NIPA",
        "TableName": "T10101",
        "Frequency": "Q",
        "Year": "X"
    }
}

retrivedData = requests.get(**query)
df_output = pd.DataFrame(retrivedData.json()['BEAAPI']['Results']['Data'])
```

## API Key Management

### Environment Variable (Recommended)

```bash
# Linux/macOS
export API_KEY_BEA=your_api_key_here

# Windows (Command Prompt)
set API_KEY_BEA=your_api_key_here

# Windows (PowerShell)
$env:API_KEY_BEA="your_api_key_here"
```

Then use:
```python
data = dpb.data()  # Automatically reads API_KEY_BEA
```

### Direct Key Passing

```python
data = dpb.data("your_api_key_here")
```

### Key File

Create a YAML or JSON file with your API key:

**keys.yaml:**
```yaml
API_KEY_BEA:
    key: your_api_key_here
    url: https://apps.bea.gov/api/data/
```

**keys.json:**
```json
{
    "API_KEY_BEA": {
        "key": "your_api_key_here",
        "url": "https://apps.bea.gov/api/data/"
    }
}
```

Then use:
```python
data = dpb.data(keyfile="/path/to/keys.yaml")
```

## Testing

Run the test suite to verify your setup:

```bash
# Run all tests
python -m pytest datapungibea/tests/test_drivers.py -v

# Generate HTML report
python -m pytest datapungibea/tests/test_drivers.py --html=report.html --self-contained-html

# Run from Python
import datapungibea as dpb
dpb.tests.runTests(outputPath='./')
```

The tests verify:
1. API connection and authentication
2. Data cleaning and transformation
3. Code snippet generation
4. Code snippet execution and reproducibility

## Migration from v1.x

### Breaking Changes

- **NIPAVintage removed**: The web scraping endpoint for vintage data is no longer available. Vintage data support is planned for a future release.
- **Environment variable renamed**: Changed from `BEA` to `API_KEY_BEA`
- **Metadata access**: Changed from `df.meta` to `df.attrs['meta']`
- **Configuration simplified**: Removed `setUserSettings()`, `setKeyName()`, `setTestFolder()` functions

### What's New

- 2 additional datasets: `NIUnderlyingDetail`, `IntlServSTA`
- Improved error handling and logging
- Cleaner API with 3 key management methods
- Better code snippet generation

## Requirements

- Python 3.14+
- pandas
- requests
- pyyaml
- beautifulsoup4
- lxml
- openpyxl
- pyperclip

## References

- [BEA API Documentation](https://apps.bea.gov/API/signup/index.cfm)
- [BEA API User Guide](https://apps.bea.gov/api/_pdf/bea_web_service_api_user_guide.pdf)
- [Python Requests Library](https://requests.readthedocs.io/)

## License

MIT License - see LICENSE file for details.

## Contributing

Contributions welcome! Please open an issue or pull request on GitHub.

## Data Disclaimer

Data used is sourced from the Bureau of Economic Analysis. As stated on the BEA website:
- Unless stated otherwise, information published on this site is in the public domain and may be used or reproduced without specific permission.
- As a U.S. government agency, BEA does not endorse or recommend any commercial products or services.
- Any reference or link to the BEA Web site must not contain information that suggests an endorsement or recommendation by BEA.

For more information, see: https://www.bea.gov/help/guidelines-for-citing-bea

