fmp-data


Namefmp-data JSON
Version 0.1.0 PyPI version JSON
download
home_pagehttps://github.com/MehdiZare/fmp-data
SummaryPython client for Financial Modeling Prep API
upload_time2024-11-24 04:38:18
maintainerNone
docs_urlNone
authormehdizare
requires_python<4.0,>=3.10
licenseMIT
keywords fmp financial api stocks market-data stock market financial data
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FMP Data Client

[![Test](https://github.com/MehdiZare/fmp-data/actions/workflows/test.yml/badge.svg)](https://github.com/MehdiZare/fmp-data/actions/workflows/test.yml)
[![codecov](https://codecov.io/gh/MehdiZare/fmp-data/branch/main/graph/badge.svg)](https://codecov.io/gh/MehdiZare/fmp-data)
[![Python](https://img.shields.io/pypi/pyversions/fmp-data.svg)](https://pypi.org/project/fmp-data/)
[![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)](https://python-poetry.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Python client for the Financial Modeling Prep (FMP) API with comprehensive logging, rate limiting, and error handling.

## Features

- 🚀 Simple and intuitive interface
- 🔒 Built-in rate limiting
- 📝 Comprehensive logging
- ⚡ Async support
- 🏷️ Type hints and validation with Pydantic
- 🔄 Automatic retries with exponential backoff
- 🎯 100% test coverage (excluding predefined endpoints)
- 🛡️ Secure API key handling
- 📊 Support for all major FMP endpoints
- 🔍 Detailed error messages
- 🚦 Configurable retry strategies

## Installation

```bash
# Using pip
pip install fmp-data

# Using poetry
poetry add fmp-data
```

## Quick Start

```python
from fmp_data import FMPDataClient, ClientConfig, LoggingConfig
from fmp_data.exceptions import FMPError, RateLimitError, AuthenticationError

# Method 1: Initialize with direct API key
client = FMPDataClient(api_key="your_api_key_here") # pragma: allowlist secret

# Method 2: Initialize from environment variable (FMP_API_KEY)
client = FMPDataClient.from_env()

# Method 3: Initialize with custom configuration
config = ClientConfig(
    api_key="your_api_key_here", #pragma: allowlist secret
    timeout=30,
    max_retries=3,
    base_url="https://financialmodelingprep.com/api",
    logging=LoggingConfig(level="INFO")
)
client = FMPDataClient(config=config)

# Using with context manager (recommended)
with FMPDataClient(api_key="your_api_key_here") as client: # pragma: allowlist secret
    try:
        # Get company profile
        profile = client.company.get_profile("AAPL")
        print(f"Company: {profile.company_name}")
        print(f"Industry: {profile.industry}")
        print(f"Market Cap: ${profile.mkt_cap:,.2f}")

        # Search companies
        results = client.company.search("Tesla", limit=5)
        for company in results:
            print(f"{company.symbol}: {company.name}")

    except RateLimitError as e:
        print(f"Rate limit exceeded. Wait {e.retry_after} seconds")
    except AuthenticationError:
        print("Invalid API key")
    except FMPError as e:
        print(f"API error: {e}")

# Client is automatically closed after the with block
```

## Key Components

### 1. Company Information
```python
from fmp_data import FMPDataClient

with FMPDataClient.from_env() as client:
    # Get company profile
    profile = client.company.get_profile("AAPL")

    # Get company executives
    executives = client.company.get_executives("AAPL")

    # Search companies
    results = client.company.search("Tesla", limit=5)

    # Get employee count history
    employees = client.company.get_employee_count("AAPL")
```

### 2. Financial Statements
```python
from fmp_data import FMPDataClient

with FMPDataClient.from_env() as client:
    # Get income statements
    income_stmt = client.fundamental.get_income_statement(
        "AAPL",
        period="quarter",  # or "annual"
        limit=4
    )

    # Get balance sheets
    balance_sheet = client.fundamental.get_balance_sheet(
        "AAPL",
        period="annual"
    )

    # Get cash flow statements
    cash_flow = client.fundamental.get_cash_flow_statement("AAPL")
```

### 3. Market Data
```python
from fmp_data import FMPDataClient

with FMPDataClient.from_env() as client:
    # Get real-time quote
    quote = client.market.get_quote("TSLA")

    # Get historical prices
    history = client.market.get_historical_price(
        "TSLA",
        from_date="2023-01-01",
        to_date="2023-12-31"
    )
```

### 4. Async Support
```python
import asyncio
from fmp_data import FMPDataClient

async def get_multiple_profiles(symbols):
    async with FMPDataClient.from_env() as client:
        tasks = [client.company.get_profile_async(symbol)
                for symbol in symbols]
        return await asyncio.gather(*tasks)

# Run async function
symbols = ["AAPL", "MSFT", "GOOGL"]
profiles = asyncio.run(get_multiple_profiles(symbols))
```

## Configuration

### Environment Variables
```bash
# Required
FMP_API_KEY=your_api_key_here

# Optional
FMP_BASE_URL=https://financialmodelingprep.com/api
FMP_TIMEOUT=30
FMP_MAX_RETRIES=3

# Rate Limiting
FMP_DAILY_LIMIT=250
FMP_REQUESTS_PER_SECOND=10
FMP_REQUESTS_PER_MINUTE=300

# Logging
FMP_LOG_LEVEL=INFO
FMP_LOG_PATH=/path/to/logs
FMP_LOG_MAX_BYTES=10485760
FMP_LOG_BACKUP_COUNT=5
```

### Custom Configuration
```python
from fmp_data import FMPDataClient, ClientConfig, LoggingConfig, RateLimitConfig


config = ClientConfig(
    api_key="your_api_key_here", # pragma: allowlist secret
    timeout=30,
    max_retries=3,
    base_url="https://financialmodelingprep.com/api",
    rate_limit=RateLimitConfig(
        daily_limit=250,
        requests_per_second=10,
        requests_per_minute=300
    ),
    logging=LoggingConfig(
        level="DEBUG",
        handlers={
            "console": {
                "class_name": "StreamHandler",
                "level": "INFO"
            },
            "file": {
                "class_name": "RotatingFileHandler",
                "level": "DEBUG",
                "filename": "fmp.log",
                "maxBytes": 10485760,
                "backupCount": 5
            }
        }
    )
)

client = FMPDataClient(config=config)
```

## Error Handling

```python
from fmp_data import FMPDataClient
from fmp_data.exceptions import (
    FMPError,
    RateLimitError,
    AuthenticationError,
    ValidationError,
    ConfigError
)
try:
    with FMPDataClient.from_env() as client:
        profile = client.company.get_profile("INVALID")

except RateLimitError as e:
    print(f"Rate limit exceeded. Wait {e.retry_after} seconds")
    print(f"Status code: {e.status_code}")
    print(f"Response: {e.response}")

except AuthenticationError as e:
    print("Invalid API key or authentication failed")
    print(f"Status code: {e.status_code}")

except ValidationError as e:
    print(f"Invalid parameters: {e.message}")

except ConfigError as e:
    print(f"Configuration error: {e.message}")

except FMPError as e:
    print(f"General API error: {e.message}")
```

## Development Setup

1. Clone the repository:
```bash
git clone https://github.com/MehdiZare/fmp-data.git
cd fmp-data
```

2. Install dependencies using Poetry:
```bash
poetry install
```

3. Set up pre-commit hooks:
```bash
poetry run pre-commit install
```

## Running Tests

```bash
# Run all tests with coverage
poetry run pytest --cov=fmp_data

# Run specific test file
poetry run pytest tests/test_client.py

# Run integration tests (requires API key)
FMP_TEST_API_KEY=your_test_api_key poetry run pytest tests/integration/
```

View the latest test coverage report [here](https://codecov.io/gh/MehdiZare/fmp-data).

## Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature-name`
3. Make your changes
4. Run tests: `poetry run pytest`
5. Create a pull request

Please ensure:
- Tests pass
- Code is formatted with black
- Type hints are included
- Documentation is updated
- Commit messages follow conventional commits

## License

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

## Acknowledgments

- Financial Modeling Prep for providing the API
- Contributors to the project
- Open source packages used in this project

## Support

- GitHub Issues: [Create an issue](https://github.com/MehdiZare/fmp-data/issues)
- Documentation: [Read the docs](./docs)
- Examples: [View examples](./examples)

## Release Notes

See [CHANGELOG.md](./CHANGELOG.md) for a list of changes in each release.
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/MehdiZare/fmp-data",
    "name": "fmp-data",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.10",
    "maintainer_email": null,
    "keywords": "fmp, financial, api, stocks, market-data, stock market, financial data",
    "author": "mehdizare",
    "author_email": "mehdizare@users.noreply.github.com",
    "download_url": "https://files.pythonhosted.org/packages/ca/06/5f55325813176c4d244435c99a81ae7793afbf61fccd9ed2cc5f1845ffb8/fmp_data-0.1.0.tar.gz",
    "platform": null,
    "description": "# FMP Data Client\n\n[![Test](https://github.com/MehdiZare/fmp-data/actions/workflows/test.yml/badge.svg)](https://github.com/MehdiZare/fmp-data/actions/workflows/test.yml)\n[![codecov](https://codecov.io/gh/MehdiZare/fmp-data/branch/main/graph/badge.svg)](https://codecov.io/gh/MehdiZare/fmp-data)\n[![Python](https://img.shields.io/pypi/pyversions/fmp-data.svg)](https://pypi.org/project/fmp-data/)\n[![Poetry](https://img.shields.io/endpoint?url=https://python-poetry.org/badge/v0.json)](https://python-poetry.org/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA Python client for the Financial Modeling Prep (FMP) API with comprehensive logging, rate limiting, and error handling.\n\n## Features\n\n- \ud83d\ude80 Simple and intuitive interface\n- \ud83d\udd12 Built-in rate limiting\n- \ud83d\udcdd Comprehensive logging\n- \u26a1 Async support\n- \ud83c\udff7\ufe0f Type hints and validation with Pydantic\n- \ud83d\udd04 Automatic retries with exponential backoff\n- \ud83c\udfaf 100% test coverage (excluding predefined endpoints)\n- \ud83d\udee1\ufe0f Secure API key handling\n- \ud83d\udcca Support for all major FMP endpoints\n- \ud83d\udd0d Detailed error messages\n- \ud83d\udea6 Configurable retry strategies\n\n## Installation\n\n```bash\n# Using pip\npip install fmp-data\n\n# Using poetry\npoetry add fmp-data\n```\n\n## Quick Start\n\n```python\nfrom fmp_data import FMPDataClient, ClientConfig, LoggingConfig\nfrom fmp_data.exceptions import FMPError, RateLimitError, AuthenticationError\n\n# Method 1: Initialize with direct API key\nclient = FMPDataClient(api_key=\"your_api_key_here\") # pragma: allowlist secret\n\n# Method 2: Initialize from environment variable (FMP_API_KEY)\nclient = FMPDataClient.from_env()\n\n# Method 3: Initialize with custom configuration\nconfig = ClientConfig(\n    api_key=\"your_api_key_here\", #pragma: allowlist secret\n    timeout=30,\n    max_retries=3,\n    base_url=\"https://financialmodelingprep.com/api\",\n    logging=LoggingConfig(level=\"INFO\")\n)\nclient = FMPDataClient(config=config)\n\n# Using with context manager (recommended)\nwith FMPDataClient(api_key=\"your_api_key_here\") as client: # pragma: allowlist secret\n    try:\n        # Get company profile\n        profile = client.company.get_profile(\"AAPL\")\n        print(f\"Company: {profile.company_name}\")\n        print(f\"Industry: {profile.industry}\")\n        print(f\"Market Cap: ${profile.mkt_cap:,.2f}\")\n\n        # Search companies\n        results = client.company.search(\"Tesla\", limit=5)\n        for company in results:\n            print(f\"{company.symbol}: {company.name}\")\n\n    except RateLimitError as e:\n        print(f\"Rate limit exceeded. Wait {e.retry_after} seconds\")\n    except AuthenticationError:\n        print(\"Invalid API key\")\n    except FMPError as e:\n        print(f\"API error: {e}\")\n\n# Client is automatically closed after the with block\n```\n\n## Key Components\n\n### 1. Company Information\n```python\nfrom fmp_data import FMPDataClient\n\nwith FMPDataClient.from_env() as client:\n    # Get company profile\n    profile = client.company.get_profile(\"AAPL\")\n\n    # Get company executives\n    executives = client.company.get_executives(\"AAPL\")\n\n    # Search companies\n    results = client.company.search(\"Tesla\", limit=5)\n\n    # Get employee count history\n    employees = client.company.get_employee_count(\"AAPL\")\n```\n\n### 2. Financial Statements\n```python\nfrom fmp_data import FMPDataClient\n\nwith FMPDataClient.from_env() as client:\n    # Get income statements\n    income_stmt = client.fundamental.get_income_statement(\n        \"AAPL\",\n        period=\"quarter\",  # or \"annual\"\n        limit=4\n    )\n\n    # Get balance sheets\n    balance_sheet = client.fundamental.get_balance_sheet(\n        \"AAPL\",\n        period=\"annual\"\n    )\n\n    # Get cash flow statements\n    cash_flow = client.fundamental.get_cash_flow_statement(\"AAPL\")\n```\n\n### 3. Market Data\n```python\nfrom fmp_data import FMPDataClient\n\nwith FMPDataClient.from_env() as client:\n    # Get real-time quote\n    quote = client.market.get_quote(\"TSLA\")\n\n    # Get historical prices\n    history = client.market.get_historical_price(\n        \"TSLA\",\n        from_date=\"2023-01-01\",\n        to_date=\"2023-12-31\"\n    )\n```\n\n### 4. Async Support\n```python\nimport asyncio\nfrom fmp_data import FMPDataClient\n\nasync def get_multiple_profiles(symbols):\n    async with FMPDataClient.from_env() as client:\n        tasks = [client.company.get_profile_async(symbol)\n                for symbol in symbols]\n        return await asyncio.gather(*tasks)\n\n# Run async function\nsymbols = [\"AAPL\", \"MSFT\", \"GOOGL\"]\nprofiles = asyncio.run(get_multiple_profiles(symbols))\n```\n\n## Configuration\n\n### Environment Variables\n```bash\n# Required\nFMP_API_KEY=your_api_key_here\n\n# Optional\nFMP_BASE_URL=https://financialmodelingprep.com/api\nFMP_TIMEOUT=30\nFMP_MAX_RETRIES=3\n\n# Rate Limiting\nFMP_DAILY_LIMIT=250\nFMP_REQUESTS_PER_SECOND=10\nFMP_REQUESTS_PER_MINUTE=300\n\n# Logging\nFMP_LOG_LEVEL=INFO\nFMP_LOG_PATH=/path/to/logs\nFMP_LOG_MAX_BYTES=10485760\nFMP_LOG_BACKUP_COUNT=5\n```\n\n### Custom Configuration\n```python\nfrom fmp_data import FMPDataClient, ClientConfig, LoggingConfig, RateLimitConfig\n\n\nconfig = ClientConfig(\n    api_key=\"your_api_key_here\", # pragma: allowlist secret\n    timeout=30,\n    max_retries=3,\n    base_url=\"https://financialmodelingprep.com/api\",\n    rate_limit=RateLimitConfig(\n        daily_limit=250,\n        requests_per_second=10,\n        requests_per_minute=300\n    ),\n    logging=LoggingConfig(\n        level=\"DEBUG\",\n        handlers={\n            \"console\": {\n                \"class_name\": \"StreamHandler\",\n                \"level\": \"INFO\"\n            },\n            \"file\": {\n                \"class_name\": \"RotatingFileHandler\",\n                \"level\": \"DEBUG\",\n                \"filename\": \"fmp.log\",\n                \"maxBytes\": 10485760,\n                \"backupCount\": 5\n            }\n        }\n    )\n)\n\nclient = FMPDataClient(config=config)\n```\n\n## Error Handling\n\n```python\nfrom fmp_data import FMPDataClient\nfrom fmp_data.exceptions import (\n    FMPError,\n    RateLimitError,\n    AuthenticationError,\n    ValidationError,\n    ConfigError\n)\ntry:\n    with FMPDataClient.from_env() as client:\n        profile = client.company.get_profile(\"INVALID\")\n\nexcept RateLimitError as e:\n    print(f\"Rate limit exceeded. Wait {e.retry_after} seconds\")\n    print(f\"Status code: {e.status_code}\")\n    print(f\"Response: {e.response}\")\n\nexcept AuthenticationError as e:\n    print(\"Invalid API key or authentication failed\")\n    print(f\"Status code: {e.status_code}\")\n\nexcept ValidationError as e:\n    print(f\"Invalid parameters: {e.message}\")\n\nexcept ConfigError as e:\n    print(f\"Configuration error: {e.message}\")\n\nexcept FMPError as e:\n    print(f\"General API error: {e.message}\")\n```\n\n## Development Setup\n\n1. Clone the repository:\n```bash\ngit clone https://github.com/MehdiZare/fmp-data.git\ncd fmp-data\n```\n\n2. Install dependencies using Poetry:\n```bash\npoetry install\n```\n\n3. Set up pre-commit hooks:\n```bash\npoetry run pre-commit install\n```\n\n## Running Tests\n\n```bash\n# Run all tests with coverage\npoetry run pytest --cov=fmp_data\n\n# Run specific test file\npoetry run pytest tests/test_client.py\n\n# Run integration tests (requires API key)\nFMP_TEST_API_KEY=your_test_api_key poetry run pytest tests/integration/\n```\n\nView the latest test coverage report [here](https://codecov.io/gh/MehdiZare/fmp-data).\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes\n4. Run tests: `poetry run pytest`\n5. Create a pull request\n\nPlease ensure:\n- Tests pass\n- Code is formatted with black\n- Type hints are included\n- Documentation is updated\n- Commit messages follow conventional commits\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.\n\n## Acknowledgments\n\n- Financial Modeling Prep for providing the API\n- Contributors to the project\n- Open source packages used in this project\n\n## Support\n\n- GitHub Issues: [Create an issue](https://github.com/MehdiZare/fmp-data/issues)\n- Documentation: [Read the docs](./docs)\n- Examples: [View examples](./examples)\n\n## Release Notes\n\nSee [CHANGELOG.md](./CHANGELOG.md) for a list of changes in each release.",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python client for Financial Modeling Prep API",
    "version": "0.1.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/MehdiZare/fmp-data/issues",
        "Documentation": "https://github.com/MehdiZare/fmp-data#readme",
        "Homepage": "https://github.com/MehdiZare/fmp-data",
        "Repository": "https://github.com/MehdiZare/fmp-data"
    },
    "split_keywords": [
        "fmp",
        " financial",
        " api",
        " stocks",
        " market-data",
        " stock market",
        " financial data"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "42bdff305b6b600e068567369d03a34aad7288cbee78a9588272a0cfb7496c7c",
                "md5": "2497b3a0a3478b68c6ca2d7e1e738b7f",
                "sha256": "b9f445530249c9f4f87d711f6a797dfa7cffd3ce04ef4e642edd1568c2927ed1"
            },
            "downloads": -1,
            "filename": "fmp_data-0.1.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2497b3a0a3478b68c6ca2d7e1e738b7f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.10",
            "size": 63610,
            "upload_time": "2024-11-24T04:38:16",
            "upload_time_iso_8601": "2024-11-24T04:38:16.410064Z",
            "url": "https://files.pythonhosted.org/packages/42/bd/ff305b6b600e068567369d03a34aad7288cbee78a9588272a0cfb7496c7c/fmp_data-0.1.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ca065f55325813176c4d244435c99a81ae7793afbf61fccd9ed2cc5f1845ffb8",
                "md5": "46bb4c167b8381889c1297eb65d2ce06",
                "sha256": "581d2e8e5c91f1544da25c1f7c0da5d7b226f01d293665a5a4db977a97539266"
            },
            "downloads": -1,
            "filename": "fmp_data-0.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "46bb4c167b8381889c1297eb65d2ce06",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.10",
            "size": 51632,
            "upload_time": "2024-11-24T04:38:18",
            "upload_time_iso_8601": "2024-11-24T04:38:18.343250Z",
            "url": "https://files.pythonhosted.org/packages/ca/06/5f55325813176c4d244435c99a81ae7793afbf61fccd9ed2cc5f1845ffb8/fmp_data-0.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-24 04:38:18",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "MehdiZare",
    "github_project": "fmp-data",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fmp-data"
}
        
Elapsed time: 0.51161s