# -*- coding: utf-8 -*-
"""Demonstrate recurrent neural network that learns to perform sequence  analysis for stock price

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1Cef6TY4UreI4bjAEovxQ6zb6GHHvCzAr
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime
from tensorflow.keras.callbacks import EarlyStopping
import warnings
warnings.filterwarnings("ignore")


data = pd.read_csv('all_stocks_5yr.csv', delimiter=',')
data['date'] = pd.to_datetime(data['date'])


apple = data[data['Name'] == 'AMG']
apple = apple[['date', 'open', 'high', 'low', 'close', 'volume']].sort_values(by='date')


features = ['open', 'high', 'low', 'close', 'volume']
close_data = apple[features].values
train_size = max(int(len(close_data) * 0.9), len(close_data) - 100)  # Ensure at least 100 test samples
train_data, test_data = close_data[:train_size], close_data[train_size:]


if len(train_data) <= 60 or len(test_data) <= 60:
    raise ValueError("Not enough data points for sequence length. Reduce seq_length or increase dataset size.")


scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit(train_data)
train_scaled = scaler.transform(train_data)
test_scaled = scaler.transform(test_data)


def create_sequences(data, seq_length=60):
    x, y = [], []
    for i in range(seq_length, len(data)):
        x.append(data[i-seq_length:i])
        y.append(data[i, 3])
    x, y = np.array(x), np.array(y)
    print(f"Created sequences: x={x.shape}, y={y.shape}")
    if x.shape[0] == 0:
        raise ValueError("Sequence creation failed. Check data size and seq_length.")
    return x, y
x_train, y_train = create_sequences(train_scaled)
x_test, y_test = create_sequences(test_scaled)



model = keras.Sequential([
    keras.layers.LSTM(64, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2])),
    keras.layers.LSTM(64, return_sequences=False),
    keras.layers.Dense(32, activation='relu'),
    keras.layers.Dropout(0.3),
    keras.layers.Dense(1)
])

model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()


early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
model.fit(x_train, y_train, epochs=50, batch_size=16, validation_data=(x_test, y_test), callbacks=[early_stopping])

predictions = model.predict(x_test)

scaled_test_copy = test_scaled[60:].copy()
scaled_test_copy[:, 3] = predictions[:, 0]
predictions = scaler.inverse_transform(scaled_test_copy)[:, 3]

print("Predicted vs Actual Stock Prices:")
for pred, actual in zip(predictions, scaler.inverse_transform(test_scaled[60:])[:, 3]):
    print(f"Predicted: {pred:.2f}, Actual: {actual:.2f}")

dates = apple['date'].values[train_size + 60:]
train_dates = apple['date'].values[:train_size]

plt.figure(figsize=(12, 6))
plt.plot(train_dates, train_data[:, 3], label='Training Data', color='blue')
plt.plot(dates, test_data[60:, 3], label='Actual Prices', color='black')
plt.plot(dates, predictions, label='Predicted Prices', color='red')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.title('Apple Stock Price Prediction Using RNN')
plt.legend()
plt.show()

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime
from tensorflow.keras.callbacks import EarlyStopping
import warnings
warnings.filterwarnings("ignore")
# Load dataset, o
data = pd.read_csv('all_stocks_5yr.csv', delimiter=',')
data['date'] = pd.to_datetime(data['date'])
# Select Apple stock data
apple = data[data['Name'] == 'AAPL']
apple = apple[['date', 'open', 'high', 'low', 'close', 'volume']].sort_values(by='date')
# Split dataset into training and testing
features = ['open', 'high', 'low', 'close', 'volume']
close_data = apple[features].values
train_size = max(int(len(close_data) * 0.9), len(close_data) - 100)  # Ensure at least 100 test samples
train_data, test_data = close_data[:train_size], close_data[train_size:]
# Ensure sufficient data for sequence creation
if len(train_data) <= 60 or len(test_data) <= 60:
    raise ValueError("Not enough data points for sequence length. Reduce seq_length or increase dataset size.")
# Normalize data
scaler = MinMaxScaler(feature_range=(0, 1))
scaler.fit(train_data)
train_scaled = scaler.transform(train_data)
test_scaled = scaler.transform(test_data)
# Create sequences with 60-day window
def create_sequences(data, seq_length=60):
    x, y = [], []
    for i in range(seq_length, len(data)):
        x.append(data[i-seq_length:i])
        y.append(data[i, 3])  # Predicting 'close' price
    x, y = np.array(x), np.array(y)
    print(f"Created sequences: x={x.shape}, y={y.shape}")  # Debugging
    if x.shape[0] == 0:
        raise ValueError("Sequence creation failed. Check data size and seq_length.")
    return x, y
x_train, y_train = create_sequences(train_scaled)
x_test, y_test = create_sequences(test_scaled)
# Build RNN model
model = keras.Sequential([
    keras.layers.LSTM(64, return_sequences=True, input_shape=(x_train.shape[1], x_train.shape[2])),
    keras.layers.LSTM(64, return_sequences=False),
    keras.layers.Dense(32, activation='relu'),
    keras.layers.Dropout(0.3),
    keras.layers.Dense(1)
])

model.compile(optimizer='adam', loss='mean_squared_error')
model.summary()
# Train with Early Stopping
early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
model.fit(x_train, y_train, epochs=50, batch_size=16, validation_data=(x_test, y_test), callbacks=[early_stopping])
# Predict stock prices
predictions = model.predict(x_test)
# Correct inverse scaling using the actual test data
scaled_test_copy = test_scaled[60:].copy()
scaled_test_copy[:, 3] = predictions[:, 0]  # Replace 'close' price column with predictions
predictions = scaler.inverse_transform(scaled_test_copy)[:, 3]  # Extract 'close' price
# Print predicted vs actual values
print("Predicted vs Actual Stock Prices:")
for pred, actual in zip(predictions, scaler.inverse_transform(test_scaled[60:])[:, 3]):
    print(f"Predicted: {pred:.2f}, Actual: {actual:.2f}")
# Prepare for visualization
dates = apple['date'].values[train_size + 60:]
train_dates = apple['date'].values[:train_size]
# Plot the results
plt.figure(figsize=(12, 6))
plt.plot(train_dates, train_data[:, 3], label='Training Data', color='blue')
plt.plot(dates, test_data[60:, 3], label='Actual Prices', color='black')
plt.plot(dates, predictions, label='Predicted Prices', color='red')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.title('Apple Stock Price Prediction Using RNN')
plt.legend()
plt.show()

