Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Step 1: Install Required Libraries
|
2 |
+
# Uncomment and run this if you haven't installed these packages yet.
|
3 |
+
# !pip install pandas numpy matplotlib yfinance tensorflow scikit-learn
|
4 |
+
|
5 |
+
# Step 2: Import Required Libraries
|
6 |
+
import pandas as pd
|
7 |
+
import numpy as np
|
8 |
+
import matplotlib.pyplot as plt
|
9 |
+
import yfinance as yf
|
10 |
+
from sklearn.preprocessing import MinMaxScaler
|
11 |
+
from tensorflow.keras.models import Sequential
|
12 |
+
from tensorflow.keras.layers import LSTM, Dense, Dropout
|
13 |
+
from datetime import datetime, timedelta
|
14 |
+
|
15 |
+
# Step 3: Load and Preprocess Data
|
16 |
+
def load_data(ticker, start_date, end_date):
|
17 |
+
# Fetch data from Yahoo Finance
|
18 |
+
data = yf.download(ticker, start=start_date, end=end_date)
|
19 |
+
data = data[['Close']] # We only need the closing prices
|
20 |
+
return data
|
21 |
+
|
22 |
+
def preprocess_data(data):
|
23 |
+
# Scale the data
|
24 |
+
scaler = MinMaxScaler(feature_range=(0, 1))
|
25 |
+
scaled_data = scaler.fit_transform(data)
|
26 |
+
|
27 |
+
# Create training data
|
28 |
+
training_data_len = int(np.ceil(len(scaled_data) * .8)) # 80% for training
|
29 |
+
train_data = scaled_data[0:training_data_len, :]
|
30 |
+
|
31 |
+
# Create the dataset with X_train and y_train
|
32 |
+
x_train, y_train = [], []
|
33 |
+
for i in range(60, len(train_data)):
|
34 |
+
x_train.append(train_data[i-60:i, 0])
|
35 |
+
y_train.append(train_data[i, 0])
|
36 |
+
|
37 |
+
x_train, y_train = np.array(x_train), np.array(y_train)
|
38 |
+
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) # Reshape for LSTM
|
39 |
+
|
40 |
+
return x_train, y_train, scaler, training_data_len, scaled_data
|
41 |
+
|
42 |
+
# Step 4: Build the LSTM Model
|
43 |
+
def build_model(input_shape):
|
44 |
+
model = Sequential()
|
45 |
+
model.add(LSTM(50, return_sequences=True, input_shape=input_shape))
|
46 |
+
model.add(Dropout(0.2))
|
47 |
+
model.add(LSTM(50, return_sequences=False))
|
48 |
+
model.add(Dropout(0.2))
|
49 |
+
model.add(Dense(25))
|
50 |
+
model.add(Dense(1)) # Prediction of the next closing price
|
51 |
+
model.compile(optimizer='adam', loss='mean_squared_error')
|
52 |
+
return model
|
53 |
+
|
54 |
+
# Step 5: Train the Model
|
55 |
+
def train_model(model, x_train, y_train, epochs=10, batch_size=1):
|
56 |
+
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)
|
57 |
+
|
58 |
+
# Step 6: Make Predictions
|
59 |
+
def make_predictions(model, scaled_data, training_data_len, scaler):
|
60 |
+
# Create the test dataset
|
61 |
+
test_data = scaled_data[training_data_len - 60:, :]
|
62 |
+
x_test = []
|
63 |
+
for i in range(60, len(test_data)):
|
64 |
+
x_test.append(test_data[i-60:i, 0])
|
65 |
+
x_test = np.array(x_test)
|
66 |
+
|
67 |
+
# Reshape the data
|
68 |
+
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
|
69 |
+
|
70 |
+
# Get the predicted price
|
71 |
+
predictions = model.predict(x_test)
|
72 |
+
predictions = scaler.inverse_transform(predictions) # Inverse scaling
|
73 |
+
return predictions
|
74 |
+
|
75 |
+
# Step 7: Visualize the Results
|
76 |
+
def visualize_results(data, predictions):
|
77 |
+
train = data[:len(data) - len(predictions)]
|
78 |
+
valid = data[len(data) - len(predictions):]
|
79 |
+
valid['Predictions'] = predictions
|
80 |
+
|
81 |
+
# Plotting
|
82 |
+
plt.figure(figsize=(16, 8))
|
83 |
+
plt.title('Model')
|
84 |
+
plt.xlabel('Date')
|
85 |
+
plt.ylabel('Close Price USD')
|
86 |
+
plt.plot(train['Close'])
|
87 |
+
plt.plot(valid[['Close', 'Predictions']])
|
88 |
+
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
|
89 |
+
plt.show()
|
90 |
+
|
91 |
+
# Example Usage
|
92 |
+
if __name__ == "__main__":
|
93 |
+
# Set parameters
|
94 |
+
ticker = "AAPL" # Example ticker (Apple Inc.)
|
95 |
+
start_date = "2020-01-01"
|
96 |
+
end_date = datetime.now().strftime("%Y-%m-%d")
|
97 |
+
|
98 |
+
# Load data
|
99 |
+
data = load_data(ticker, start_date, end_date)
|
100 |
+
|
101 |
+
# Preprocess data
|
102 |
+
x_train, y_train, scaler, training_data_len, scaled_data = preprocess_data(data)
|
103 |
+
|
104 |
+
# Build and train the model
|
105 |
+
model = build_model((x_train.shape[1], 1))
|
106 |
+
train_model(model, x_train, y_train, epochs=50)
|
107 |
+
|
108 |
+
# Make predictions
|
109 |
+
predictions = make_predictions(model, scaled_data, training_data_len, scaler)
|
110 |
+
|
111 |
+
# Visualize results
|
112 |
+
visualize_results(data, predictions)
|