Fetching real-time share prices from stock exchanges like the London Stock Exchange (LSE) can be crucial for investors and financial applications. In this article, we’ll explore how to retrieve share price data for LSE stocks and other exchanges using PHP.
We’ll use a combination of API calls and caching to efficiently fetch and display share prices. This method can be applied to various stocks, not just those on the LSE.
Choosing a Data Source
To fetch real-time share prices, you need a reliable data source. There are numerous options available, each with its own advantages and limitations. Some popular choices include:
- Alpha Vantage
- IEX Cloud
- Finnhub
- Polygon.io
- Quandl
When selecting a data source, consider factors such as data accuracy, update frequency, API limits, pricing, and the specific markets or exchanges covered. For a comprehensive comparison of various stock market data APIs, you can refer to resources like the Portfolio Optimizer blog.
In this example, we’ll use the Yahoo Finance Chart API. While not officially documented, it’s widely used due to its reliability and free access. However, keep in mind that for production applications, especially those with high volume or commercial use, it’s advisable to use an official, paid API service to ensure consistent access and compliance with terms of service.
Fetching Share Prices with PHP
Here’s a PHP function that retrieves the share price for a given stock symbol:
This function uses the Yahoo Finance API to fetch real-time stock data. It includes a caching mechanism to reduce API calls and improve performance.
$url = "https://query1.finance.yahoo.com/v8/finance/chart/RR.L"; // URL to fetch stock price data
$cacheFile = __DIR__ . '/share_cache.txt'; // Path to cache file
$cacheTime = 300; // Cache time in seconds (5 minutes)
// Check if cache file exists and is still valid
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
// Read from cache
$data = json_decode(file_get_contents($cacheFile), true);
} else {
// Fetch new data
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)'); // User agent string
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Timeout in seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: */*')); // Accept header
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL peer verification
$response = curl_exec($ch); // Execute cURL request and store response
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
curl_close($ch); // Close cURL session
$data = json_decode($response, true); // Decode JSON response
// Save to cache
file_put_contents($cacheFile, $response);
}
if (is_array($data)) {
$price = number_format($data['chart']['result'][0]['meta']['regularMarketPrice'], 2,".",",");
?><p><strong>RR.L:</strong> GBp <?php echo number_format( $price ,2,".",","); ?></p><?php
}
It will return a pre-formatted html share price for use in your WordPress template. You can edit the functions to change the formatting:
<p><strong>RR.L:</strong> GBp 556.20</p>
Using the Function
To use this function as a wordpress shortcode, you need to register it in functions.php. For example:
add_shortcode('sc_get_share_price', 'get_share_price');
Full code example
function get_share_price($atts, $content=null){
ob_start(); // start buffer to capture output of the function
$url = "https://query1.finance.yahoo.com/v8/finance/chart/RR.L"; // URL to fetch stock price data
$cacheFile = __DIR__ . '/share_cache.txt'; // Path to cache file
$cacheTime = 300; // Cache time in seconds (5 minutes)
// Check if cache file exists and is still valid
if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $cacheTime)) {
// Read from cache
$data = json_decode(file_get_contents($cacheFile), true);
} else {
// Fetch new data
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)'); // User agent string
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Timeout in seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: */*')); // Accept header
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL peer verification
$response = curl_exec($ch); // Execute cURL request and store response
if (curl_errno($ch)) {
throw new Exception(curl_error($ch));
}
curl_close($ch); // Close cURL session
$data = json_decode($response, true); // Decode JSON response
// Save to cache
file_put_contents($cacheFile, $response);
}
if (is_array($data)) {
$price = number_format($data['chart']['result'][0]['meta']['regularMarketPrice'], 2,".",",");
?><p><strong>RR.L:</strong> GBp <?php echo number_format( $price ,2,".",","); ?></p><?php
}
return ob_get_clean(); // return the captured output
}
add_shortcode('sc_get_share_price', 'get_share_price');
This versatile approach allows you to fetch share prices from various stock exchanges, not just the LSE. The function automatically handles different currencies and formats the output consistently.
Now you can use the shortcode in your pages, posts and widgets:
[sc_get_share_price]
Benefits of Caching
The caching mechanism in this function offers several advantages:
- Reduced API calls, preventing rate limiting issues
- Faster response times for frequently requested stocks
- Lower server load, especially for high-traffic websites
By caching the data for 5 minutes, we strike a balance between having up-to-date information and maintaining good performance.