简单的基于LSTM的股市分析与预测(Python)
简单的基于LSTM的股市分析与预测(Python)
简单的基于LSTM的股市分析与预测(Python)
哥廷根数学学派 关注他
与现代信号处理,机器学习,深度学习,故障诊断那些事
3 人赞同了该文章
import pandas as pd
import numpy as np
yf.pdr_override()
https://zhuanlan.zhihu.com/p/712662485 1/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
end = datetime.now()
start = datetime(end.year - 1, end.month, end.day)
df = pd.concat(company_list, axis=0)
df.tail(10)
[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
# Summary Stats
AAPL.describe()
https://zhuanlan.zhihu.com/p/712662485 2/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# General info
AAPL.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 252 entries, 2023-06-05 to 2024-06-04
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Open 252 non-null float64
1 High 252 non-null float64
2 Low 252 non-null float64
3 Close 252 non-null float64
4 Adj Close 252 non-null float64
5 Volume 252 non-null int64
6 company_name 252 non-null object
dtypes : float64(5), int64(1), object(1)
memory usage: 15.8+ KB
# Let's see a historical view of the closing price
plt.figure(figsize=(15, 10))
plt.subplots_adjust(top=1.25, bottom=1.2)
plt.tight_layout()
https://zhuanlan.zhihu.com/p/712662485 3/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# Now let's plot the total volume of stock being traded each day
plt.figure(figsize=(15, 10))
plt.subplots_adjust(top=1.25, bottom=1.2)
plt.tight_layout ()
for ma in ma_day:
https://zhuanlan.zhihu.com/p/712662485 4/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
for company in company_list:
column_name = f"MA for {ma} days"
company[column_name] = company['Adj Close'].rolling(ma).mean()
AAPL[['Adj Close', 'MA for 10 days', 'MA for 20 days', 'MA for 50 days']].plot(
axes[0,0].set_title('APPLE')
GOOG[['Adj Close', 'MA for 10 days', 'MA for 20 days', 'MA for 50 days']].plot(
axes[0,1].set_title('GOOGLE')
MSFT[['Adj Close', 'MA for 10 days', 'MA for 20 days', 'MA for 50 days']].plot(
axes[1,0].set_title('MICROSOFT')
AMZN[['Adj Close', 'MA for 10 days', 'MA for 20 days', 'MA for 50 days']].plot(
axes[1,1].set_title('AMAZON')
fig.tight_layout()
# We'll use pct_change to find the percent change for each day
for company in company_list:
company['Daily Return'] = company['Adj Close'].pct_change()
https://zhuanlan.zhihu.com/p/712662485 5/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
AAPL['Daily Return'].plot(ax=axes[0,0], legend=True, linestyle='--', marker='o
axes[0,0].set_title('APPLE')
fig.tight_layout()
plt.figure(figsize=(12, 9))
plt.tight_layout()
https://zhuanlan.zhihu.com/p/712662485 6/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# Grab all the closing prices for the tech stock list into one DataFrame
https://zhuanlan.zhihu.com/p/712662485 7/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# We'll use joinplot to compare the daily returns of Google and Microsoft
sns.jointplot(x='GOOG', y='MSFT', data=tech_rets, kind='scatter')
https://zhuanlan.zhihu.com/p/712662485 8/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# We can simply call pairplot on our DataFrame for an automatic visual analysis
# of all the comparisons
sns.pairplot(tech_rets, kind='reg')
# Using map_upper we can specify what the upper triangle will look like.
return_fig.map_upper(plt.scatter, color='purple')
# We can also define the lower triangle in the figure, inclufing the plot type
# or the color map (BluePurple)
return_fig.map_lower(sns.kdeplot, cmap='cool_d')
# Finally we'll define the diagonal as a series of histogram plots of the daily
return_fig.map_diag(plt.hist, bins=30)
https://zhuanlan.zhihu.com/p/712662485 9/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
# Using map_upper we can specify what the upper triangle will look like.
returns_fig.map_upper(plt.scatter,color='purple')
# We can also define the lower triangle in the figure, inclufing the plot type
returns_fig.map_lower(sns.kdeplot ,cmap='cool_d')
# Finally we'll define the diagonal as a series of histogram plots of the daily
returns_fig.map_diag(plt.hist,bins=30)
https://zhuanlan.zhihu.com/p/712662485 10/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
plt.figure(figsize=(12, 10))
plt.subplot(2, 2, 1)
sns.heatmap(tech_rets.corr(), annot=True, cmap='summer')
plt.title('Correlation of stock return')
plt.subplot(2, 2, 2)
sns.heatmap(closing_df.corr(), annot=True, cmap='summer')
plt.title('Correlation of stock closing price')
rets = tech_rets.dropna()
https://zhuanlan.zhihu.com/p/712662485 11/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
area = np.pi * 20
plt.figure(figsize=(10, 8))
plt.scatter(rets.mean(), rets.std(), s=area)
plt.xlabel('Expected return')
plt.ylabel('Risk')
https://zhuanlan.zhihu.com/p/712662485 12/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
plt.figure(figsize=(16,6))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
training_data_len
2969
# Scale the data
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
scaled_data
https://zhuanlan.zhihu.com/p/712662485 13/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
array([[0.00401431],
[0.00444289],
[0.00533302],
...,
[0.96818027],
[0.97784564],
[0.98387293]])
# Create the training data set
# Create the scaled training data set
train_data = scaled_data[0:int(training_data_len), :]
# Split the data into x_train and y_train data sets
x_train = []
y_train = []
https://zhuanlan.zhihu.com/p/712662485 14/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
https://zhuanlan.zhihu.com/p/712662485 15/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
知乎学术咨询:https://www.zhihu.com/consult/people/792359672131756032?isMe=1
赞同 3 添加评论 分享 喜欢 收藏 申请转载
https://zhuanlan.zhihu.com/p/712662485 16/17
2025/1/19 03:08 简单的基于LSTM的股市分析与预测(Python) - 知乎
评论区已关闭
推荐阅读
量化
前言
理了
是用
个人
数据科学 | Seaborn + Pandas 从零入门量化交易系列-数据可 利用python进行时间序列分析 的pl
plot
带你玩转股市数据可视化分析 视化库Matplotlib详解 ——季节性ARIMA
运筹OR帷... 发表于『运筹AI... wang ... 发表于从零入门量... Eureka 雁陎
https://zhuanlan.zhihu.com/p/712662485 17/17