在Flask中通过表单获取股票ID调用Alpha Vantage API获取金融数据
基于Alpha Vantage API获取股票金融数据实现
需求概述
通过Alpha Vantage API,根据用户输入的股票ID(如股票代码)获取对应公司的金融数据。用户在home.html的表单中提交股票ID,由后端views.py处理API请求、获取数据并返回至页面展示。
HTML表单实现(home.html)
<form method="post"> <label for="company_id">输入公司股票ID(例如:股票代码):</label> <input type="text" name="stock_id" id="sys" placeholder="例如:AAPL"> <button type="submit">获取股票数据</button> </form>
Python后端处理(views.py)
from flask import request, render_template import requests import pandas as pd @views.route('/home', methods=['GET', 'POST']) def get_stock_data(): symbol = request.form.get('stock_id') # 替换为你的Alpha Vantage API密钥 api_key = 'hidden' # 数据时间间隔,这里设为60分钟 interval = '60min' # 返回数据量:'compact'返回最近100条,'full'返回全部历史数据 outputsize = 'compact' url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval={interval}&outputsize={outputsize}&apikey={api_key}' # 发送API请求 response = requests.get(url) # 解析JSON响应 data = response.json() # 提取时间序列数据 time_series_key = f'Time Series ({interval})' time_series = data.get(time_series_key) # 处理数据缺失或请求失败的情况 if not time_series: return render_template("home.html", error="无法获取股票数据,请检查股票代码或API密钥") # 转换为DataFrame并转置,以时间戳为索引 df = pd.DataFrame(time_series).T # 将收盘价字段转为数值类型 df['4. close'] = pd.to_numeric(df['4. close']) # 返回模板并传递数据 return render_template("home.html", symbol=symbol, stock_data=df)
实用提示
- 先安装依赖库:执行
pip install flask requests pandas - 需前往Alpha Vantage平台申请个人API密钥,替换代码中的
'hidden' - 建议补充网络请求异常、JSON解析错误等处理逻辑,提升程序稳定性
- 需在
home.html中添加数据展示模块,比如通过模板语法遍历stock_data渲染表格
内容的提问来源于stack exchange,提问作者Cruel
相关产品推荐
相关产品推荐

