使用 GPT 4o with Canvas 构建金融预测 Streamlit 应用
ChatGPT 今年发布了多个模型,其中 GPT 4o 结合 Canvas 功能为开发者提供了强大的辅助编程能力。本文将探索如何利用 GPT 4o with Canvas 快速构建一个预测股票价格的 Streamlit Web 应用。
什么是 Streamlit?
Streamlit 是一种极其有用且快速的方法,可以在几分钟内构建你的 Web 应用。它允许数据科学家和开发人员仅使用 Python 代码即可创建交互式组件(如按钮、滑块和文本输入),无需复杂的 Web 开发知识。这使得它成为展示模型或交互式探索数据集的首选工具。
项目准备
首先,我们需要准备开发环境。确保已安装 Python 3.x,并创建一个新的 GitHub 仓库用于托管代码。
依赖安装
创建一个 requirements.txt 文件,包含以下依赖:
streamlit
yfinance
pandas
numpy
scikit-learn
tensorflow
plotly
核心代码实现
使用 GPT 4o with Canvas 可以生成大部分逻辑代码。以下是完整的 app.py 实现,集成了数据获取、LSTM 模型训练及可视化界面。
import streamlit as st
import yfinance as yf
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
import datetime
import plotly.graph_objects as go
st.title('金融股票价格预测')
st.sidebar.header('用户参数')
def load_data(ticker):
end = datetime.datetime.now()
start = datetime.datetime(end.year - 1, end.month, end.day)
data = yf.download(ticker, start=start, end=end)
return data
def preprocess_data(data, look_back=60):
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
x, y = [], []
for i in range(look_back, len(scaled_data)):
x.append(scaled_data[i-look_back:i])
y.append(scaled_data[i])
return np.array(x), np.array(y), scaler
def build_model(input_shape):
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=25))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
return model
@st.cache_data
def run_prediction(ticker):
try:
df = load_data(ticker)
if df.empty:
return None, None, None
x, y, scaler = preprocess_data(df)
if len(x) < 10:
return None, None, None
model = build_model((x.shape[1], 1))
model.fit(x, y, epochs=10, batch_size=32, verbose=0)
last_days = x[-1:]
pred_scaled = model.predict(last_days)
pred_price = scaler.inverse_transform(pred_scaled)[0][0]
history = df['Close'].tail(60).values
future_dates = pd.date_range(start=df.index[-1], periods=7, freq='D')
predictions = [pred_price]
return history, predictions, future_dates
except Exception as e:
st.error(f"发生错误:{e}")
return None, None, None
ticker = st.sidebar.text_input("股票代码", value="AAPL")
if st.button("开始预测"):
history, predictions, future_dates = run_prediction(ticker)
if history is not None:
fig = go.Figure()
fig.add_trace(go.Scatter(x=pd.to_datetime(history.index), y=history, name='历史价格'))
fig.add_trace(go.Scatter(x=future_dates, y=predictions, name='预测价格', mode='lines+markers'))
st.plotly_chart(fig)
st.write(f"预测下一周价格约为:${predictions[0]:.2f}")
else:
st.warning("无法获取数据或处理失败,请检查股票代码。")
运行与部署
本地测试
保存上述代码为 app.py,并在终端运行:
streamlit run app.py
浏览器将自动打开应用界面。
云端部署
- 将代码上传至 GitHub 公共仓库。
- 登录 Streamlit Cloud,选择'New App'。
- 连接 GitHub 仓库并指定
app.py作为入口文件。 - 点击部署,应用将在几分钟后上线。
总结
利用 GPT 4o with Canvas 能够显著降低开发门槛,快速生成高质量的数据科学应用原型。通过本教程,我们实现了从数据获取到模型预测的全流程自动化,展示了 AI 编程助手在实际金融场景中的应用潜力。


