Skip to content

Examples

Igor Sazonov edited this page Feb 4, 2026 · 1 revision

Examples

This section provides real-world examples of how to use the Marketstack PHP SDK to build common financial applications and features.

Building a Stock Portfolio Tracker

You can use the SDK to track the value of a stock portfolio in real time.

use Tigusigalpa\Marketstack\Facades\Marketstack;

// Your portfolio of stocks
$portfolio = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'AMZN'];

$latestPrices = Marketstack::eod()
    ->symbols(...$portfolio)
    ->latest()
    ->collect();

$totalValue = 0;
foreach ($latestPrices as $stock) {
    $shares = getSharesOwned($stock->symbol); // Your function to get the number of shares
    $value = $stock->close * $shares;
    $totalValue += $value;
    
    echo "{$stock->symbol}: {$shares} shares @ \${$stock->close} = \${$value}\n";
}

echo "Total Portfolio Value: \${$totalValue}";

Real-time Price Monitoring

Monitor intraday price movements for a specific stock.

$priceData = Marketstack::intraday()
    ->symbols('TSLA')
    ->interval('5min')
    ->dateFrom(now()->subHours(6)->format('Y-m-d'))
    ->collect();

foreach ($priceData as $tick) {
    echo "[{$tick->date}] TSLA: Open: \${$tick->open}, High: \${$tick->high}, Low: \${$tick->low}, Close: \${$tick->close}\n";
}

Historical Data Analysis

Analyze the historical performance of a stock over a specific period.

$historicalData = Marketstack::eod()
    ->symbols('AAPL')
    ->dateFrom(now()->subYear()->format('Y-m-d'))
    ->dateTo(now()->format('Y-m-d'))
    ->sort('ASC')
    ->collect();

$startPrice = $historicalData->first()->close;
$endPrice = $historicalData->last()->close;
$percentChange = (($endPrice - $startPrice) / $startPrice) * 100;

echo "AAPL 1-Year Performance: " . number_format($percentChange, 2) . "%";

Multi-Exchange Stock Screener

Find stocks that match specific criteria across different exchanges.

$nasdaqTickers = Marketstack::tickers()
    ->exchange('XNAS')
    ->search('technology')
    ->limit(50)
    ->collect();

foreach ($nasdaqTickers as $ticker) {
    echo "{$ticker->symbol} - {$ticker->name}\n";
}

Currency Conversion for International Stocks

Retrieve stock prices and convert them to a different currency.

$stock = Marketstack::eod()->latest('AAPL')->dto();
$currency = Marketstack::currencies()->code('EUR')->dto();

// This is a simplified example. You would need a currency conversion rate.
echo "AAPL in USD: \${$stock->close}\n";
echo "Currency: {$currency->name} ({$currency->symbol})\n";

Clone this wiki locally