如何使用Highcharts正确绘制指定API返回的股票数据?
用Highcharts绘制指定股票数据的解决方案
数据格式适配要点
你使用的数据源返回的historical数组中,每个条目包含date、open、high、low、close字段,但Highcharts的股票类图表(如K线、折线图)需要结构化的数组格式:
- K线/OHLC图:
[时间戳, 开盘价, 最高价, 最低价, 收盘价] - 折线图:
[时间戳, 收盘价]
实现步骤与代码
数据转换逻辑
遍历接口返回的历史数据,将日期转为时间戳,同时提取价格字段并转为数值类型:const chartData = rawData.historical.map(item => [ new Date(item.date).getTime(), parseFloat(item.open), parseFloat(item.high), parseFloat(item.low), parseFloat(item.close) ]);完整实现代码
<div id="container" style="height: 400px; min-width: 310px"></div> <script src="https://code.highcharts.com/stock/highstock.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { // 请求数据源 fetch('https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=1920dcbb65f52e51cf4ceb45d64d6bd9') .then(res => res.json()) .then(data => { // 转换为Highcharts兼容格式 const formattedData = data.historical.map(item => [ new Date(item.date).getTime(), +item.open, +item.high, +item.low, +item.close ]); // 初始化K线图 Highcharts.stockChart('container', { title: { text: 'AAPL 历史股价' }, series: [{ name: 'AAPL', data: formattedData, type: 'candlestick', tooltip: { valueDecimals: 2 } }] }); }) .catch(err => console.error('数据加载失败:', err)); }); </script>
关键注意事项
- 必须引入Highstock模块(
highstock.js),它包含股票图表所需的K线、OHLC等组件 - 接口返回的价格是字符串类型,需通过
parseFloat或+号转为数值,否则Highcharts无法识别 - 若需折线图,只需修改
type为line,并将数据简化为[new Date(item.date).getTime(), +item.close]
内容的提问来源于stack exchange,提问作者Bruce Wright
相关产品推荐
相关产品推荐

