1 of 92

A Stock Market Prediction System based on Learning from Historical Prices and Customer Reviews

Supervised By

Dr. Reda El-Basiony

2 of 92

Abdallah Ibrahim El-Badry

Abdelrahman Mohamed Emam

Aya Mohsen El-Kilany

Habiba Khaled Ibrahim

Ibrahim Mohamed Yousef

Mona Mardy El-Araby

Reem Emad Abdelaziz

Team Members

3 of 92

Outlines

01

Problem & Solution

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

4 of 92

Problem Statement

  • How Stocks Begin!?

​

  • Modern stock markets

​

  • Future of stock market

​

  • Financial data of stock market is of complex nature, which makes it difficult to predict or forecast the stock market behavior.
  • Prediction of stocks is generally believed to be a very difficult task. In fact, stock market price prediction is very fluctuating in nature. They depend on various factors like the previous stock prices, current market trends, financial news, competitor’s performance etc.

5 of 92

Problem Statement

6 of 92

Motivation

  • The stock market play a pivotal role in the growth of the industry and commerce.

​

  • The government, industry and central banks of the country keep a close watch on the happenings of the stock market

​

  • For successful investment, many investors are interested in knowing about the future situation of the market.

​

  • Effective prediction systems indirectly help traders by providing supportive information such as the future market direction.

7 of 92

Stock Market Applications

  • Yahoo! Finance

Allows users to sync portfolios and quotes across multiple devices � Tracking stocks, currencies, commodities � Notifications allow you to stay current on breaking news

​

  • Stock Market Simulator

Users can play a simulated version of the real U.S. stock market and invest virtual funds without taking on any real risk. � Shouldn't be used as a decision-making tool for actual trading � A great way for first-time investors to get their feet wet and learn how the stock� market works without losing any actual money. �

8 of 92

Proposed Solution

  • Study and analyze the historical information.

​

  • Sentiment analysis of Tweets.

​

  • Construct an effective model to predict stock market future trends with small error ratio and improve the accuracy of prediction.

​

  • This model is based on sentiment analysis of financial news from twitter and historical stock market prices that provides better accuracy results considering multiple types of news related to market and company with historical stock prices.

9 of 92

Proposed Solution

Historical Data

  • Using stock market historical data and studying specific examples from the stock market past, make it easier to put current market moves in context, while making informed decision.
  • notice how the Dow and NASDAQ index charts move in lockstep through their respective decades. The 1929 stock market crash reflected in Dow index overlays almost perfectly against the 2000 NASDAQ index break.

10 of 92

Tweets

  • Several studies show why. Blake spoor, Miller, and White (2014) suggest that Twitter influences the trading volume within the market.
  • Another study showed that sentiment of tweets (including non-company published tweets) are associated with abnormal returns.

Proposed Solution

11 of 92

Outlines

01

Introduction

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

12 of 92

System Model

Goals:

  • Facilize the communication between the system components
  • Organize the workflow between services
  • Facilize data transformation between machine learning model and web application
  • Increase the response time of the system to provide customers with updated predictions in time.

13 of 92

System Model

This project built on Google Cloud infrastructure..

​

Why Cloud!?

1. Cost efficiency

2. Private Global Fiber + Tiered Network�3. Increase number of users�4. Improved Performance �5. More Security�6. Continued Expansion

7. Scalability

8. Flexibility

​

What is Google Cloud Platform!?

Google Cloud Platform is a suite of public cloud computing services offered by Google

14 of 92

System Architecture

15 of 92

Outlines

01

Introduction

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

16 of 92

System Architecture

17 of 92

Html, css and..React js!

React (also known as React.js or ReactJS) is a JavaScript library for building user interfaces.

​

React allows developers to create large web applications which can change data, without reloading the page.

​

​

Why React js?

  • It’s about using reusable components.
  • Small Learning Curve, much less than other frameworks.
  • React has a huge community of support.

​

What is React js?

18 of 92

Data Visualization

  • Is representing data in a visual form. This visual form can be a chart, graphs, lists. This representation helps people to understand the magnitude of the data.
  • To communicate information clearly and efficiently to users.
  • Helps data analytics to get better insights.
  • Data visualization and analytics will draw the conclusions about the datasets.

