RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Add Stock Quote Graphs With PHP (Alpha Vantage API)

The PHP function on this page supports the article published here, titled "Add Stock Quote Graphs to WordPress With Shortcode (Alpha Vantage API)". The PHP function retrieves stock data from the Alpha Vantage API and renders it into a Google graph. It's rather incomplete in that it only seeks to provide a single generic example of how the data might be used.

Find the WordPress shortcode article here.

The function requires use of Simple Cache.

PHP Function

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

Usage

The function requires only a stock symbol. To alter the default attributes as defined by the $atts array, pass them via an $args array as a second function argument.

1
<?php 
2
/* Basic usage */
3
echo beliefmedia_alphavantage_quotes($symbol = 'F');

WordPress Shortcode Result

The result as returned from our shortcode function is as follows:

Add Stock Quote Graphs With PHP (Alpha Vantage API)

Download

Download the WordPress shortcode here.

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

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

Leave a comment