RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts</strong | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.39% (5.84%*) • Fixed: 5.39% (5.84%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.69% (6.19%*) • Investment PI: 5.55% (6.02%*)

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

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

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment