# Alphavantage Laravel API

This Laravel package provides an easy way to access the Alphavantage API. With it, you can i.e. fetch historical financial data, including stock prices, forex, and cryptocurrency information. It integ


# Installation

Installation of the Alphavantage Laravel API

You can install the package via composer:

```bash
composer require tschucki/alphavantage-laravel
```

You can publish the config file with:

```bash
php artisan vendor:publish --tag="alphavantage-laravel-config"
```

This is the contents of the published config file:

```php
return [
    'key' => env('ALPHAVANTAGE_API_KEY'),
];
```

Pay Alphavantage and get your API key [here](https://www.alphavantage.co/support/#api-key).

You are now ready to take off.


# Basic Usage

Usage of the Alphavantage Laravel API Package

I tried to make the package as easy to use as possible. I tried to follow the [Alphavantage](https://www.alphavantage.co/documentation/) API documentation as closely as possible. So if you are familiar with the API, you should feel right at home. You have access to the following categories:

* Core
* Fundamentals
* Indicators
* Intelligence

You can either use the facade access these categories or use the `Alphavantage` class directly.

```php
use Tschucki\Alphavantage;

Alphavantage::timeSeries()->daily('IBM');
```


# Deep Dive

The package follows the original Alphavantage API Documentation. So the endpoints are grouped behind Categories.


# TimeSeries

The `TimeSeries` class provides methods to interact with various time series endpoints of the Alphavantage API. It includes methods for fetching daily, weekly, and monthly time series data, both adjusted and unadjusted.

### Methods

#### 1. Daily

Fetches daily time series data for a given stock symbol.

**Signature:**

```php
public function daily(string $symbol, string $outputSize = 'compact'): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch daily time series data for.
* `outputSize` (string): The size of the output. Must be 'compact' or 'full'. Default is 'compact'.

**Returns:**

* `array`: An array containing the daily time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 2. Daily Adjusted

Fetches adjusted daily time series data for a given stock symbol.

**Signature:**

```php
public function dailyAdjusted(string $symbol, string $outputSize = 'compact'): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch adjusted daily time series data for.
* `outputSize` (string): The size of the output. Must be 'compact' or 'full'. Default is 'compact'.

**Returns:**

* `array`: An array containing the adjusted daily time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 3. Weekly

Fetches weekly time series data for a given stock symbol.

**Signature:**

```php
public function weekly(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch weekly time series data for.

**Returns:**

* `array`: An array containing the weekly time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 4. Weekly Adjusted

Fetches adjusted weekly time series data for a given stock symbol.

**Signature:**

```php
public function weeklyAdjusted(string $symbol, string $outputSize = 'compact'): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch adjusted weekly time series data for.
* `outputSize` (string): The size of the output. Must be 'compact' or 'full'. Default is 'compact'.

**Returns:**

* `array`: An array containing the adjusted weekly time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 5. Monthly

Fetches monthly time series data for a given stock symbol.

**Signature:**

```php
public function monthly(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch monthly time series data for.

**Returns:**

* `array`: An array containing the monthly time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 6. Monthly Adjusted

Fetches adjusted monthly time series data for a given stock symbol.

**Signature:**

```php
public function monthlyAdjusted(string $symbol, string $outputSize = 'compact'): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch adjusted monthly time series data for.
* `outputSize` (string): The size of the output. Must be 'compact' or 'full'. Default is 'compact'.

**Returns:**

* `array`: An array containing the adjusted monthly time series data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

***

The `TimeSeries` class is designed to provide an easy way to fetch various time series data using the Alphavantage API. It includes methods for daily, weekly, and monthly time series data, both adjusted and unadjusted. Be sure to handle the possible exceptions when using these methods to ensure robust error handling in your application.


# Core

The `Core` class provides methods to interact with essential endpoints of the Alphavantage API. It includes methods for fetching global quotes and searching for stock symbols.

### Methods

#### 1. Quote Endpoint

Fetches the latest global quote for a given stock symbol.

**Signature:**

```php
public function quoteEndpoint(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the global quote for.

**Returns:**

* `array`: An array containing the global quote data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 2. Search

Searches for stock symbols based on keywords.

**Signature:**

```php
public function search(string $keywords): array
```

**Parameters:**

* `keywords` (string): The keywords to search for stock symbols.

**Returns:**

* `array`: An array containing the search results.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

***

The `Core` class is designed to provide essential functionalities using the Alphavantage API. The `quoteEndpoint` method fetches the latest global quote for a given stock symbol, while the `search` method allows for searching stock symbols based on keywords. Be sure to handle the possible exceptions when using these methods to ensure robust error handling in your application.


# Fundamental

The `Fundamentals` class provides methods to interact with various endpoints of the Alphavantage API related to fundamental financial data. Each method fetches specific financial information about a given symbol or other relevant parameters.

### Methods

#### 1. Overview

Fetches the company overview for a given symbol.

**Signature:**

```php
public function overview(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the overview for.

**Returns:**

* `array`: An array containing the company overview data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 2. Income Statement

Fetches the income statement for a given symbol.

**Signature:**

```php
public function incomeState(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the income statement for.

**Returns:**

* `array`: An array containing the income statement data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 3. Balance Sheet

Fetches the balance sheet for a given symbol.

**Signature:**

```php
public function balanceSheet(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the balance sheet for.

**Returns:**

* `array`: An array containing the balance sheet data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 4. Cash Flow

Fetches the cash flow statement for a given symbol.

**Signature:**

```php
public function cashFlow(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the cash flow statement for.

**Returns:**

* `array`: An array containing the cash flow data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 5. Earnings

Fetches the earnings report for a given symbol.

**Signature:**

```php
public function earnings(string $symbol): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the earnings report for.

**Returns:**

* `array`: An array containing the earnings data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 6. Listing Status

Fetches the listing status of companies, either active or delisted, optionally filtered by date.

**Signature:**

```php
public function listingStatus(?Carbon $date = null, string $state = 'active'): array
```

**Parameters:**

* `date` (Carbon|null): Optional date to filter the listing status.
* `state` (string): The listing state, either 'active' or 'delisted'.

**Returns:**

* `array`: An array containing the listing status data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`
* `InvalidArgumentException`: Thrown if the state is not 'active' or 'delisted'.

#### 7. Earnings Calendar

Fetches the earnings calendar for a given symbol over a specified number of months.

**Signature:**

```php
public function earningsCalendar(?string $symbol, int $months = 3): array
```

**Parameters:**

* `symbol` (string|null): The stock symbol to fetch the earnings calendar for.
* `months` (int): The number of months to look ahead. Default is 3.

**Returns:**

* `array`: An array containing the earnings calendar data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

#### 8. IPO Calendar

Fetches the IPO calendar data.

**Signature:**

```php
public function ipoCalendar(): array
```

**Parameters:**

* None

**Returns:**

* `array`: An array containing the IPO calendar data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

***

Each method in the `Fundamentals` class is designed to interact with a specific endpoint of the Alphavantage API, ensuring easy and efficient retrieval of financial data. Be sure to handle the possible exceptions when using these methods to ensure robust error handling in your application.


# Indicators

The `Indicators` class provides methods to interact with various technical indicator endpoints of the Alphavantage API. It includes methods for fetching different types of moving averages and other technical indicators for a given stock symbol.

### Methods

#### 1. Private Method: getIndicator

This is a private method used internally to fetch data for various technical indicators.

**Signature:**

```php
private function getIndicator(
    string $function, 
    string $symbol, 
    string $interval, 
    int $timePeriod, 
    string $seriesType, 
    ?string $month = null, 
    string $dataType = 'json'
): array
```

**Parameters:**

* `function` (string): The technical indicator function to call (e.g., 'SMA').
* `symbol` (string): The stock symbol to fetch data for.
* `interval` (string): The time interval between data points. Must be one of: '1min', '5min', '15min', '30min', '60min', 'daily', 'weekly', 'monthly'.
* `timePeriod` (int): The number of data points used to calculate the indicator.
* `seriesType` (string): The desired price series type. Must be one of: 'close', 'open', 'high', 'low'.
* `month` (string|null): Optional month parameter, valid only for intraday intervals.
* `dataType` (string): The data type of the response. Must be 'json' or 'csv'.

**Returns:**

* `array`: An array containing the indicator data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`
* `InvalidArgumentException`: Thrown if any of the parameters are invalid.

#### 2. Simple Moving Average (SMA)

Fetches the Simple Moving Average (SMA) for a given stock symbol.

**Signature:**

```php
public function sma(
    string $symbol, 
    string $interval, 
    int $timePeriod, 
    string $seriesType, 
    ?string $month = null, 
    string $dataType = 'json'
): array
```

**Parameters:**

* `symbol` (string): The stock symbol to fetch the SMA for.
* `interval` (string): The time interval between data points. Must be one of: '1min', '5min', '15min', '30min', '60min', 'daily', 'weekly', 'monthly'.
* `timePeriod` (int): The number of data points used to calculate the SMA.
* `seriesType` (string): The desired price series type. Must be one of: 'close', 'open', 'high', 'low'.
* `month` (string|null): Optional month parameter, valid only for intraday intervals.
* `dataType` (string): The data type of the response. Must be 'json' or 'csv'.

**Returns:**

* `array`: An array containing the SMA data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`
* `InvalidArgumentException`: Thrown if any of the parameters are invalid.

***

The `Indicators` class is designed to provide an easy way to fetch various technical indicators using the Alphavantage API. The `getIndicator` method serves as a utility function to handle common logic for different indicators, while the `sma` method provides a specific implementation for fetching the Simple Moving Average. Be sure to handle the possible exceptions when using these methods to ensure robust error handling in your application.


# Intelligence

The `Intelligence` class provides methods to interact with various intelligence-related endpoints of the Alphavantage API. It includes methods for fetching news sentiment and top gainers and losers.

### Methods

#### 1. News

Fetches news sentiment for given tickers and topics within a specified time range.

**Signature:**

```php
public function news(
    array $tickers, 
    array $topics = [], 
    ?Carbon $timeFrom = null, 
    ?Carbon $timeTo = null, 
    string $sort = 'LATEST', 
    int $limit = 10000
): array
```

**Parameters:**

* `tickers` (array): An array of stock tickers to fetch news for.
* `topics` (array): An array of topics to filter news by. Default is an empty array.
* `timeFrom` (Carbon|null): The start time for fetching news. Default is null.
* `timeTo` (Carbon|null): The end time for fetching news. Default is null.
* `sort` (string): The sorting order of the news. Must be 'LATEST', 'EARLIEST', or 'RELEVANCE'. Default is 'LATEST'.
* `limit` (int): The maximum number of news items to fetch. Default is 10000.

**Returns:**

* `array`: An array containing the news sentiment data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`
* `InvalidArgumentException`: Thrown if the sort parameter is invalid.

#### 2. Gainers and Losers

Fetches the top gainers and losers.

**Signature:**

```php
public function gainersAndLosers(): array
```

**Parameters:**

* None

**Returns:**

* `array`: An array containing the top gainers and losers data.

**Exceptions:**

* `ApiVolumeReached`
* `ConnectionException`

***

The `Intelligence` class is designed to provide an easy way to fetch various intelligence-related data using the Alphavantage API. The `news` method allows for fetching news sentiment based on tickers and topics within a specified time range and sort order. The `gainersAndLosers` method fetches the top gainers and losers. Be sure to handle the possible exceptions when using these methods to ensure robust error handling in your application.


# Exceptions


# ApiVolumeReached Exception

**Exception Class:** `Tschucki\Alphavantage\Exceptions\ApiVolumeReached`

**Description:**

* This exception is thrown when the API call cannot be completed because the maximum API call volume has been reached for your current API plan or API key.

**Possible Causes:**

* Your API plan or key has reached its daily or monthly limit of API calls allowed by Alphavantage.
* You may need to upgrade your API plan or wait until your API call limit resets according to Alphavantage's policies.

**Handling:**

* If you encounter this exception, you should consider upgrading your Alphavantage API plan to allow for more API calls per day or month.
* Implement retry logic with exponential backoff if possible, as suggested by Alphavantage's rate limit documentation.
* Inform users or administrators about the limitation and possible solutions to avoid future interruptions.


# ConnectionException Exception

**Exception Class:** `Illuminate\Http\Client\ConnectionException`

**Description:**

* This exception is thrown when a connection to the Alphavantage API server cannot be established or when the connection is unexpectedly terminated.

**Possible Causes:**

* Network issues, such as timeouts or DNS resolution failures.
* Temporary unavailability of the Alphavantage API servers.
* Server-side issues or maintenance on the Alphavantage side.

**Handling:**

* Implement retry logic with exponential backoff to handle transient network issues.
* Monitor network health and Alphavantage API status for ongoing issues.
* Provide informative error messages to users about the connection problem and any recommended actions (e.g., check network connection, try again later).


# InvalidArgumentException Exception

**Exception Class:** `\InvalidArgumentException`

**Description:**

* This exception is thrown when an invalid argument is passed to a method in the API wrapper.

**Possible Causes:**

* Incorrect values or types provided as arguments to API methods.
* Parameters that do not meet the expected format or criteria.

**Handling:**

* Validate input parameters before making API calls to ensure they meet the required format and constraints.
* Provide clear error messages indicating which argument caused the exception and why it is invalid.
* Document the expected formats and values for parameters in your API wrapper's documentation to guide users.

***

These exceptions help provide clear feedback and handling mechanisms for potential issues that may arise while interacting with the Alphavantage API through your wrapper. Handling these exceptions effectively will enhance the reliability and usability of your API integration.


