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

Django集成yfinance及Plotly问题求助:股票数据与图表生成

依赖包安装方法

直接在项目的虚拟环境中执行以下命令安装所需依赖:

pip install yfinance plotly

若你的Django项目使用requirements.txt管理依赖,可添加以下内容:

yfinance>=0.2.31
plotly>=5.18.0
原代码错误分析与修复
  1. 变量名错误:第一个代码片段中return HttpResponse(room)里的room未定义,实际应返回定义好的stock变量。
  2. 库过时问题:yahoo_finance库已停止维护,官方推荐使用yfinance替代,直接弃用旧库即可。
Django中股票图表实现方案

1. 视图函数编写

在对应app的views.py中编写处理请求的视图,接收用户输入的股票代码,生成图表HTML并传递给模板:

from django.shortcuts import render
import yfinance as yf
import plotly.graph_objects as go

def stock_chart(request):
    chart_html = ""
    error_message = ""
    if request.method == "POST":
        stock_code = request.POST.get("stock_code", "").strip().upper()
        if stock_code:
            try:
                # 获取股票历史数据
                ticker = yf.Ticker(stock_code)
                hist = ticker.history(period="1y")
                if hist.empty:
                    error_message = "未找到该股票代码的数据,请检查输入"
                else:
                    # 生成Plotly图表
                    fig = go.Figure(data=go.Scatter(x=hist.index, y=hist.Close, mode="lines", name=stock_code))
                    fig.update_layout(title=f"{stock_code} 近一年收盘价走势", xaxis_title="日期", yaxis_title="收盘价(USD)")
                    # 转换为HTML片段,使用CDN加载Plotly JS
                    chart_html = fig.to_html(include_plotlyjs="cdn", full_html=False)
            except Exception as e:
                error_message = f"获取数据失败:{str(e)}"
    return render(request, "stock_chart.html", {"chart_html": chart_html, "error_message": error_message})

2. 模板文件创建

在app的templates目录下创建stock_chart.html,包含表单和图表展示区域:

<!DOCTYPE html>
<html>
<head>
    <title>股票走势图表</title>
</head>
<body>
    <h1>股票走势查询</h1>
    <form method="post">
        {% csrf_token %}
        <input type="text" name="stock_code" placeholder="输入股票代码(如AAPL)" required>
        <button type="submit">生成图表</button>
    </form>
    {% if error_message %}
        <p style="color: red;">{{ error_message }}</p>
    {% endif %}
    {% if chart_html %}
        <div>{{ chart_html|safe }}</div>
    {% endif %}
</body>
</html>

3. URL配置

在app的urls.py中添加对应路由:

from django.urls import path
from . import views

urlpatterns = [
    path("stock-chart/", views.stock_chart, name="stock_chart"),
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:50:39