Highcharts|Stock calendar

highcharts logo



在這篇文章中,我們將建立一個股票日曆演示,這是一個集成了日曆和股票價格顯示的區域股票圖。其結果顯示在下面的演示中。


讓我們看看如何創建一個股票日曆演示。

在這個演示中,我們使用jQuery Datepicker來管理日曆,因為它開箱即用,可以在頁面加載後立即自動打開,而瀏覽器的默認拾取器需要用戶的操作才能顯示。當然,你也可以使用其他任何日期選擇器。

股票價格顯示只是一個簡單的HTML輸出區。

日期選擇器和HTML輸出區域都顯示在圖表的容器之外。

股票價格顯示只是一個簡單的HTML輸出區域。

Datepicker和HTML輸出區域都顯示在圖表的容器之外。

我們使用一個區域系列類型來顯示存儲在數據陣列中的隨機數據集。默認情況下,這個系列在圖表上只顯示一個y數據。在我們的案例中,我們希望顯示所有的開盤價、最高價、最低價和收盤價。為了映射它們,我們使用series.key屬性。

keys: ['x', 'custom.open', 'custom.high', 'custom.low', 'y'] 。現在,我們可以直接從點讀取所有的值。

openCell.innerText = point.custom.open.toFixed(2) + '$';
highCell.innerText = point.custom.high.toFixed(2) + '$';
lowCell.innerText = point.custom.low.toFixed(2) + '$';
closeCell.innerText = point.y.toFixed(2) + '$';

為了在股票價格顯示中顯示所有懸停的點值,我們使用了mouseOver事件。此外,我們在Datepicker中突出顯示懸停的日期,並在區域圖上呈現一個紅色的情節線。

const showDataInfo = (chart, point, date) => {
  const plotLinesAndBands = chart.xAxis[0].plotLinesAndBands;

  if (plotLinesAndBands && plotLinesAndBands.length) {
    plotLinesAndBands[0].destroy();
  }

  chart.xAxis[0].addPlotLine({
    value: date,
    color: 'red',
    lineWidth: 3
  });

  openCell.innerText = point.custom.open.toFixed(2) + '$';
  highCell.innerText = point.custom.high.toFixed(2) + '$';
  lowCell.innerText = point.custom.low.toFixed(2) + '$';
  closeCell.innerText = point.y.toFixed(2) + '$';
};

備註

使用destroy和add AP來分別刪除和創建繪圖線。

現在讓我們為jQuery Datepicker添加邏輯--點擊一個特定的日期將找到具有相應X值的點,將其置於圖形中心,並顯示上述所有信息。

$('#date-picker').datepicker({
  beforeShowDay: $.datepicker.noWeekends,
  // First available date
  minDate: -Math.ceil(lastX - firstX) / DAY - 1,
  maxDate: -1 // today
});
$.datepicker.setDefaults({
  // Set the datepicker's date format
  dateFormat: 'yy-mm-dd',
  onSelect: function(dateText) {
    const clickedDateStr = dateText.split('-'),
      clickedDate = Date.UTC(clickedDateStr[0], clickedDateStr[1] - 1, clickedDateStr[2]);

    // Show 20 points on the graph
    chart.xAxis[0].setExtremes(
      clickedDate - DAY * 10,
      clickedDate + DAY * 10
    );
    const points = chart.series[0].points;
    let point;
    for (let i in points) {
      if (dateFormat('%Y-%m-%d', points[i].x) === dateText) {
        point = points[i];
        break;
      }
    }
    if (point) {
      showDataInfo(chart, point, clickedDate);
    }
  }
});

注意事項 使用setExtremes API來設置渲染後軸的最小值和最大值。 這就是它! 現在你知道如何創建一個帶有日期選擇器和股票價格顯示的實用區域股票圖。

延伸閱讀
aa71435723的大頭照
Winston

Eggplant DAI 自動化測試專家。

留言