Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Add Stock Quote Graphs to WordPress With Shortcode (Alpha Vantage API)

Alpha Vantage describe themselves as a "... tight-knit community of researchers, engineers, and business professionals" that are a "a leading provider of free APIs for realtime and historical stock market data." They claim that their success is "driven by rigorous research, cutting edge technology, and a disciplined focus on democratizing access to data." It's rare to find a supplier of freely available source of stock data and, despite making attempts to find 'the catch', thus far I'm suitably impressed with their tools. Alpha offer free API access with an extremely permissive quote of 100 queries per minute.

Note: The Google Graphs will soon be replaced with more reliable representations. Until then, don't be surprised if the graphs fail to render.

This is the first of a number of articles we'll write that deal with displaying stock market data, and it's the latest in an ongoing series that seeks to utilize Google Charts to render interesting data (in particularly financial data for our partners in relevant industries).

Given the broad scope of Alpha's data, it's difficult to provide the array of examples necessary to illustrate the multiple means in which to represent the information they provide. For that reason we'll provide a single WordPress shortcode example that'll only render the close price of FORD (F) stock.

The Result

Graphing the closing price of FORD stock (TIME_SERIES_DAILY, default) is returned with the following shortcode: [stock symbol="F"].

Add Stock Quote Graphs to WordPress With Shortcode (Alpha Vantage API)

Note: If you're seeing an empty graph it's because the attempt to retrieve data was unsuccessful (the API isn't overly reliable). If this behaviour continues, consider using Simple Cache (which returns old data if the API request was unsuccessful) or storing the result as a post option (and using the transient as a trigger).

WordPress Shortcode

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
    Add Stock Quote Graphs to WordPress With Shortcode
4
    http://www.beliefmedia.com/stock-quote-graph-wordpress
5
*/
6
 
7
 
8
9
 
10
  $atts = shortcode_atts(array(
11
    'symbol' => 'F',
12
    'width' => '600',
13
    'height' => '410',
14
    'time' => '2',
15
    'number' => '90',
16
    'size' => 'compac', /* compac or full */
17
    'interval' => '60', /* 1min, 5min, 15min, 30min, 60min */
18
    'apikey' => 'xxxxxxxxxxxxxxxxx',
19
    'cache' => 3600
20
  ), $atts);
21
 
22
 $transient = 'bmaast_' . md5(serialize($atts));
23
 $cachedposts = get_transient($transient);
24
 
25
 if ($cachedposts !== false) {
26
  return $cachedposts;
27
 
28
 } else {
29
 
30
    switch ($atts['time']) {
31
        case 1:
32
            $series = 'TIME_SERIES_INTRADAY';
33
            $series_name = 'Time Series (' . $atts['interval'] . 'min)';
34
            break;
35
        case 2:
36
            $series = 'TIME_SERIES_DAILY';
37
            $series_name = 'Time Series (Daily)';
38
            break;
39
        case 3:
40
            $series = 'TIME_SERIES_DAILY_ADJUSTED';
41
            $series_name = 'Time Series (Daily)';
42
            break;
43
        case 4:
44
            $series = 'TIME_SERIES_WEEKLY';
45
            $series_name = 'Weekly Time Series';
46
            break;
47
        case 5:
48
            $series = 'TIME_SERIES_MONTHLY';
49
            $series_name = 'Monthly Time Series';
50
            break;
51
        default:
52
            $series = 'Time Series (Daily)';
53
            break;
54
    }
55
 
56
    /* Get Stock data */
57
    $data = @file_get_contents('https://www.alphavantage.co/query?function=' . $series . '&symbol=' . strtoupper($atts['symbol']) . '&interval=' . $atts['interval'] . 'min&apikey=' . $atts['apikey'] . '&interval=' . $atts['interval'] . 'min&outputsize=' . $atts['size']);
58
    if ($data === false) return '<p>Data currently unavailable.</p>';
59
    $data = json_decode($data, true);
60
    $data = $data[$series_name];
61
 
62
    /* Return portion of results & reverse */ 
63
    if ($atts['number'] != '') $data = array_slice($data, 0, $atts['number'], true);
64
    $data = array_reverse($data, true);
65
 
66
    foreach ($data AS $key => $value) {
67
      $chart .= ',[new Date(' . str_replace(array('-', ' ', ':'), ',', $key) . '), ' . $value['4. close'] . ']';
68
    }
69
 
70
    $chart = ltrim($chart, ',');
71
 
72
   /* Build chart with fresh data */
73
   $return = "<script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
74
    <script type='text/javascript'>
75
      google.charts.load('current', {packages: ['corechart', 'line']});
76
      google.charts.setOnLoadCallback(drawTrendlines);
77
 
78
    function drawTrendlines() {
79
      var data = new google.visualization.DataTable();
80
        data.addColumn('date', 'Date');
81
        data.addColumn('number', 'Close');
82
 
83
      data.addRows([
84
        $chart
85
      ]);
86
 
87
      var options = {
88
        hAxis: {
89
          title: 'Date'
90
        },
91
        backgroundColor: 'transparent',
92
        vAxis: {
93
          title: 'Stock Price'
94
        },
95
        colors: ['#AB0D06'],
96
        trendlines: {
97
          // 0: {type: 'exponential', color: '#333', opacity: 1},
98
          // 1: {type: 'linear', color: '#111', opacity: .3}
99
        }
100
      };
101
 
102
      var chart = new google.visualization.LineChart(document.getElementById('chart_div_$interval'));
103
      chart.draw(data, options);
104
    }
105
    </script>";
106
 
107
    /* Chart container */
108
    $return .= '<div id="chart_div_' . $interval . '" style="width: ' . $atts['width'] . 'px; height: ' . $atts['height'] . 'px;"></div>';
109
 
110
   /* Set transient chart data */
111
   set_transient($transient, $return, $atts['cache']);
112
   return $return;
113
 }
114
}
115
add_shortcode('stock', 'beliefmedia_alphavantage_quotes');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

