PHPackages                             shredio/fmp-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. shredio/fmp-client

ActiveLibrary

shredio/fmp-client
==================

0344↓100%PHPCI passing

Since Nov 7Pushed 2mo agoCompare

[ Source](https://github.com/Shredio/fmp-client)[ Packagist](https://packagist.org/packages/shredio/fmp-client)[ RSS](/packages/shredio-fmp-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (2)Used By (0)

FMP Client
==========

[](#fmp-client)

A high-performance PHP client library for the [Financial Modeling Prep (FMP) API](https://financialmodelingprep.com/), designed to handle large financial datasets efficiently with memory-conscious streaming and asynchronous processing.

Key Features
------------

[](#key-features)

- **Memory Efficient**: Large JSON/CSV responses are streamed using JsonMachine and League CSV, not loaded entirely into memory
- **Async Support**: Non-blocking concurrent API requests using PHP Fibers via FmpPromise
- **Strong Typing**: All data structures use readonly classes with comprehensive type hints
- **Immutable Payloads**: All payload objects are immutable with readonly properties
- **Validation**: Optional strict mode for enhanced data validation
- **Bulk Operations**: Efficient handling of bulk data endpoints
- **Error Handling**: Comprehensive exception handling with request URL context

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- Symfony HTTP Client
- JsonMachine for efficient JSON parsing
- League CSV for CSV processing
- Webmozart Assert for validation

Installation
------------

[](#installation)

Install via Composer:

```
composer require shredio/fmp-client
```

Quick Start
-----------

[](#quick-start)

```
use Shredio\FmpClient\SymfonyFmpClient;
use Symfony\Component\HttpClient\HttpClient;

// Initialize the client
$httpClient = HttpClient::create();
$fmpClient = new SymfonyFmpClient($httpClient, 'your-api-key-here');

// Get company profile
foreach ($fmpClient->companyProfile('AAPL') as $profile) {
    echo "Company: {$profile->companyName}\n";
    echo "Price: ${$profile->price}\n";
    echo "Market Cap: {$profile->marketCap}\n";
}

// Get stock list (streamed)
foreach ($fmpClient->stockList() as $stock) {
    echo "{$stock->symbol}: {$stock->name}\n";
}
```

Configuration Options
---------------------

[](#configuration-options)

### Strict Mode

[](#strict-mode)

Enable strict mode for enhanced validation that throws exceptions on invalid data:

```
$strictClient = $fmpClient->withStrictMode(true);

try {
    foreach ($strictClient->companyProfile('INVALID') as $profile) {
        // Process profile
    }
} catch (UnexpectedResponseContentException $e) {
    echo "Validation error: {$e->getMessage()}\n";
    echo "Request URL: {$e->getRequestUrl()}\n";
}
```

### Custom Error Handling

[](#custom-error-handling)

Implement custom error handling for non-strict mode (useful for logging):

```
use Shredio\FmpClient\Exception\UnexpectedResponseContentExceptionHandler;

$handler = new class implements UnexpectedResponseContentExceptionHandler {
    public function handle(UnexpectedResponseContentException $exception): void {
        error_log("FMP Client Error: {$exception->getMessage()}");
    }
};

$fmpClient = new FmpClient($httpClient, 'api-key', $handler);
```

Usage Examples
--------------

[](#usage-examples)

### Basic Stock Data

[](#basic-stock-data)

```
use Shredio\FmpClient\Enum\PeriodQuery;

// Get available exchanges
foreach ($fmpClient->availableExchanges() as $exchange) {
    echo "{$exchange->name} ({$exchange->code})\n";
}

// Get company financials
foreach ($fmpClient->balanceSheetStatement('AAPL') as $statement) {
    echo "Date: {$statement->date}\n";
    echo "Total Assets: {$statement->totalAssets}\n";
}

// Get financial statement growth metrics
foreach ($fmpClient->incomeStatementGrowth('AAPL', limit: 5, period: PeriodQuery::Quarter) as $growth) {
    echo "Date: {$growth->date}\n";
    echo "Revenue Growth: {$growth->growthRevenue}\n";
    echo "Net Income Growth: {$growth->growthNetIncome}\n";
}

// Get dividend history
foreach ($fmpClient->dividends('AAPL') as $dividend) {
    echo "Date: {$dividend->date}, Amount: {$dividend->dividend}\n";
}

// Get shares float information
$sharesFloat = $fmpClient->getSharesFloat('AAPL');
if ($sharesFloat !== null) {
    echo "Free Float: {$sharesFloat->freeFloat}%\n";
    echo "Float Shares: {$sharesFloat->floatShares}\n";
    echo "Outstanding Shares: {$sharesFloat->outstandingShares}\n";
}
```

### Bulk Operations

[](#bulk-operations)

```
use DateTimeImmutable;

// Bulk company profiles (memory efficient streaming)
foreach ($fmpClient->companyProfileBulk() as $profile) {
    echo "{$profile->symbol}: {$profile->companyName}\n";
}

// End of day bulk quotes
$date = new DateTimeImmutable('2024-01-15');
foreach ($fmpClient->eodBulkQuotes($date) as $quote) {
    echo "{$quote->symbol}: Close ${$quote->close}\n";
}

// Bulk financial statements
foreach ($fmpClient->incomeStatementBulk('2023') as $statement) {
    echo "{$statement->symbol}: Revenue {$statement->revenue}\n";
}
```

### Calendar Data

[](#calendar-data)

```
use DateTimeImmutable;
use Psr\Log\NullLogger;

$from = new DateTimeImmutable('2024-01-01');
$to = new DateTimeImmutable('2024-01-31');
$logger = new NullLogger();

// Earnings calendar (automatically paginated)
foreach ($fmpClient->earningsCalendar($from, $to, $logger) as $earning) {
    echo "Date: {$earning->date}\n";
    echo "Symbol: {$earning->symbol}\n";
    echo "EPS Estimate: {$earning->epsEstimate}\n";
}

// Dividends calendar
foreach ($fmpClient->dividendsCalendar($from, $to, $logger) as $dividend) {
    echo "{$dividend->symbol}: {$dividend->dividend} on {$dividend->date}\n";
}

// Stock splits calendar
foreach ($fmpClient->splitsCalendar($from, $to, $logger) as $split) {
    echo "{$split->symbol}: {$split->numerator}:{$split->denominator} on {$split->date}\n";
}
```

### Historical Data

[](#historical-data)

```
use DateTimeImmutable;
use Shredio\FmpClient\Enum\TimeInterval;

$from = new DateTimeImmutable('2024-01-01');
$to = new DateTimeImmutable('2024-01-31');

// Historical end-of-day prices
foreach ($fmpClient->historicalPriceEod('AAPL', $from, $to) as $price) {
    echo "Date: {$price->date}, Close: ${$price->close}\n";
}

// Historical chart data with intervals
foreach ($fmpClient->historicalChart('AAPL', TimeInterval::FiveMin, $from, $to) as $data) {
    echo "Time: {$data->date}, Price: ${$data->close}\n";
}
```

### Financial Metrics and Ratios

[](#financial-metrics-and-ratios)

```
use Shredio\FmpClient\Enum\PeriodQuery;

// Key metrics
foreach ($fmpClient->keyMetrics('AAPL', 10, PeriodQuery::Annual) as $metrics) {
    echo "Date: {$metrics->date}\n";
    echo "P/E Ratio: {$metrics->peRatio}\n";
    echo "ROE: {$metrics->roe}\n";
}

// TTM (Trailing Twelve Months) metrics
foreach ($fmpClient->keyMetricsTtm('AAPL') as $metrics) {
    echo "Market Cap: {$metrics->marketCapTtm}\n";
    echo "Revenue TTM: {$metrics->revenueTtm}\n";
}

// Financial ratios
foreach ($fmpClient->ratios('AAPL', 5, PeriodQuery::Quarterly) as $ratios) {
    echo "Current Ratio: {$ratios->currentRatio}\n";
    echo "Debt to Equity: {$ratios->debtEquityRatio}\n";
}

// Market risk premium by country
foreach ($fmpClient->marketRiskPremium() as $premium) {
    echo "Country: {$premium->country} ({$premium->continent})\n";
    echo "Country Risk Premium: {$premium->countryRiskPremium}%\n";
    echo "Total Equity Risk Premium: {$premium->totalEquityRiskPremium}%\n";
}

// US Treasury rates
foreach ($fmpClient->treasuryRates() as $rate) {
    echo "Date: {$rate->date}\n";
    echo "1 Month: {$rate->month1}%, 3 Month: {$rate->month3}%\n";
    echo "1 Year: {$rate->year1}%, 10 Year: {$rate->year10}%\n";
    echo "30 Year: {$rate->year30}%\n";
}
```

### Asynchronous Operations

[](#asynchronous-operations)

```
// Execute multiple requests concurrently
$companyProfilePromise = $fmpClient->promise(fn() =>
    iterator_to_array($fmpClient->companyProfile('AAPL'))
);

$dividendsPromise = $fmpClient->promise(fn() =>
    iterator_to_array($fmpClient->dividends('AAPL'))
);

$keyMetricsPromise = $fmpClient->promise(fn() =>
    iterator_to_array($fmpClient->keyMetrics('AAPL'))
);

// Wait for all promises to complete
$profiles = $companyProfilePromise->wait();
$dividends = $dividendsPromise->wait();
$metrics = $keyMetricsPromise->wait();

echo "Loaded data for: " . $profiles[0]->companyName . "\n";
echo "Dividend count: " . count($dividends) . "\n";
echo "Metrics count: " . count($metrics) . "\n";
```

Available Endpoints
-------------------

[](#available-endpoints)

### Company &amp; Stock Data

[](#company--stock-data)

- `stockList()` - List all available stocks
- `companyProfile(string $symbols)` - Company profile information
- `companyProfileBulk()` - Bulk company profiles (streaming)
- `sharesFloat(string $symbol)` - Shares float information (free float, float shares, outstanding shares)
- `availableExchanges()` - Available stock exchanges
- `allExchangeMarketHours()` - Market hours for all exchanges

### Financial Statements

[](#financial-statements)

- `balanceSheetStatement(string $symbol)` - Balance sheet data
- `balanceSheetStatementBulk(string $year, Period $period)` - Bulk balance sheets
- `balanceSheetStatementGrowth(string $symbol, int|null $limit, PeriodQuery|null $period)` - Balance sheet growth metrics
- `balanceSheetStatementGrowthBulk(int $year, Period $period)` - Bulk balance sheet growth metrics
- `incomeStatement(string $symbol)` - Income statement data
- `incomeStatementBulk(string $year, Period $period)` - Bulk income statements
- `incomeStatementGrowth(string $symbol, int|null $limit, PeriodQuery|null $period)` - Income statement growth metrics
- `incomeStatementGrowthBulk(int $year, Period $period)` - Bulk income statement growth metrics
- `cashFlowStatement(string $symbol)` - Cash flow data
- `cashFlowStatementBulk(string $year, Period $period)` - Bulk cash flow statements
- `cashFlowStatementGrowth(string $symbol, int|null $limit, PeriodQuery|null $period)` - Cash flow growth metrics
- `cashFlowStatementGrowthBulk(int $year, Period $period)` - Bulk cash flow growth metrics
- `latestFinancialStatements(int $page, int $limit)` - Latest financial statements

### Market Data &amp; Quotes

[](#market-data--quotes)

- `eodBulkQuotes(DateTimeImmutable $date)` - End of day bulk quotes
- `batchExchangeQuote(string $exchange)` - Exchange quotes
- `batchExchangeQuoteDetailed(string $exchange)` - Detailed exchange quotes
- `batchForexQuotes()` - Forex currency quotes

### Historical Data

[](#historical-data-1)

- `historicalPriceEod(string $symbol, DateTimeImmutable $from, DateTimeImmutable $to)` - Historical prices
- `historicalChart(string $symbol, TimeInterval $interval, DateTimeImmutable $from, DateTimeImmutable $to)` - Historical chart data

### Analytics &amp; Metrics

[](#analytics--metrics)

- `keyMetrics(string $symbol, int $limit, PeriodQuery $period)` - Key financial metrics
- `keyMetricsTtm(string $symbol)` - TTM key metrics
- `keyMetricsTtmBulk()` - Bulk TTM key metrics
- `ratios(string $symbol, int $limit, PeriodQuery $period)` - Financial ratios
- `ratiosTtm(string $symbol)` - TTM ratios
- `ratiosTtmBulk()` - Bulk TTM ratios
- `financialScores(string $symbol)` - Financial scores
- `scoresBulk()` - Bulk financial scores
- `analystEstimates(string $symbol, string $period, int $page, int $limit)` - Analyst estimates
- `marketRiskPremium()` - Market risk premium by country
- `treasuryRates()` - US Treasury rates for various maturities

### Calendar Events

[](#calendar-events)

- `earningsCalendar(DateTimeImmutable $from, DateTimeImmutable $to, ?LoggerInterface $logger)` - Earnings calendar
- `dividendsCalendar(DateTimeImmutable $from, DateTimeImmutable $to, ?LoggerInterface $logger)` - Dividends calendar
- `splitsCalendar(DateTimeImmutable $from, DateTimeImmutable $to, ?LoggerInterface $logger)` - Stock splits calendar
- `dividends(string $symbol)` - Company dividend history

### Search

[](#search)

- `searchIsin(string $isin)` - Search for stocks by ISIN code

### Other Data

[](#other-data)

- `cryptocurrencyList()` - Available cryptocurrencies
- `indexList()` - Available market indices
- `financialStatementSymbolList()` - Symbols with financial statements

Data Types
----------

[](#data-types)

All API responses are mapped to strongly-typed readonly payload classes with comprehensive type annotations. Each payload class includes a `toArray()` method that returns all properties as an associative array.

Example payload structure:

```
// CompanyProfile payload
readonly class CompanyProfile {
    public function __construct(
        public string $symbol,
        public ?float $price = null,
        public ?int $marketCap = null,
        public ?string $companyName = null,
        // ... more properties
    ) {}

    /**
     * @return array{symbol: string, price: float|null, marketCap: int|null, companyName: string|null, ...}
     */
    public function toArray(): array {
        // Returns all properties as associative array
    }
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run static analysis:

```
composer phpstan
```

The library includes comprehensive tests with real API response fixtures and uses MockHttpClient for reliable testing without API dependencies.

Architecture
------------

[](#architecture)

The library follows these key design principles:

- **Memory Efficiency**: Uses streaming parsers (JsonMachine, League CSV) to handle large responses without loading entire datasets into memory
- **Async Processing**: Leverages PHP Fibers through FmpPromise for concurrent request handling
- **Immutable Data**: All payload objects are readonly and immutable
- **Strong Typing**: Comprehensive type hints throughout the codebase
- **Error Resilience**: Graceful handling of malformed API responses with optional strict validation

### Core Components

[](#core-components)

- **FmpClient** - Main entry point with all API methods
- **FmpPromise** - Async operations using PHP Fibers
- **LargeResponseParser** - Memory-efficient streaming parser
- **FmpPayloadMapper** - Maps API responses to typed objects
- **FmpValidator** - Data validation layer

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass: `composer test`
5. Run static analysis: `composer phpstan`
6. Submit a pull request

License
-------

[](#license)

This library is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Financial Modeling Prep API
---------------------------

[](#financial-modeling-prep-api)

This library provides a PHP interface to the [Financial Modeling Prep API](https://financialmodelingprep.com/). You'll need an API key from FMP to use this library. Visit their website to sign up and get your API key.

Links
-----

[](#links)

- [Financial Modeling Prep API Documentation](https://financialmodelingprep.com/developer/docs)
- [PHP 8.3 Documentation](https://www.php.net/releases/8.3/en.php)
- [Symfony HTTP Client](https://symfony.com/doc/current/http_client.html)

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance61

Regular maintenance activity

Popularity14

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity14

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/312e788a47a251e05734378921d4596a91819b7de416fa18e77aa69e08798ea8?d=identicon)[Antik](/maintainers/Antik)

---

Top Contributors

[![MartkCz](https://avatars.githubusercontent.com/u/10145362?v=4)](https://github.com/MartkCz "MartkCz (65 commits)")

### Embed Badge

![Health badge](/badges/shredio-fmp-client/health.svg)

```
[![Health](https://phpackages.com/badges/shredio-fmp-client/health.svg)](https://phpackages.com/packages/shredio-fmp-client)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
