아빠는 개발자

[tf2]tensorflow2 LSTM 주가예측 본문

카테고리 없음

[tf2]tensorflow2 LSTM 주가예측

father6019 2024. 4. 7. 19:48
728x90
반응형

내가 .. 물려있는 테슬라 LSTM 으로 주가 예측을 해서 탈출해보자 

tensorflow 1 버전으로 작업된 내용이 있긴하다. 

 

내 PC에 깔린게 2다 보니..

 

테슬라의 주가는  야후 finance 에서  historical Data 에서 받으면 된다. 

 

날짜 범위를 Max 로 넣고 

 

 

다운로드 

 

 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout

# Load your stock price data
# Assuming you have a CSV file with a column 'Close' representing the closing prices
data = pd.read_csv('TSLA2.csv')

# Preprocess the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))

# Create training data
seq_len = 60  # Sequence length, you can adjust this according to your choice
X = []
y = []
for i in range(seq_len, len(scaled_data)):
    X.append(scaled_data[i - seq_len:i, 0])
    y.append(scaled_data[i, 0])
X, y = np.array(X), np.array(y)

# Reshape the data for LSTM
X = np.reshape(X, (X.shape[0], X.shape[1], 1))

# Split the data into training and testing sets
split = int(0.8 * len(X))
X_train, X_test, y_train, y_test = X[:split], X[split:], y[:split], y[split:]

# Build the LSTM model
model = Sequential([
    LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
    Dropout(0.2),
    LSTM(units=50, return_sequences=True),
    Dropout(0.2),
    LSTM(units=50),
    Dropout(0.2),
    Dense(units=1)
])

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

# Train the model
model.fit(X_train, y_train, epochs=10, batch_size=32)

# Evaluate the model
loss = model.evaluate(X_test, y_test)
print(f'Test Loss: {loss}')

# Make predictions
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)

# Plot the results
plt.figure(figsize=(14, 7))
plt.plot(data.index[split + seq_len:], data['Close'][split + seq_len:], color='blue', label='Actual Stock Price')
plt.plot(data.index[split + seq_len:], predictions, color='red', label='Predicted Stock Price')
plt.title('Stock Price Prediction')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.legend()
plt.show()

 

 

크..

 

미래예측은 불가능하다고 하는데 

이... 새키..

728x90
반응형