Apple historical VaR

Basic example

by pablojim

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.15/c3.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.14/c3.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.js"></script>
<h3>Apple Historical VaR</h3>
<div class="chart"></div>

CSS

.chart {
  width: 100%;
  min-height: 440px;
}

JavaScript

fetch('https://raw.githubusercontent.com/mekhatria/demo_highcharts/master/AAPL.json', {
  mode: 'cors',
}).then(function(response) {
  return response.json()
}).then(function(data) {

  let unzipped = _.unzip(data);
  let prices = {
    x: unzipped[0],
    price: unzipped[1]
  };

  var prevPrice = data[0][1];
  prices.diff = prices.price.map(function(p) {
    let diff = ((p - prevPrice) / prevPrice) * 100.0;
    prevPrice = p;
    return diff;
  });
  console.log(prices);

  let diffMin = Math.min(...prices.diff)
  let histoRange = (Math.max(...prices.diff) - diffMin);
  let bins = 200;
  let binSize = histoRange / bins;

  let histo = {}
  //first pass make dict {binNo -> array of prices}
  prices.diff.map(function(p) {
    let binNo = Math.floor((p - diffMin) / binSize);
    if (histo[binNo]) {
      histo[binNo].push(p);
    } else {
      histo[binNo] = [p]
    }
  });
  console.log({
    histo
  });

  //second pass - convert to {bin min -> count of entries}
  let histogram = {
    x: [],
    count: []
  };
  for (let i = 0; i < bins; i++) {
    histogram.x.push((i * binSize) + diffMin);
    histogram.count.push(histo[i] ? histo[i].length : 0);
  }

  console.log({
    histogram
  });

  //let binNumbers = prices.diff.map(x => x.floor())


  return {
    prices,
    histogram
  }
}).then(function(data) {
  //console.log(prices)
  let prices = data.prices;
  var chart = c3.generate({
    bindto: d3.select('.chart'),
    data: {
      columns: [
        ['x'].concat(prices.x), ['price'].concat(prices.price)
      ],
      xFormat: '%Y-%m-%d',
      x: 'x',
    },
    transition: {
      duration: 1000
    },
    axis: {
      x: {
        type: 'timeseries',
        tick: {
          format: function(x) {
            return x.getFullYear() > 1980 ? x.getFullYear() : x.getTime() + '%';
          },
          //rotate: -50,
          multiline: false,
          count: 10,
          // culling: {
          //   max: 10 // the  number of tick texts will be...