skka3134

skka3134

email
telegram

机器学习和量化投资:2.处理数据

1. 加载训练的数据

import pandas as pd
data=pd.read_csv('data.csv')

2. 特征工程,我们需要其中的 Time 和 Close

data = data[['Time', 'Close']]

3. 安装 matplotlib

sudo /home/skka3134/folder/bot/bin/python -m pip install matplotlib

4. 使用 matplotlib,根据日期 和收盘价绘制曲线图,matplotlib 是一个 2D 绘图库。

import matplotlib.pyplot as plt
plt.plot(data['Time'],data['Close'])
plt.show()

image
5. 为神经网络 LSTM 准备一个数据框。RNN 是一种使用序列数据或时序数据的人工神经网络。 LSTM 是一种特殊的 RNN,主要是为了解决长序列训练过程中的梯度消失和梯度爆炸问题。

from copy import deepcopy as dc
def prepare_dataframe_for_lstm(df, n_steps):
    df = dc(df)
    
    df.set_index('Time', inplace=True)
    
    for i in range(1, n_steps+1):
        df[f'Close(t-{i})'] = df['Close'].shift(i)
        
    df.dropna(inplace=True)
    
    return df

lookback = 7
shifted_df = prepare_dataframe_for_lstm(data, lookback)

image
6. 将其 转换成 numpy

shifted_df = prepare_dataframe_for_lstm(data, lookback)
shifted_df_as_np = shifted_df.to_numpy()

image
7. 安装 sklearn,我们需要用到 sklearn 里面的 MinMaxScaler 进行数据缩放,减小误差。

sudo /home/skka3134/folder/bot/bin/python -m pip install Scikit-Learn

8. 缩放到 - 1 到 1 之间,再反缩放回去

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(-1, 1))
shifted_df_as_np = scaler.fit_transform(shifted_df_as_np)

image
9. 制作输入 X,和输出 Y

X = shifted_df_as_np[:, 1:]
y = shifted_df_as_np[:, 0]
X = dc(np.flip(X, axis=1))

image
10. 分割 X,用前百分之 95 进行训练,后百分之几 5 进行测试

split_index = int(len(X) * 0.95)

11. 重塑

X_train = X[:split_index]
X_test = X[split_index:]
y_train = y[:split_index]
y_test = y[split_index:]

X_train = X_train.reshape((-1, lookback, 1))
X_test = X_test.reshape((-1, lookback, 1))
y_train = y_train.reshape((-1, 1))
y_test = y_test.reshape((-1, 1))

X_train = torch.tensor(X_train).float()
y_train = torch.tensor(y_train).float()
X_test = torch.tensor(X_test).float()
y_test = torch.tensor(y_test).float()
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。