我们如何根据Keras LSTM的2个或更多功能来预测股票价格?

发布于 2025-01-25 00:01:38 字数 6245 浏览 1 评论 0原文

我想预测股票未来价格。但是问题在于,当我想根据2个功能(例如,关闭和开放价格)预测未来的关闭价格时,我会出现错误。该代码是:

我的问题是:如何将其他功能(例如开放价格或数量以及其他功能)添加到此代码中,并根据此组合功能进行预测未来的封闭价格? 感谢您的未来帮助! :))

在这里输入代码

#import libraries
import numpy as np
import pandas as pd
import yfinance as yf
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.models import Sequential
from sklearn.preprocessing import MinMaxScaler
pd.options.mode.chained_assignment = None
tf.random.set_seed(0)

# download the data
df = yf.download(tickers=['AAPL'], period='1y')
y = df['Close'].fillna(method='ffill')
y = y.values.reshape(-1, 1)

# scale the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(y)
y = scaler.transform(y)

# generate the input and output sequences
n_lookback = 60  # length of input sequences (lookback period)
n_forecast = 60 # length of output sequences (forecast period)

X = []
Y = []

for i in range(n_lookback, len(y) - n_forecast + 1):
    X.append(y[i - n_lookback: i])
    Y.append(y[i: i + n_forecast])

X = np.array(X)
Y = np.array(Y)

#fit the model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(n_lookback, 1)))
model.add(LSTM(units=50))
model.add(Dense(n_forecast))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, epochs=100, batch_size=32, verbose=0)

# generate the forecasts
X_ = y[- n_lookback:]  # last available input sequence
X_ = X_.reshape(1, n_lookback, 1)

Y_ = model.predict(X_).reshape(-1, 1)
Y_ = scaler.inverse_transform(Y_)

# organize the results in a data frame
df_past = df[['Close']].reset_index()
df_past.rename(columns={'index': 'Date', 'Close': 'Actual'}, inplace=True)
df_past['Date'] = pd.to_datetime(df_past['Date'])
df_past['Forecast'] = np.nan
df_past['Forecast'].iloc[-1] = df_past['Actual'].iloc[-1]

df_future = pd.DataFrame(columns=['Date', 'Actual', 'Forecast'])
df_future['Date'] = pd.date_range(start=df_past['Date'].iloc[-1] + pd.Timedelta(days=1), periods=n_forecast)
df_future['Forecast'] = Y_.flatten()
df_future['Actual'] = np.nan
results = df_past.append(df_future).set_index('Date')

the changes that i apply on the sections of the code there is below:

    enter code here

# download the data
df1 = yf.download(tickers=['AAPL'], period='max',interval='1d')
y1 = df1['Close'].fillna(method='ffill')
y1 = y1.values.reshape(-1, 1)
y2 = df1['Open'].fillna(method='ffill')
y2 = y2.values.reshape(-1, 1)
y3 = [*y1 , *y2]
y1 = df1[['Close','Open']]
y = np.array(y1).T  

i convert the 2 inputs (close & open) to array and get that to y and the output is below:

[*********************100%***********************]  1 of 1 completed

array([[1.28347993e-01, 1.21652000e-01, 1.12723000e-01, ...,
        1.56570007e+02, 1.63639999e+02, 1.57649994e+02],
       [1.28347993e-01, 1.22210003e-01, 1.13280997e-01, ...,
        1.55910004e+02, 1.59250000e+02, 1.61839996e+02]])

the problem is when i want to get merged input to the input of model:
 

    enter code here

#fit the model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(n_lookback, 1)))
model.add(LSTM(units=50))
model.add(Dense(n_forecast))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, epochs=100, batch_size=32, verbose=0)
model.summary()

the error of top section of code is that : 

WARNING:tensorflow:Model was constructed with shape (None, 1, 1) for input KerasTensor(type_spec=TensorSpec(shape=(None, 1, 1), dtype=tf.float32, name='lstm_309_input'), name='lstm_309_input', description="created by layer 'lstm_309_input'"), but it was called on an input with incompatible shape (None, 1, 10434).

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [1594], in <cell line: 7>()
      5 model.add(Dense(n_forecast))
      6 model.compile(loss='mean_squared_error', optimizer='adam')
----> 7 model.fit(X, Y, epochs=100, batch_size=32, verbose=0)
      8 model.summary()

File E:\anaconda\envs\time_series\lib\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File E:\anaconda\envs\time_series\lib\site-packages\tensorflow\python\framework\func_graph.py:1147, in func_graph_from_py_func.<locals>.autograph_handler(*args, **kwargs)
   1145 except Exception as e:  # pylint:disable=broad-except
   1146   if hasattr(e, "ag_error_metadata"):
-> 1147     raise e.ag_error_metadata.to_exception(e)
   1148   else:
   1149     raise

ValueError: in user code:

    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1021, in train_function  *
        return step_function(self, iterator)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1010, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1000, in run_step  **
        outputs = model.train_step(data)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 859, in train_step
        y_pred = self(x, training=True)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Exception encountered when calling layer "sequential_138" (type Sequential).
    
    Input 0 of layer "lstm_309" is incompatible with the layer: expected shape=(None, None, 1), found shape=(None, 1, 10434)
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None, 1, 10434), dtype=float32)
      • training=True
      • mask=None



