#!/usr/bin/env python
# coding: utf-8

# In[11]:


#Predicting Stock Prices by relying on ML Models

#installing required libraries
import quandl
import numpy as np
from sklearn.linear_model import LinearRegression   #ML package for regression model 
from sklearn.svm import SVR                         #Support Vector Machine - another model 
from sklearn.model_selection import train_test_split  #method


# In[22]:


#Get the stock data
df = quandl.get("WIKI/FB")

# Print data
print(df.head())


# In[23]:


# Getting adjusted close price

df = df[['Adj. Close']]

print(df.head())


# In[76]:


# Predicting 'N' Days into the future
forecast_out = 150

#Create the dependent variable
df['Prediction'] = df[['Adj. Close']].shift(-forecast_out)
print(df.head)


# In[77]:


# Create the independent dataset

#create numpy array using the dataframe

X = np.array(df.drop(['Prediction'],1))

#Removing NaN rows

X = X[:-forecast_out]

print(X)


# In[78]:


# Create the dependent dataset
y = np.array(df['Prediction'])

y = y[:-forecast_out]

print(y)


# In[79]:


# Creating training and testing data

x_train, x_test, y_train, y_test = train_test_split(X,y, test_size = 0.2)


# In[80]:


# Create and train the model using SVM 

svr_rbf = SVR(kernel ='rbf', C=1e3, gamma = 0.1)
svr_rbf.fit(x_train, y_train)

#testing the accuracy of the model
#We will use R^2 to calculate the fitting of the model
svm_confidence = svr_rbf.score(x_test, y_test)
print("SVM confidence: ", svm_confidence)


# In[81]:


# Second model - This time using a Linear Regression Model

lr = LinearRegression()

# Train the model

lr.fit(x_train, y_train)

# Testing the accuracy of this model 

lr_confidence = lr.score(x_test, y_test)
print("Linear Regression Confidence:", lr_confidence)


# In[82]:


# Since we are forecasting on the last month,
# We will use these values as our testing data

x_forecast = np.array(df.drop(['Prediction'],1))[-forecast_out:]

lr_prediction = lr.predict(x_forecast)
#print(lr_prediction)

svm_prediction = svr_rbf.predict(x_forecast)
print(svm_prediction)


# In[107]:


#Creating a Visualization of our model

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(10,8))
plt.plot(svm_prediction, label = "SVM")
plt.plot(lr_prediction, label = "Regression")
plt.plot(x_forecast, color = 'red', label = "Actual Prices")
plt.xlabel('Days',fontsize = '15')
plt.ylabel('$ Value', fontsize = '15')
plt.legend()


# In[ ]:


# As we can see, the Linear regression overestimates and the SVM underestimates the Actual Stock Value. 
# It's good to see that the actual value remains between both models
# An extension on top of this would be to combine both the SVM and the Regression to get a better fit 