The Tool We Used:

​

React Stockcharts: creates highly customizable stock charts built with React js and d3.

19 of 92

Home page

20 of 92

Featured Companies

21 of 92

Company Page

Historical Prices

22 of 92

Company Page

Daily Prediction

23 of 92

Company Page

Monthly Prediction

24 of 92

Company Page

Twitter Analysis

25 of 92

News(Twitter)

26 of 92

News(Financial News)

27 of 92

Outlines

01

Introduction

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

28 of 92

  • System Architecture

Back End Development

29 of 92

  • App Engine

What is app engine & features?

  • Google App Engine is a web framework and cloud computing platform for developing and hosting web applications in Google-managed data centers.

Back End Development

30 of 92

  • App engine features
  • Salable
  • Runtimes
  • Data Storage
  • Infrastructure
  • Security
  • Faster time
  • Easy to use and maintain.
  • communication between product.
  • SDK

​

by download SDK, we can start the project.

​

Back End Development

31 of 92

Back End Development

32 of 92

  • Storage

Compute Engine

Big query

App Engine

App engine

(website)

Big query

Send request for data

Response Send back json file

Back End Development

33 of 92

  • Connection example

This API call could be local like this

This API call for Facebook stocks prediction.

Call query from bigquery , the result json file

Back End Development

34 of 92

Then after deploy the backend folder on google cloud:

  • Connection example

Back End Development

35 of 92

In Front-End Use Axios to call API

Axios is a JavaScript library used to make HTTP requests

Back End Development

  • Connection example

36 of 92

  • Deployment

http://www.tanta-stocks.appspot.com

Build React

Deploy on

App Engine

Front-end

+

Back-end

Back End Development

37 of 92

Home page

38 of 92

Outlines

01

Introduction

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

39 of 92

Machine Learning For Time Series Forecasting

Phase1

01

Phase2

02

Phase3

03

Phase1

Historical Data

Phase2

Social media Data(Twitter)

Phase3

Historical + Twitter Data

40 of 92

Machine Learning For Time Series Forecasting

Phase1

01

Phase2

02

Phase3

03

Phase1

Historical Data

Phase2

Social media Data(Twitter)

Phase3

Historical + Twitter Data

41 of 92

Phase 1

ARIMA Model

FBProphet

For Short term Prediction

For Long term Prediction

42 of 92

Time Series Data

Time-series data is a sequence of observations stored in time order.

​

Time series analysis is an approach to analyze time series data to extract meaningful characteristics of data and generate other useful insights applied in business situation.

Time series analysis helps understand time-based patterns of a set of metric data points which is critical for any business.

​

43 of 92

ARIMA Model

ARIMA stands for Auto Regressive Integrated Moving Average.

​

The AutoRegressive (AR) model

specifies that the output variable depends linearity on its own previous values.

Yt = β0 + β1 Yt-1 + β2 Yt-2 + .. + βpYt-p

​

Moving average Model

In statistics, a moving average is a calculation to analyze data points by creating a series of averages of different subsets of the full data set.

MA=(A1​+A2​+…+An​)/n​

​

ARIMA is a combination of Auto Regression Model and moving Average Model with difference to make data stationary.

The parameters of the ARIMA model are defined as follows:

• p is the number of autoregressive terms(AR Model)

• q is the number of lagged forecast errors in the prediction equation(MA Model)

• d is the number of nonseasonal differences needed for stationarity(Integration level)

​

44 of 92

Historical Data API

Data Schema

  • Yahoo Finance is our source of stock prices data.

​

  • Yahoo Finance APIs in python is available in different ways and sources. And in this point, we choose pandas-datareader to become our API to crewel data from Yahoo Finance.

​

  • Our data considers 10 main corporations.

45 of 92

Visualizing Close time series data

46 of 92

Validating forecasts

To help us understand the accuracy of our forecasts, we compare predicted Close to real close price of the time series

47 of 92

Producing and visualizing forecasts

48 of 92

FBprophet Model