i want to predict stock future price. but the problem is that when i want predict future close price based on 2 feature (close and open price for example), i get error. the code is this:

my question is that : how can i add other feature (for example, open price or volume and the other) to this code and do forecast future close price based on this combination features?!
thanks for your future help! :))

enter code here

#import libraries
import numpy as np
import pandas as pd
import yfinance as yf
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.models import Sequential
from sklearn.preprocessing import MinMaxScaler
pd.options.mode.chained_assignment = None
tf.random.set_seed(0)

# download the data
df = yf.download(tickers=['AAPL'], period='1y')
y = df['Close'].fillna(method='ffill')
y = y.values.reshape(-1, 1)

# scale the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(y)
y = scaler.transform(y)

# generate the input and output sequences
n_lookback = 60  # length of input sequences (lookback period)
n_forecast = 60 # length of output sequences (forecast period)

X = []
Y = []

for i in range(n_lookback, len(y) - n_forecast + 1):
    X.append(y[i - n_lookback: i])
    Y.append(y[i: i + n_forecast])

X = np.array(X)
Y = np.array(Y)

#fit the model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(n_lookback, 1)))
model.add(LSTM(units=50))
model.add(Dense(n_forecast))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, epochs=100, batch_size=32, verbose=0)

# generate the forecasts
X_ = y[- n_lookback:]  # last available input sequence
X_ = X_.reshape(1, n_lookback, 1)

Y_ = model.predict(X_).reshape(-1, 1)
Y_ = scaler.inverse_transform(Y_)

# organize the results in a data frame
df_past = df[['Close']].reset_index()
df_past.rename(columns={'index': 'Date', 'Close': 'Actual'}, inplace=True)
df_past['Date'] = pd.to_datetime(df_past['Date'])
df_past['Forecast'] = np.nan
df_past['Forecast'].iloc[-1] = df_past['Actual'].iloc[-1]

df_future = pd.DataFrame(columns=['Date', 'Actual', 'Forecast'])
df_future['Date'] = pd.date_range(start=df_past['Date'].iloc[-1] + pd.Timedelta(days=1), periods=n_forecast)
df_future['Forecast'] = Y_.flatten()
df_future['Actual'] = np.nan
results = df_past.append(df_future).set_index('Date')

the changes that i apply on the sections of the code there is below:

    enter code here

# download the data
df1 = yf.download(tickers=['AAPL'], period='max',interval='1d')
y1 = df1['Close'].fillna(method='ffill')
y1 = y1.values.reshape(-1, 1)
y2 = df1['Open'].fillna(method='ffill')
y2 = y2.values.reshape(-1, 1)
y3 = [*y1 , *y2]
y1 = df1[['Close','Open']]
y = np.array(y1).T  

i convert the 2 inputs (close & open) to array and get that to y and the output is below:

[*********************100%***********************]  1 of 1 completed

array([[1.28347993e-01, 1.21652000e-01, 1.12723000e-01, ...,
        1.56570007e+02, 1.63639999e+02, 1.57649994e+02],
       [1.28347993e-01, 1.22210003e-01, 1.13280997e-01, ...,
        1.55910004e+02, 1.59250000e+02, 1.61839996e+02]])

the problem is when i want to get merged input to the input of model:
 

    enter code here

#fit the model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(n_lookback, 1)))
model.add(LSTM(units=50))
model.add(Dense(n_forecast))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, epochs=100, batch_size=32, verbose=0)
model.summary()

the error of top section of code is that : 

WARNING:tensorflow:Model was constructed with shape (None, 1, 1) for input KerasTensor(type_spec=TensorSpec(shape=(None, 1, 1), dtype=tf.float32, name='lstm_309_input'), name='lstm_309_input', description="created by layer 'lstm_309_input'"), but it was called on an input with incompatible shape (None, 1, 10434).

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [1594], in <cell line: 7>()
      5 model.add(Dense(n_forecast))
      6 model.compile(loss='mean_squared_error', optimizer='adam')
----> 7 model.fit(X, Y, epochs=100, batch_size=32, verbose=0)
      8 model.summary()

File E:\anaconda\envs\time_series\lib\site-packages\keras\utils\traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File E:\anaconda\envs\time_series\lib\site-packages\tensorflow\python\framework\func_graph.py:1147, in func_graph_from_py_func.<locals>.autograph_handler(*args, **kwargs)
   1145 except Exception as e:  # pylint:disable=broad-except
   1146   if hasattr(e, "ag_error_metadata"):
-> 1147     raise e.ag_error_metadata.to_exception(e)
   1148   else:
   1149     raise

ValueError: in user code:

    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1021, in train_function  *
        return step_function(self, iterator)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1010, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 1000, in run_step  **
        outputs = model.train_step(data)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\training.py", line 859, in train_step
        y_pred = self(x, training=True)
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "E:\anaconda\envs\time_series\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility
        raise ValueError(f'Input {input_index} of layer "{layer_name}" is '

    ValueError: Exception encountered when calling layer "sequential_138" (type Sequential).
    
    Input 0 of layer "lstm_309" is incompatible with the layer: expected shape=(None, None, 1), found shape=(None, 1, 10434)
    
    Call arguments received:
      • inputs=tf.Tensor(shape=(None, 1, 10434), dtype=float32)
      • training=True
      • mask=None



如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文