Predict Stock Prices with Regression Analysis with Pandas & Python

by - August 05, 2018

Image result for wolf of the wall street

Ever wondered, can we predict the stock prices ?  Investors make calculated guess by analyzing data like company history, news and industry trends they go into making a prediction.

But Stock Prices are completely random. Hence Finance companies like Morgan Stanely and citigroup hire data analyst to build the predictive models. In this age of algorithms today we'll check out this simple code which predicts the stock prices of Google so lets begin.

import quandl, math                                                                   
import numpy as np                                                                   
import pandas as pd                                                                   
from sklearn import preprocessing, cross_validation, svm       
from sklearn.linear_model import LinearRegression                

Here we first import all the required libraries such as math, numpy and pandas.
for those who do not know what is the use of this libraries here is just a quick overview of it

quandl  : Quandl is a marketplace for financial, economic and alternative data delivered in modern formats for today's analysts, including Python
pandas  : pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools
numpy  : used for scientific computing with python
sklearn : Machine Learning library used for data mining and analysis.
math     : It provides access to the mathematical functions defined by the C standard. ... Return fmod(x, y) , as defined by the platform C library.

If you dont know how to setup these libraries you can check it out here.

df = quandl.get("WIKI/GOOGL")
df = df[['Adj. Open',  'Adj. High',  'Adj. Low',  'Adj. Close', 'Adj. Volume']]
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0

df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0

df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
forecast_col = 'Adj. Close'
df.fillna(value=-99999, inplace=True)
forecast_out = int(math.ceil(0.01 * len(df)))
df['label'] = df[forecast_col].shift(-forecast_out)

X = np.array(df.drop(['label'], 1))
X = preprocessing.scale(X)
X = X[:-forecast_out]
df.dropna(inplace=True)
y = np.array(df['label'])
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)

clf = LinearRegression(n_jobs=-1)
clf.fit(X_train, y_train)
accuracy = clf.score(X_test, y_test)

print(accuracy)

I will stress that creating a linear model with say >95% accuracy is not that great. I certainly wouldn't trade stocks on it. There are still many issues to consider, especially with different companies that have different price trajectories over time. Google really is very linear: Up and to the right. Many companies aren't, so keep this in mind. Now, to forecast out, we need some data. We decided that we're forecasting out 1% of the data, thus we will want to, or at least *can* generate forecasts for each of the final 1% of the dataset. So when can we do this? When would we identify that data? We could call it now, but consider the data we're trying to forecast is not scaled like the training data was. Okay, so then what? Do we just do preprocessing.scale() against the last 1%? The scale method scales based on all of the known data that is fed into it. Ideally, you would scale both the training, testing, AND forecast/predicting data all together. Is this always possible or reasonable? No. If you can do it, you should, however. In our case, right now, we can do it. Our data is small enough and the processing time is low enough, so we'll preprocess and scale the data all at once.
In many cases, you wont be able to do this. Imagine if you were using gigabytes of data to train a classifier. It may take days to train your classifier, you wouldn't want to be doing this every...single...time you wanted to make a prediction. Thus, you may need to either NOT scale anything, or you may scale the data separately. As usual, you will want to test both options and see which is best in your specific case.

Final Words :

This is juts basic stock price predictor soon i'll be uploading an advance and more complex version of this and more amazing articles like this till then stay tuned.
You can get the code to this article from our github repository.

You May Also Like

0 comments