You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:如何在Jupyter中用Chart.from_pandas绘制Highcharts Stock蜡烛图及成交量图

用Highcharts Stock的Chart.from_pandas绘制蜡烛图+成交量的Jupyter示例

原代码问题说明

你的代码存在几个关键问题:

  • 未导入CandlestickSeries类型,导致series_type= Candlestick报错
  • 你的DataFrame日期是索引而非列,property_map中'date': 'Date'无效,需用use_index_as_date=True替代
  • Chart.from_pandas默认生成单个系列,要实现蜡烛图+成交量需手动添加第二个系列
  • 未配置双Y轴,无法同时展示价格和成交量数据

完整可运行示例代码

from highcharts_stock.chart import Chart
from highcharts_stock.options.series.candlestick import CandlestickSeries
from highcharts_stock.options.series.bar import BarSeries
import yfinance as yf
import pandas as pd

# 获取TSLA一年历史数据
tsla = yf.Ticker('TSLA')
df = tsla.history(period="1y")

# 1. 创建蜡烛图系列
candlestick_series = CandlestickSeries.from_pandas(
    df,
    property_map={
        'open': 'Open',
        'high': 'High',
        'low': 'Low',
        'close': 'Close'
    },
    use_index_as_date=True,  # 将DataFrame的Datetime索引作为日期轴
    name='TSLA Price'
)

# 2. 创建成交量柱状图系列
volume_series = BarSeries.from_pandas(
    df,
    property_map={
        'y': 'Volume'
    },
    use_index_as_date=True,
    name='Volume',
    y_axis=1  # 指定使用第二个Y轴
)

# 3. 配置图表全局选项
chart_options = {
    'title': {
        'text': 'TSLA 1-Year Price & Volume'
    },
    'y_axis': [
        {
            'title': {
                'text': 'Price'
            },
            'height': '70%',
            'line_width': 2
        },
        {
            'title': {
                'text': 'Volume'
            },
            'top': '75%',
            'height': '25%',
            'offset': 0,
            'line_width': 2
        }
    ],
    'range_selector': {
        'selected': 5  # 默认选中"1Y"范围
    },
    'navigator': {
        'enabled': True
    }
}

# 4. 初始化图表并添加两个系列
my_chart = Chart(
    options=chart_options,
    container='my_target_div'
)
my_chart.add_series(candlestick_series)
my_chart.add_series(volume_series)

# 在Jupyter中展示图表
my_chart.display()

关键配置说明

  • 系列创建:分别用CandlestickSeries.from_pandas和BarSeries.from_pandas生成两个系列,通过use_index_as_date=True利用DataFrame的Datetime索引作为时间轴
  • 双Y轴配置:第一个Y轴用于价格(占70%高度),第二个Y轴用于成交量(占25%高度,位于下方),通过y_axis=1指定成交量系列使用第二个轴
  • 股票组件:启用range_selector(范围选择器)和navigator(导航器),匹配官网示例的交互体验
  • 字段映射:蜡烛图映射Open/High/Low/Close字段,成交量直接映射Volume为Y值

内容的提问来源于stack exchange,提问作者Luthor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 21:50:19