Shortcode Attributes

Given the scope of data returned by Alpha Vantage is rather broad, the shortcode needs to built upon to return more robust graphs. The basic attributes for single-line line-graphs are detailed below.

symbol

The appropriate stock symbol. Some symbols return limited data.

width

The width of your graph DIV container.

height

The height of your graph DIV container.

time

The time determines what range of data is returned. The most commonly used (and those that are supported in the shortcode) include 1 (TIME_SERIES_INTRADAY), 2 (TIME_SERIES_DAILY), 3 (TIME_SERIES_DAILY_ADJUSTED), 4 (TIME_SERIES_WEEKLY) and 5 (TIME_SERIES_MONTHLY).

number

If truncting the size of the returned array, use number="90" (where 90 is the number of data points).

size

The size may be compac (default) or full. The latter returns far more historical data (perhaps reserved for CSV downloads).

interval

If you're rendering regular quotes (up to every single minute, using TIME_SERIES_INTRADAY endpoint), you can choose to return intervals of 1min, 5min, 15min, 30min, or 60min. Include only the integer.

apikey

The API key is free and can be retrieved via Alpha Vantage website . Queries are limited to an extremely permissive 100 requests per minute.

cache

The time interval to cache the entire graph and data. Defaults to one hour. Keep in mind it takes time to retrieve and process the data.

PHP Function

A PHP function is available here for use outside of WordPress. Usage requires Simple Cache.

Considerations

  • Register for an API key here .
  • Details on Google's Line Charts here .
  • The data is returned with a header that includes the symbol and refresh time. It's the second array that includes the stock data. Note that it includes open, high, low, close, and volume data. We're using the close price the purpose of the example. Example data below:

    1
    Array
    2
    (
    3
        [Meta Data] => Array
    4
            (
    5
                [1. Information] => Intraday (1min) prices and volumes
    6
                [2. Symbol] => KPG
    7
                [3. Last Refreshed] => 2017-10-02 20:04:00
    8
                [4. Interval] => 1min
    9
                [5. Output Size] => Compact
    10
                [6. Time Zone] => US/Eastern
    11
            )
    12
     
    13
        [Time Series (1min)] => Array
    14
            (
    15
                [2017-10-02 20:04:00] => Array
    16
                    (
    17
                        [1. open] => 1.5700
    18
                        [2. high] => 1.5800
    19
                        [3. low] => 1.5700
    20
                        [4. close] => 1.5800
    21
                        [5. volume] => 1500
    22
                    )
    23
     
    24
                [2017-10-01 19:08:00] => Array
    25
                    (
    26
                        [1. open] => 1.5700
    27
                        [2. high] => 1.5700
    28
                        [3. low] => 1.5700
    29
                        [4. close] => 1.5700
    30
                        [5. volume] => 627
    31
                    )
    32
     
    33
                ...

  • Google Graphs can be quite slow for large amounts of data. Consider swapping for another open source and locally hosted graphing library. If you're a client, we'll do this for you.
  • If you're after some active quotes to play with, use this list from the WSJ.
  • The time returned is USA Eastern. To convert to local, use strtotime() to convert the time to a timestamp, subtract or add the UTC offset, then convert back to the correct data format with date(). If you're taking this path you won't need the str_replace() array as provided; simply return the date chunks formatted with a comma.
  • Google's Candlestick Chart is ideal because it renders the high and low range of trade along with the open and close price (in the block). An example for General Motors (GM) graph is as follows:

    Add Stock Quote Graphs to WordPress With Shortcode (Alpha Vantage API)


Download

Title: Add Stock Quote Graphs With WordPress Shortcode
Description: Add a stock quote graph with a PHP function. Utilizes the Alpha Vantage API. WordPress shortcode version is also available.
  Download • Version 0.1, 1.6K, zip, Category: WordPress Shortcodes
PHP Code & Snippets, (1.6K)    

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment

READY TO HAVE A CHAT? CALL US ANYTIME ON 1300 235 433