0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactで実装した株価チャート~Chart.js から EChartsで移行

Posted at

はじめに

この記事では、株価データの可視化において「Chart.jsでできなかったこと」と「EChartsに変えて解決できたこと」をコードとスクリーンショット付きで解説します。
自らがハマってしまった箇所ではあるので、備忘録として残しておこうと思います。

なぜ Chart.js を使っていたのか?

最初にチャート描画するのにChart.jsを利用しましたが、その利用は以下の通りです。

  • React + TypeScript の構成で、軽量なチャートライブラリを探していた
  • react-chartjs-2 で簡単に導入できる
  • シンプルな構成ならこれで十分だった

Chart.js での限界(ハマったポイント)

image.png

実現したかったのにできなかったこと

  • 出来高とローソク足の2段チャート
  • ズーム・スライダー付きのデータ範囲選択
  • ローソク足に移動平均線(MA)を重ねる
  • 複数銘柄の比較チャートを横並びで表示するレイアウト
  • 土日などデータ欠損分を詰めて描画
    • 設定はありそうだったけど私が上手くできなかったのか。。

Chart.js の実装コード例

import {
  Chart as ChartJS,
  TimeScale,
  LinearScale,
  BarElement,
  CategoryScale,
  Tooltip,
  Legend,
} from 'chart.js';
import {
  CandlestickController,
  CandlestickElement,
} from 'chartjs-chart-financial';

ChartJS.register(
  TimeScale,
  LinearScale,
  BarElement,
  CategoryScale,
  CandlestickController,
  CandlestickElement,
  Tooltip,
  Legend
);

<Chart
  type="candlestick"
  data={{
    datasets: [
      {
        label: 'ローソク足',
        data: [ { x: new Date(), o: 100, h: 110, l: 90, c: 105 } ],
      },
    ],
  }}
  options={{ responsive: true }}
/>

ECharts に変えた結果

image.png

  • ローソク足・移動平均線・出来高・スライダーをすべて 1 つのチャートに統合
  • 柔軟なレイアウト調整と凡例・タイトルの独立配置
  • グリッドの分割による上段ローソク足、下段出来高の表示

実装コードのハイライト(ECharts)

const option = {
  title: {
    text: `${code} - ${name}`,
    top: 10,
    left: 'center',
  },
  legend: {
    data: ['ローソク足', 'MA5', 'MA25', '出来高'],
    top: 40,
  },
  grid: [
    { top: 70, height: '60%' },
    { top: '75%', height: '15%' },
  ],
  xAxis: [
    { type: 'category', data: dates },
    { type: 'category', data: dates, gridIndex: 1 }
  ],
  yAxis: [
    { scale: true },
    { scale: true, gridIndex: 1 }
  ],
  dataZoom: [
    { type: 'inside' },
    { type: 'slider' },
  ],
  series: [
    { type: 'candlestick', data: ohlcData },
    { type: 'line', name: 'MA5', data: calculateMA(closeData, 5) },
    { type: 'line', name: 'MA25', data: calculateMA(closeData, 25) },
    { type: 'bar', name: '出来高', xAxisIndex: 1, yAxisIndex: 1, data: volumeData },
  ]
};

ハマりポイントと解決策まとめ

課題 解決策
Chart.js で複数軸のチャート作成が難しい ECharts の grid/xAxis/yAxis の配列構成で分離
移動平均線 MA5/MA25 の実装がない calculateMA() 関数で独自に算出して line series へ追加
スクロール・ズーム dataZoom 機能でスライダーとインサイド拡縮対応

以上のようにしてEChartsを利用して作りたいグラフの描画ができました。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?