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

如何将HTML文本框中的Ticker传入Python机器学习模型

实现HTML网页向Python机器学习模型传递股票代码的简单方案

你需要搭建一个前后端交互的基础流程:前端收集用户输入的股票代码,通过请求发送给Python后端,后端调用你的机器学习模型处理后返回结果。下面是最简洁的实现方案:


1. 修改前端HTML(添加交互逻辑)

在原有HTML基础上,增加JavaScript监听按钮点击事件,发送请求到后端并展示结果:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>Stock Prediction</title>
    </head>
    <body>
    <h1>Stock Prediction</h1>
    <textarea placeholder="Enter ticker here..." id="text"></textarea>
    <button id="submit" type="submit">Go</button>
    <!-- 用于展示预测结果的区域 -->
    <div id="result"></div>

    <script>
        // 获取页面元素
        const submitBtn = document.getElementById('submit');
        const tickerInput = document.getElementById('text');
        const resultDiv = document.getElementById('result');

        // 监听按钮点击事件
        submitBtn.addEventListener('click', async () => {
            const ticker = tickerInput.value.trim();
            if (!ticker) {
                resultDiv.textContent = '请输入有效的股票代码';
                return;
            }

            try {
                // 发送请求到后端接口
                const response = await fetch('/predict', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ ticker: ticker }),
                });

                const data = await response.json();
                // 展示结果
                if (data.success) {
                    resultDiv.textContent = `${ticker} 的预测股价: ${data.prediction}`;
                } else {
                    resultDiv.textContent = data.error;
                }
            } catch (error) {
                resultDiv.textContent = '请求出错,请检查后端是否正常运行';
            }
        });
    </script>
    </body>
</html>

2. 补充CSS(新增结果区域样式)

在原有CSS基础上,添加结果展示区域的样式:

#text {
    display: block;
    width: 50%;
    background-color: transparent;
    color: #021652;
    border: 2px solid #3ba9f4;
    border-radius: 2px;
    resize: none;
    margin-bottom: 35px;
    height: 50px;
    padding: 10px;
    font-size: 20px;
  }

#submit {
  background-color: #3ba9f4;
  color: #fff;
  font-size: 20px;
  height: 50px;
  border: none;
  border-radius: 2px;
  width: 174px;
  cursor: pointer;
  }

#result {
  margin-top: 20px;
  font-size: 20px;
  color: #021652;
}

3. 搭建Python后端(Flask)

用轻量的Flask框架接收前端请求,调用你的机器学习模型:

步骤1:安装依赖

执行命令安装所需库:

pip install flask flask-cors

步骤2:创建后端文件app.py

from flask import Flask, request, jsonify
from flask_cors import CORS

# 替换成你实际的机器学习模型预测函数
def predict_stock_price(ticker):
    # 这里只是模拟返回结果,你需要替换为加载模型、处理数据、输出预测值的逻辑
    # 示例:根据ticker获取历史数据,传入模型计算预测股价
    return 185.6  # 模拟AAPL的预测股价

app = Flask(__name__)
CORS(app)  # 解决跨域请求问题

@app.route('/predict', methods=['POST'])
def predict():
    try:
        data = request.get_json()
        ticker = data.get('ticker', '').upper()
        
        if not ticker:
            return jsonify({'success': False, 'error': '股票代码不能为空'})
        
        # 调用模型获取预测结果
        prediction_result = predict_stock_price(ticker)
        
        return jsonify({'success': True, 'prediction': prediction_result})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

if __name__ == '__main__':
    app.run(debug=True)

4. 运行测试

  1. 将index.html、style.css、app.py放在同一个文件夹下
  2. 运行后端:python app.py
  3. 打开浏览器访问http://127.0.0.1:5000,输入股票代码点击「Go」即可触发预测

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:25:41