![[特殊字符] 股价时间序列预测数据分析项目任务书](http://pic.xiahunao.cn/yaotu/[特殊字符] 股价时间序列预测数据分析项目任务书)
#### 项目背景 本项目是股价时间序列预测分析项目。将使用某股票的历史数据股价数据.xlsx通过数据探查、预处理、可视化探索以及建模分析挖掘股价波动规律并构建预测模型。 ------ #### ️ 项目环境与数据准备 - **开发工具** Python 3.x (推荐使用 Jupyter Notebook) - **核心库** pandas, numpy, matplotlib, sklearn - **数据集** 股价数据.xlsx - **数据说明** 数据包含日期、开盘价、最高价、最低价、收盘价、成交 #### 项目全流程阶段任务拆解 **阶段 1需求明确与数据探查 ** - 具体要求 1. 导入必要的库pandas, numpy, matplotlib # 导入所需工具库 # 数据分析库 import pandas as pd import numpy # 绘图库 import matplotlib.pyplot as plt # 忽略无关警告机房运行更清爽 import warnings warnings.filterwarnings(ignore) # 设置中文显示重点机房必加 # 解决图表中文乱码、负号不显示问题 plt.rcParams[font.family] SimHei # 中文字体 plt.rcParams[axes.unicode_minus] False # 读取Excel股价数据 # 数据文件和代码同文件夹直接写文件名 df pd.read_excel(rC:\Users\Administrator\Downloads\股价数据.xlsx, engineopenpyxl) # 基础数据查看 print( 1. 数据前5行 ) print(df.head()) print(\n 2. 数据总行数、总列数 ) print(数据形状, df.shape) print(\n 3. 每列数据类型 ) print(df.dtypes) print(\n 4. 缺失值统计 ) # isnull() 判断空值sum() 统计每列空值数量 print(df.isnull().sum()) - 1. 读取 股价数据.xlsx 数据文件。 2. 查看数据的基本信息数据类型、非空值数量。 3. 查看数据的前5行确认数据加载是否成功。 4. 检查缺失值情况并统计数据总条数。 - 难点解析 - **中文显示问题** 在绘图时需设置 plt.rcParams[font.family] SimHei 和 plt.rcParams[axes.unicode_minus] False 来解决中文乱码和负号显示问题。 - **数据质量** 需确认数据中是否存在缺失值或异常值这直接影响后续分析。 **阶段 2数据预处理与特征工程 ** - 具体要求 1. 将 date 列转换为标准的 datetime 时间格式。 2. 按时间从早到晚对数据进行排序原始数据可能是倒序的。 3. 保留核心分析字段date, open, close, high, low, volume, p_change, ma5, ma10, ma2Up20。 4. 重置索引确保数据整洁。 - 难点解析 - **时间排序** 股票数据通常按时间倒序排列需使用 sort_values 进行反转确保时间序列的连续性。 - **特征选择** 需理解各字段含义剔除冗余字段如 price_change保留对预测有帮助的均线特征。 **阶段 3探索性数据分析EDA与可视化 ** - 具体要求 1. **股价与均线走势** 绘制收盘价与5日、10日、20日均线的走势折线图。 2. **成交量分析** 绘制成交量随时间变化的柱状图。 3. **涨跌幅分布** 绘制涨跌幅p_change的直方图分析波动分布规律。 - 难点解析 - **双轴绘图** 股价和成交量量级差异巨大绘制在同一图中需使用双Y轴twinx。 - **规律挖掘** 观察均线与股价的关系如“金叉”、“死叉”分析成交量放大时的股价表现。 **阶段 4时间序列模型构建** - 具体要求 1. **数据标准化** 由于各特征量纲不同需使用 StandardScaler 对数据进行标准化处理。 2. **构建监督学习数据集** 将时间序列数据转换为监督学习格式即用前N天的数据预测第N1天的收盘价。 3. **划分数据集** 将数据划分为训练集前80%和测试集后20%。 4. **模型训练** 使用线性回归模型进行训练。 - 难点解析 - **时间步长Timesteps** 需确定使用过去多少天的数据来预测未来通常设置为 60 或 30。 - **数据重塑** LSTM 模型要求输入数据为 3D 张量samples, timesteps, features需使用 reshape 进行转换。 # 1. 将日期列转为时间格式 df[date] pd.to_datetime(df[date]) # 2. 按时间从小到大排序 df df.sort_values(bydate, ascendingTrue) # 先打印所有列名核对字段 print(表格现有全部列, df.columns.tolist()) # 3. 保留需要的字段删除无用列 # 方案2直接去掉不存在的ma2Up20避免报错 need_cols [date, open, close, high, low, volume, p_change, ma5, ma10] df df[need_cols] # 4. 重置行索引 df df.reset_index(dropTrue) print( 预处理完成查看前10行数据 ) print(df.head(10)) # 3. 计算均线解决ma20不存在报错 df[ma5] df[close].rolling(5).mean() df[ma10] df[close].rolling(10).mean() df[ma20] df[close].rolling(20).mean() # 4. 绘图代码你原来的代码 plt.rcParams[font.sans-serif] [SimHei] plt.rcParams[axes.unicode_minus] False plt.figure(figsize(14,6)) plt.plot(df[date],df[close],label收盘价) plt.plot(df[date],df[ma5],label5日均线,linestyle--) plt.plot(df[date],df[ma10],label10日均线,linestyle--) plt.plot(df[date],df[ma20],label20日均线,linestyle--) plt.legend() plt.title(收盘价与均线) plt.grid(alpha0.3) plt.xticks(rotation45) # 防止日期重叠 plt.show() #绘制K-线图 from pyecharts.charts import Kline from pyecharts import options as opts ydf[[open,close,high,low]].values.tolist() kline( Kline() .add_xaxis(df[date].tolist()) .add_yaxis(K线图,y) .set_global_opts( title_optsopts.TitleOpts(titleK线图), toolbox_optsopts.ToolboxOpts(is_showTrue) ) ) kline.render_notebook() #2.绘制成交量柱状图 plt.figure(figsize(14,6)) plt.bar(df[date],df[volume]) #plt.plot(df[date],df[volume],colorred) plt.title(成交量柱状图) plt.show() # 构造滞后特征用前1天收盘价预测当天时间序列常用特征 df[close_lag1] df[close].shift(1) # 去除空值 df df.dropna() # 划分前80%训练后20%测试 split int(len(df) * 0.8) train df.iloc[:split] test df.iloc[split:] # 特征与标签用前一日收盘价、开盘价、均线预测当日收盘价 feature_cols [close_lag1, open, ma5] X_train train[feature_cols] y_train train[close] X_test test[feature_cols] y_test test[close] print(f训练集: {len(train)} 条 | 测试集: {len(test)} 条) from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score import numpy as np # 训练模型 lr LinearRegression() # 线性回归模型 lr.fit(X_train, y_train) # 训练模型 # 预测 y_pred_lr lr.predict(X_test) # 模型评估 def eval_model(y_true, y_pred): mae mean_absolute_error(y_true, y_pred) # 平均绝对误差 rmse np.sqrt(mean_squared_error(y_true, y_pred)) # 均方根误差 r2 r2_score(y_true, y_pred) # R²(拟合度) print(fMAE(平均绝对误差): {mae:.2f}) print(fRMSE(均方根误差): {rmse:.2f}) print(fR²(拟合度): {r2:.2f}) print( 线性回归模型评估 ) eval_model(y_test, y_pred_lr) # 可视化真实值 vs 预测值 plt.figure(figsize(14, 6)) plt.plot(test[date], y_test, label真实收盘价, linewidth2) plt.plot(test[date], y_pred_lr, label线性回归预测, linestyle--) plt.title(线性回归预测结果) plt.xlabel(日期) plt.ylabel(股价) plt.legend() plt.grid(alpha0.3) plt.show() from statsmodels.tsa.arima.model import ARIMA import numpy as np # 1. 初始化列表存储预测结果 history list(train[close]) predictions [] # 2. 滚动预测每次只预测1步然后把真实值加入模型 for i in range(len(test)): model ARIMA(history, order(10,1,0)) # 创建按历史数据训练的ARIMA模型 model_fit model.fit() # 训练模型 yhat model_fit.forecast()[0] # 预测1步 predictions.append(yhat) # 存储预测结果 # 把真实值加入历史数据让模型看到最新数据 history.append(test[close].iloc[i]) # 加入最新真实值 # 3. 转换为数组得到测试集全部预测结果 y_pred_arima np.array(predictions) print(\n ARIMA模型评估 ) eval_model(y_test, y_pred_arima) # 1. 两个模型同图对比 plt.figure(figsize(15, 6)) plt.plot(test[date], y_test, label真实收盘价, linewidth2) plt.plot(test[date], y_pred_lr, label线性回归, linestyle--) plt.plot(test[date], y_pred_arima, labelARIMA, linestyle--, colorred) plt.title(双模型预测效果对比) plt.legend() plt.grid(alpha0.3) plt.show() # 2. 用ARIMA预测未来10个交易日 full_series df[close] final_arima ARIMA(full_series, order(5,1,0)).fit() # 训练ARIMA模型 future_pred final_arima.get_forecast(steps10).predicted_mean # 预测未来10个交易日 print(\n 未来10个交易日预测收盘价 ) for i, val in enumerate(future_pred, 1): print(f第{i}天预测股价: {val:.2f} 元) # 1. 两个模型同图对比 plt.figure(figsize(15, 6)) plt.plot(test[date], y_test, label真实收盘价, linewidth2) plt.plot(test[date], y_pred_lr, label线性回归, linestyle--) plt.plot(test[date], y_pred_arima, labelARIMA, linestyle--, colorred) plt.title(双模型预测效果对比) plt.legend() plt.grid(alpha0.3) plt.show() # 2. 用ARIMA预测未来10个交易日 full_series df[close] final_arima ARIMA(full_series, order(5,1,0)).fit() # 训练ARIMA模型 future_pred final_arima.get_forecast(steps10).predicted_mean # 预测未来10个交易日的收盘价 print(\n 未来10个交易日预测收盘价 ) for i, val in enumerate(future_pred, 1): print(f第{i}天预测股价{val:.2f} 元)