rogarciago / CIENCIA-DE-DATOS

0 stars 0 forks source link

RNN AAL #5

Open rogarciago opened 3 years ago

rogarciago commented 3 years ago

!/usr/bin/env python

coding: utf-8

In[2]:

import numpy as np import pandas as pd import plotly.graph_objs as go from pandas_datareader import data, wb from datetime import date import cufflinks as cf import yfinance as yf import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout import math from sklearn.preprocessing import MinMaxScaler import sklearn.metrics as metrics import sklearn.metrics as sm from sklearn.metrics import mean_squared_error from sklearn.metrics import accuracy_score, confusion_matrix

In[3]:

start=pd.to_datetime('2013-01-01') end=pd.to_datetime('2018-01-01')

In[4]:

AAL = data.DataReader('AAL', 'yahoo', start, end)

In[5]:

AAL_processed=AAL.iloc[:, 3:4].values

In[6]:

scaler = MinMaxScaler(feature_range = (0, 1)) AAL_training_scaled = scaler.fit_transform(AAL_processed)

In[7]:

x_train = [] y_train = [] for i in range(60, 1259): x_train.append(AAL_training_scaled[i-60:i, 0]) y_train.append(AAL_training_scaled[i, 0]) x_train, y_train = np.array(x_train), np.array(y_train)

In[8]:

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

In[9]:

model = Sequential() model.add(LSTM(units=200, return_sequences=True, activation='relu',input_shape=(x_train.shape[1], 1))) model.add(Dropout(0.2))

model.add(LSTM(units=200, return_sequences=True)) model.add(Dropout(0.2))

model.add(LSTM(units=200, return_sequences=True)) model.add(Dropout(0.2))

model.add(LSTM(units=200, return_sequences=False)) model.add(Dropout(0.2))

In[10]:

model.add(Dense(units = 1)) model.compile(optimizer = 'adam', loss = 'mean_squared_error')

In[11]:

model.fit(x_train, y_train, epochs = 100, batch_size = 32)

In[12]:

start=pd.to_datetime('2018-01-01') end=pd.to_datetime('2018-01-8') AAL2 = data.DataReader('AAL', 'yahoo', start, end)

In[13]:

AAL2_processed=AAL2.iloc[:, 3:4].values AAL_total = pd.concat((AAL['Close'], AAL2['Close']), axis=0) test_inputs = AAL_total[len(AAL_total) - len(AAL2) - 60:].values test_inputs = test_inputs.reshape(-1,1) test_inputs = scaler.transform(test_inputs)

In[14]:

test_features = [] for i in range(60, 65): test_features.append(test_inputs[i-60:i, 0])

In[15]:

test_features = np.array(test_features) test_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1))

In[16]:

predictions = model.predict(test_features)

In[17]:

predictions = scaler.inverse_transform(predictions)

In[18]:

plt.figure(figsize=(10,6)) plt.plot(AAL2_processed, color='blue', label='Actual American Airlines Stock Price') plt.plot(predictions , color='red', label='Predicted Americsn Airlines Stock Price') plt.title('American Airline Stock Price Prediction') plt.xlabel('Date') plt.ylabel('Tesla Stock Price') plt.legend() plt.show()

In[19]:

print("Mean absolute error =", round(sm.mean_absolute_error(AAL2_processed, predictions), 2)) print("Mean squared error =", round(sm.mean_squared_error(AAL2_processed, predictions), 2)) print("Median absolute error =", round(sm.median_absolute_error(AAL2_processed, predictions), 2)) print("Explain variance score =", round(sm.explained_variance_score(AAL2_processed, predictions), 2)) print("R2 score =", round(sm.r2_score(AAL2_processed, predictions), 2))

In[20]:

start=pd.to_datetime('2018-01-01') end=pd.to_datetime('2018-02-01') AAL3 = data.DataReader('AAL', 'yahoo', start, end)

In[21]:

AAL3_processed=AAL3.iloc[:, 3:4].values

In[22]:

AAL_total = pd.concat((AAL['Close'], AAL3['Close']), axis=0)

In[23]:

test_inputs = AAL_total[len(AAL_total) - len(AAL3) - 60:].values

In[24]:

test_inputs = test_inputs.reshape(-1,1) test_inputs = scaler.transform(test_inputs)

In[25]:

test_features = [] for i in range(60, 82): test_features.append(test_inputs[i-60:i, 0])

In[26]:

test_features = np.array(test_features) test_features = np.reshape(test_features, (test_features.shape[0], test_features.shape[1], 1))

In[27]:

predictions = model.predict(test_features) predictions = scaler.inverse_transform(predictions)

In[28]:

plt.figure(figsize=(10,6)) plt.plot(AAL3_processed, color='blue', label='Actual American Airlines Stock Price') plt.plot(predictions , color='red', label='Predicted American Airlines Stock Price') plt.title('American Airlines Stock Price Prediction') plt.xlabel('Date') plt.ylabel('American Airlines Stock Price') plt.legend() plt.show()

In[29]:

print("Mean absolute error =", round(sm.mean_absolute_error(AAL3_processed, predictions), 2)) print("Mean squared error =", round(sm.mean_squared_error(AAL3_processed, predictions), 2)) print("Median absolute error =", round(sm.median_absolute_error(AAL3_processed, predictions), 2)) print("Explain variance score =", round(sm.explained_variance_score(AAL3_processed, predictions), 2)) print("R2 score =", round(sm.r2_score(AAL3_processed, predictions), 2))