使用 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, ))
scaled_data = scaler.fit_transform(data[].values.reshape(-, ))
x, y = [], []
i (look_back, (scaled_data)):
x.append(scaled_data[i-look_back:i])
y.append(scaled_data[i])
np.array(x), np.array(y), scaler
():
model = Sequential()
model.add(LSTM(units=, return_sequences=, input_shape=input_shape))
model.add(Dropout())
model.add(LSTM(units=))
model.add(Dropout())
model.add(Dense(units=))
model.add(Dense(units=))
model.(optimizer=, loss=)
model
():
:
df = load_data(ticker)
df.empty:
, ,
x, y, scaler = preprocess_data(df)
(x) < :
, ,
model = build_model((x.shape[], ))
model.fit(x, y, epochs=, batch_size=, verbose=)
last_days = x[-:]
pred_scaled = model.predict(last_days)
pred_price = scaler.inverse_transform(pred_scaled)[][]
history = df[].tail().values
future_dates = pd.date_range(start=df.index[-], periods=, freq=)
predictions = [pred_price]
history, predictions, future_dates
Exception e:
st.error()
, ,
ticker = st.sidebar.text_input(, value=)
st.button():
history, predictions, future_dates = run_prediction(ticker)
history :
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=))
st.plotly_chart(fig)
st.write()
:
st.warning()