Fbprophet is an open source released by Facebook in order to provide some useful guidance for producing forecast at scale.

​

fbprophet package in Python or R can help us look deeper into the hidden cycles in stock market.

​

The Prophet uses a decomposable time series model with three main model components: trend, seasonality, and holidays. They are combined in the following equation:

y(t)= g(t) + s(t) + h(t) + εt

​

• g(t): piecewise linear or logistic growth curve for modeling non-periodic changes in time series.

• s(t): periodic changes (e.g. weekly/yearly seasonality).

• h(t): effects of holidays (user provided) with irregular schedules.

• εt: error term accounts for any unusual changes not accommodated by the model.

​

The important idea in Prophet is that by doing a better job of fitting the trend component very flexibly, we more accurately model seasonality and the result is a more accurate forecast

49 of 92

Apple stock price from 2014/10/10 to 2019/2/15

50 of 92

We can also visualize our data according to different components of FBprophet model: weekly, yearly, trend and user-defined cycle

51 of 92

Model validation

In our model we try to use last 12-month data to predict the next 10 days.

52 of 92

Machine Learning For Time Series Forecasting

Phase1

01

Phase2

02

Phase3

03

Phase1

Historical Data

Phase2

Social media Data(Twitter)

Phase3

Historical + Twitter Data

53 of 92

Phase 2

Sentimental Analysis

Nature Language Processing

54 of 92

Sentiment Analysis

Sentiment Analysis is the most common text classification tool that analyses an incoming message and tells whether the underlying sentiment is positive, negative our neutral.

55 of 92

Naïve Bayes

​

Bayes theorem calculations :

​

  • P(c|x) is the probability of class (c, target) given predictor (x, attributes).
  • P(c) is the probability of class.
  • P(x|c) is the probability of predictor given class.
  • P(x) is the prior probability of predictor.

​

56 of 92

Data Set Sample

We used training dataset from sentiment140.com. The dataset comes with prelabeled columns containing one of two binary targets. Zero(0) for Negative sentiment and Four(4) for Positive sentiment. The data is made up of about 1.6 million random tweets with corresponding sentiment labels.

�

57 of 92

Twitter API

Tweets

    • To get the most effective influence of tweets, we were in need to get historical tweets and up-to-date tweets.

    • To work with twitter API to get up-to-date data we install some libraries like tweepy.

58 of 92

Training Data Preprocessing

​

Pre-processing steps:

​

    • Convert @username to AT_USER.
    • HTML special entities (e.g. & amp;).
    • Make all the text in lower case.
    • Remove:
        • hyperlinks.
        • Remove hashtags.
        • Remove Punctuation and split 's, 't, 've with a space for filter.
        • Remove words with 2 or fewer letters.
        • Remove whitespace (including new line characters).
        • Remove single space remaining at the front of the.
        • tickers.

​

59 of 92

Feature Extraction

We will transform data into tokens and then tokens into features. This is done by Term Frequency, Inverse Document Frequency (TF-IDF).

​

We'll convert each message which is represented by a list of tokens into a vector that a machine learning model can understand.

​

Feature Extraction steps:

  1. Count how many times does a word occur in each message (Known as term frequency TF which measures how frequently a term occurs in a document)

​

  • Weigh the counts, so that frequent tokens get lower weight (inverse document frequency IDF which measures how important a term is)

​

  • TF(t) = (Number of times term appears in a document) / (Total number of terms in the document).

​

  • IDF(t) = loge (Total number of documents / Number of documents with term t in it)

​

60 of 92

Naïve Bayes Training

  • The recommended method for training a good model is to first cross-validate using a portion of the training set itself to check if you have used a model with too much capacity (i.e. if the model is overfitting the data).
  • We use the KFold strategy to split the model into random parts to find out if it's generalizing well or if it's overfitting.
  • For our case, there are 4 + 2 + 2=8 parameter combinations to test and 10 KFold validations, so the model will be trained and tested on the validation set 8 x 10 = 80 times.

​

​

61 of 92

Naïve Bayes score

  • Confusion matrix
  • Precision
  • Recall
  • F1 -score

​

62 of 92

Phase 2

Sentimental Analysis

Nature Language Processing

63 of 92

What is deep learning ?

​

Deep Learning is :

​

  • subset of machine learning
  • deep learning was inspired by artificial neural networks, that composed of three stages :

*input layer .

*hidden layer.

*output layer .

​

​

64 of 92

NLP

Natural Language Processing (NLP) is the field of Artificial Intelligence concerned with the processing and understanding of human language.

Since its inception during the 1950s, machine understanding of language has played a pivotal role in translation, topic modeling, document indexing,

information retrieval, and extraction.

​

65 of 92

NLP using Deep learning

​

​

​

CNN can extract an area of features from global information, and it is able to consider the relationship among these features. The above solution can achieve a higher accuracy in analysis and classification. For natural language processing, texts data features also can be extracted piece by piece and to consider the relationship among these features, but without the consideration of context or whole sentence, the sentiment might be understood wrong.

​

​

CNN has a convolutional layer to extract information by a larger piece of text, so we work for sentiment analysis with convolutional neural network

​

​

​

​

​

​

​

​

​

​

66 of 92

Model Architecture

67 of 92

Model Architecture

68 of 92

Model Layer description:

1- Embedding Layer:

​

we can think of the Embedding layer as a dictionary

that maps an index assigned to a word to a word vector.

This layer is very flexible and can be used in a few ways:

a-The embedding layer can be used at the start of

a larger deep learning model.

​

b-Also, we could load pre-train word embeddings into

the embedding layer when we create our model.

​

​

​

​

​

​

​

​

​

​

​

​

69 of 92

Model Layer description:

2- Convolution layer:

​

​

After we come out of embedding layer, we want to get feature

descriptor for whole of text, so we use neural network over this

embedding. To analyze n-grams in our text, we just convolve

the word vectors that are near, you can think of it as sliding

window walk on our word vector matrix.  You need to track

many n-grams,  that's why you need a lot of convolutional filters.

 And these filters are called 1D convolutions because we

slide the window only in one direction.

​

​

​

​

​

​

​

​

​

70 of 92

​

Model Layer description:

​

​

​

3- Maxpooling layer:

​

is a sample-based discretization process.

The objective is to down-sample an input

representation (image, hidden-layer 

output matrix, etc.), reducing its

dimensionality , we do maximum pooling

overtime and, we apply multiple filter with

different length and finally we got vector is

a kind of embedding of our input sequence.

​

​

​

​

​

​

​

71 of 92

​

Model Layer description:

​

4- Flatten layer:

Does not affect the batch size. The purpose of this argument is to preserve weight ordering when switching a model from one data format to another

​

5- Dense layer :

Two dense layer are used in our architecture one with relu activation function , another one with sigmoid

​

6- dropout layer:

​

This layer prevent overfitting .

​

​

​

​

​

​

​

​

​

72 of 92

Data Cleaning

Text preprocessing is technique that transforms raw data into an understandable format. Raw data(real world data) is always incomplete and that data cannot be sent through a model. That would cause certain errors. That is why we need to preprocess data before sending through a model.

​

Preprocessing steps:

1- lowering words.

2- remove punctuation.

3- remove hyperlinks.

4-remove unused fields.

73 of 92

Feature Extraction

We will transform tokens(words) into features. This is done by word embedding. Word Embedding is the texts converted into numbers and there may be different numerical representations of the same text. many Machine Learning algorithms and almost all Deep Learning Architectures are incapable of processing strings or plain text in their raw form They require numbers as inputs to perform any sort of job, be it classification, regression etc. A Word Embedding format generally tries to map a word using a dictionary to a vector.

​

Feature Extraction steps:

1- Tokenize sentence into words or tokens. Each word take an integer id . Start indexing from1.

2- Convert sentence into vector of numbers by replacing each word by its integer id .(To_sequence_function)

3- padding sequence mean when there are multiple sentence with different length ,we are in need to make them equal in length vector.

​

​

​

​

​

​

​

​

​

​

​

​

​

74 of 92

Model Training

75 of 92

Comparison

​

sentiment analysis

(with machine learning)

Nlp using deep learning

Data dependency

Machine learning algorithms often work well even if the dataset is small

Deep learning is Data Hungry the more data you have, the better it is likely to perform

computation power

Traditional machine learning algorithm can be implemented on a CPU

For the deep learning network training, you need a graphical processing unit (GPU) which have thousands of cores compared to a CPU that has very minimal cores.

Time consuming

Whereas traditional machine learning algorithms often train very fast ranging from few minutes to a couple of hours, but during the test time, some algorithms can also take quite a bit of time.

The training time of a deep learning network can range from anywhere between a few hours to months

76 of 92

Machine Learning For Time Series Forecasting

Phase1

01

Phase2

02

Phase3

03

Phase1

Historical Data

Phase2

Social media Data(Twitter)

Phase3

Historical + Twitter Data

77 of 92

Phase 3

Sell or buy model

Polynomial model

CNN model

78 of 92

1- Sell/Buy Model

  • We extracted tweets from API, processed them for Natural Language Processing (NLP) and sentiment analysis.
  • After predicting sentiment, we extracted historical data from Yahoo Finance.
  • We then developed a model for stock market prediction using stock price data and sentiment score to predict the change in stock market.
  • The proposed methodology for predicting the stock market movement through sentiment analysis showed in the following figure:

79 of 92

We used SVM model to suggest whether a person should buy or sell a share. We applied some preprocessing on the data as we created new columns to present the class if it is 1 or 0 (buy or sell) so we can train the model.

SELL

BUY

SVC Model

We achieved 98% accuracy

80 of 92

2- Polynomial Regression Model

​

In statistics, polynomial regression is a form of regression analysis in which the relationship between the independent variable x and the dependent variable  y is modelled as an nth degree polynomial in x. Polynomial regression fits a nonlinear relationship between the value of x and the corresponding conditional mean of y, denoted E(y | x).  Polynomial regression is considered to be a special case of multiple linear regression.

​

This is the general equation of a polynomial regression is:

​

Y=θo + θ₁X + θ₂X² + … + θₘXᵐ + residual error

​

​

We developed a polynomial regression model to enhance our daily prediction using the score we get from NLP analysis of tweets and customer reviews. We used a second-degree model to fit our data. We used 70% of the data for training the model and 30% for the evaluation.

​

​

​

​

81 of 92

2- Polynomial Regression Validation

82 of 92

3- CNN Model

We use 3 hidden layers (Conv2D, MaxPooling2D and Dense). And input of size (1,7,7). We use RELU function for all of them.

  • Conv2D

Conv2D of 64 neurons.

  • MaxPooling2D

Pool size = (1, 2).

  • Dense

Dense of 30 neurons

83 of 92

3- CNN Model Architecture

Input Layer 49 neurons

Dense�7*7*32

Output Layer

Conv2D 7*7*64

MaxPooling2D 1*2*64

​

​

84 of 92

3- CNN Model Architecture

85 of 92

3- CNN Model Validation

86 of 92

Evaluation

Actual / predicted

True

False

True

35

1

False

0

63

 

87 of 92

Evaluation

Model

MSE

RMSE

EVS

R2

 

CNN

 

4.567077

 

6.52544

 

0.86388

 

0.86266

 

Polynomial

 

8.4125

 

2.9

 

0.9731

 

0.9724

 

FBprophet

 

6.6753

 

9.219508

 

0.73108

 

0.73107

88 of 92

Outlines

01

Introduction

02

System Components And Architecture

04

Front End Development

03

Back End Development

05

Machine Learning For Time Series Forecasting

06

Conclusions & Future Work

89 of 92

Conclusions

  • We developed two models based on historical data for long-term and short-term predictions

​

  • We used the customer reviews to make our predictions more accurate , So we developed a NLP model to analysis the customer review

​

  • Finally , We developed three models to combine the analysis of customer reviews with our predictions so we can get better predictions and more accurate system with higher performance

90 of 92

  • Prediction
  • Data
  • Application

Future Work

91 of 92

Demo

92 of 92

Thank You

Insert the Sub Title of Your Presentation