1922 B.SC Cs Batchno 24
1922 B.SC Cs Batchno 24
BY
MS.B.JOTHILAKSHMI(39290044)
MS.M.SHALINI (39290093)
SATHYABAMA
2022 INSTITUTE OF SCIENCE AND TECHNOLOGY
(DEEMED TO BE UNIVERSITY)
Accredited with Grade "A" by JEPPIAR NAGAR, RAJIV GANDHI
SALAI, CHENNAI-600 119
May-2022
SATHYABAMA
INSTITUTE OF SCIENCE AND TECHNOLOGY
(DEEMED TO BE UNIVERSITY)
www.sathyabama.ac.in
BONAFIDE CERTIFICATE
This is to certify that the Project Report is the bonafide work of B.JOTHILAKSHMI
(39290093) and M.SHALINI(39290093) who carried out the project entitled "STOCK
MARKET PREDICTION USING PYTHON " under our supervision from November
2021 to May 2022.
Internal Guide
I , M.SHALINI here by declare that the Project Report entitled “STOCK MARKET
PREDICTION USING PYTHON” done by me under the guidance of Dr. M.SELVI is
submitted in partial fulfillment of the requirements for the award of Bachelor of
Engineering / Technology degree in Computer science.
DATE:
I would like to express my sincere and deep sense of gratitude to my Project Guide
Mrs. M.SELVI, ME., PH.D., for his valuable guidance, suggestions andconstant
encouragement paved way for the successful completion of my project work.
I wish to express my thanks to all Teaching and Non-teaching staff members of the
Department of computer science who were helpful in many ways for the
ABSTRACR
LIST OF FIGURES
LIST OF ABBREVIATION
1 INTRODUCTION
ⅵ
4 Technologies used
4.1 Hardware required
4.2 software required
6 Testing
7.1 Unit testing
7.2 Tool used for testing
Appendix
A. SOURCE CODE
B. SCREENSHOTS
ⅷ
LIST OF FIGURES
ⅸ
LIST OF ABBREVIATION
ⅹ
CHAPTER 1
INTRODUCTION
Forecasting of stock market is a way to predict future prices of stocks. It is a long time
attractive topic for researcher and investors from its existence. The Stock prices are
dynamic day by day, so it is hard to decide what is the best time to buy and sell stocks.
Machine Learning provides a wide range of algorithms, which has been reported to be
quite effective in predicting the future stock prices. In this project, we explored different
data mining algorithms to forecast stock market prices for NSE stock market. Our goal is
to compare various algorithms and evaluate models by comparing prediction accuracy.
We examined a few models including Linear regression, Arima, LSTM, Random Forest
and Support Vector Regression. Based on the accuracy calculated using RMSE of all the
models, we predicted prices of different industries. For forecasting, we used historical data
of NSE stock market and applied a few preprocessing methods to make prediction more
accurate and relevant. The ultimate goal of our application is to serve retail investors as a
third party investment tool that uses machine learning to help them navigate in the fast-
changing stock market. The project aims to introduce and democratize the latest machine
learning technologies for retail investors. No prediction is 100% accurate. Therefore, the
upper bound and lower bound of the stock prices will be displayed to illustrate the trading
range the investors should be looking this application serves. Stock market prediction ad
analysis are some of the most difficult jobs to complete. There are numerous causes for
this, including market volatility and variety of other dependent and independent variables
that influence the value of a certain stock in the market. These variable make it extremely
difficult for any stock market expert to anticipate the rise and fall on the market with great
precision. Machine learning is a strong algorithm the most recent market research and
stock market prediction advancements have begun to include such approaches in
analyzing stock market data. Implementation of analyzing and forecasting the stock price
in python using various machine learning algorithms. Stock price prediction using machine
learning helps to discover the future value of a company stock and other financial assets
traded on an exchange. The entire idea of stock prices is an gain significant profits. Stock
1
market helps companies to raise capital . It helps to generate personal wealth. Stock
market server as an indicator of the state of the economy. It is a widely used source for
the people to invest money in companies with high growth.
2
CHAPTER 2
2.1 LITERATURE SURVEY
In the finance world stock trading is one of the most important activities. Stock
market prediction is an act of trying to determine the future value of a stock other financial
instrument traded on a financial exchange. This paper explains the prediction of a stock
using Machine Learning. The technical and fundamental or the time series analysis is
used by the most of the stockbrokers while making the stock predictions. The
programming language is used to predict the stock market using machine learning is
Python. we propose a Machine Learning (ML) approach that will be trained from the
available stocks data and gain intelligence and then uses the acquired knowledge for an
accurate prediction. In this context this study uses a machine learning technique called
Support Vector Machine (SVM) to predict stock prices for the large and small
capitalizations and in the three different markets, employing prices with both daily and up-
to-the-minute frequencies.
5
CHAPTER 3
3.2.1RESEARCH:
This project will investigate how different machine learning techniques can be
used and will affect the accuracy of stock price predictions. Different models, from linear
regression to dense and recurrent neural networks are tested. Different hyperparameters
are also tuned for better performance These arch space for all neural network
architectures and hyperparameter combinations is huge, and with limited time in
6
conducting this project, apart from manually trying combinations, the team optimizes the
models with evolution algorithm, replicating AutoML techniques from other researches
with promising results in the financial context.
3.2.2 APPLICATION:
This project aims to provide stock price predictions based on the latest machine learning
technologies to all retail investors. A mobile web application is developed to provide
predictions in an intuitive way. Different models’ performance and accuracy can also be
compared. The application also serves as another user interface (UI) in visualizing results
from the research apart from Jupyter notebooks with lots of tables and graphs
Figure 3.3 Linear regression method to evaluate and predict the market trend
8
Inspired by the increasing popularity of deep learning algorithms for forecasting
application, these algorithms might serve as potential tools to find hidden patterns in the
trend of stock prices, this information could be useful to provide extra insights for retail
investors when making investment decisions. Therefore, this final year project aims to
investigate the usefulness of deep learning algorithms in predicting stock prices and
democratize such technologies through an easy to use interface for the general public.
9
CHAPTER 4
TECHNOLOGY USED:
10
CHAPTER 5
METHODLOGY DESIGN
The architecture of the system follows a client-server model ,where the server and the
client are loosely coupled.
11
After relevant stock data are retrieved from the third-party data provider through the cloud,
the backend pre-processes the data and builds the models. After that, predictions are
made and the prediction results will be stored on another cloud, which can be retrieved
from the mobile application. The advantages of the loosely coupled architecture include
improved scalability and ease of collaboration. The workload for the cloud which serves
the models and the one which serves the mobile application will be very different. One
cloud serves the model prediction results, which are simple text files; another cloud
serves the mobile application with a lot of rich user content such as images and large UI
libraries. Having two clouds to adapt to two different demand patterns is more efficient,
especially since cloud providers these days usually serve content on demand. Also, these
parathion allows different team members in the team to focus on different parts after
agreeing on a common interface. It speeds up development as team members
responsible for different parts of the system do not need to take care of the under lying
implementation details. Also, it is easier to swap out different components, e.g. to replace
the models the team could simply make changes to the backend, while the frontend
remains unaffected.
12
5.2 PROBLEM FRAMING:
The problem of the project is set to predict the stock price for the next 10
business days. “10days” is chosen as the time frame as short term price movements tend
to depend more on trend momentum and price pattern, while long term price movements
depend on the fundament also a stock (e.g. company management capabilities, revenue
model, market demand, macroeconomic factors, etc.). The loss function of the training
algorithm is the mean squared error of the 10 predicted stock prices. The training
algorithm or optimizer is set to minimize its value, and it serves as the basic performance
metric for comparing different models. Other scores are defined to provide more in-depth
in sights on a model predictability performance and finance-domain-based comparisons
between models for investors. Two different prediction approaches are mainly tested,
predicting the stock prices for the next10 days directly and predicting the stock price of
the next day 1 at a time. It is suspected that the two different problem framing approaches
will result in different abstractions learn performance for different use-cases.
5.4.1 MOTIVATION:
Apart from the mean squared error that a model tries to minimize, different
finance-specifics cores are introduced to evaluate and compare performance of different
models, namely model accuracy score, model trend score and stock buy/sell score. The
scores are also designed to convey useful and meaningful messages to help investors
13
understand a stock and make investment decisions.
5.4.2 DEFINITION:
In this project, the test set is defined as the last 100 days stock price.
To clearly explain the performance evaluation rationale, the following symbols are
defined.
“Snakes” is defined as 10-day disjoint prediction segments in the test set, which will be a
set of 10“snake”. It includes the actual prices and the predicted prices for the last
100days.
It is named as “Snakes” because intuitively the 10-day disjoint segments look like
snakes when being plotted on a graph of historical prices.
5.5 MODEL:
Different common neural network models are tested, including dense neural network,
simple recurrent neural networks (RNNs), Long short-term memory networks(LSTMs)and
gated recurrent unit networks (GRUs).Different model architectures are tested by
changing the number of hidden layers, the number of hidden units per hidden layer, and
the activation function or recurrent activation function used in each hidden layer. All
recurrent neural networks, RNNs, LSTMs, and GRUs, are set to have the recurrent neural
networks same high-level architecture (Figure2.2), a stack of recurrent layers by passing
14
the full output sequence to the next layer, followed by a stack of dense layers.
15
5.6 Functionality accessible by normal users and advanced user
16
5.6.2 USER JOURNEY:
First of all, users need to login to use the system, as there will be customization options
for different users. Since users might not want to create a separate account just for our
application, it will more convenient if users can log in with their existing social media
accounts. In particular, Facebook login is a good option, since there are over 2 billion
users worldwide. Thus, it might be possible to reach a larger market by adopting
Facebook login. Only the very basic user information like the user name will be collected
by the system. For normal users (advanced user mode disabled), after logging into the
system, they can view the stock list and search from it by stock name.
17
5.7.2 DATA PRE-PROCESSING:
3 Python scripts are written to transform the raw stock prices (.csv files) into
feature vectors, for training, predicting and testing respectively. The scripts take the input
options and the raw stock prices as inputs and produce the correct features by building
the lookback arrays and the moving averages. It concatenates the features into the final
feature vectors, which will be passed to the model for training or testing. The 3 scripts
share common operations in building a dataset except the output size and the range of
dates to build from, so common functions are written to centralize the logic instead of
repeating the same index-calculation-intensive work across functions . Is frequently used
for machine learning tasks because it is much for performant than Python lists ,as NumPy
arrays are implemented as densely packed lists, instead of a dynamic array where the
elements are not stored contiguously. Pandas is a popular framework for pre-processing
time series data. It has various utilities for reading raw input files such as .csv and
transforming time series data to the correct format. Pandas uses NumPy as the
underlying data structure, so it is very convenient to inter operate between the two.
5.7.3 MODEL:
A model base class is used as a common interface for all machine learning
models. All models then have their own model class, specifying model-specific details like
methods to build the model, train the model, use the model and save the model.
To decouple model configurations from software code to provide flexibility and robustness
and save engineering effort as mentioned , each model is defined by a JSON object, which
specifies the model’s architecture and hyperparameters with model options and the model
inputs with input options. A corresponding model can then be created by passing the object
to the model class constructor. The model options specify which machine learning model
to use, and the hyperparameters for the model like the number of hidden layers, the
number of hidden units, activation functions used, as well as optimization algorithms and
loss functions. Some example model options are in Appendix A.
18
5.7.4 TRAINING:
In training, a randomized initial model is first generated from the model
options definition. A training set is generated by the build training dataset script, which
generates the training set features from the input options and the raw stock price data.
Then, the data is fed into the model for training.
5.8.4 COMPONENT:
The whole application is broken down into the following hierarchy of components.
At the top level, the App component brings everything together. If the user is not logged
in he/she will be directed to the login page (Login Page).The router component (Router)
controls where the user will end up at, including the home page(Home Page), which is the
default starting point for users with a list of stocks and a search bar, all broken down into
separate components Other components include the details page (Detail Page), which is
where details about a stock price, including the stock price chart, a list of models with a
model score attached to each model, along with a buy/sell score that indicates the overall
predictions for whether the stock should be purchased or sold, are included in.
20
Figure 5.8 Component Diagram
21
5.9 FINDINGS
5.9.1 GENERAL FINDINGS:
The following are some general findings from testing out different machine
learning models.
Figure 5.9 1-day interval historical predictions (GE, Dense Neural Network)
22
From Figure 5.9, it shows that the 1-day interval historical predictions line follows closely
with the historical prices. The graph looks like the prediction line is just 1 day shifting from
the historical prices, similar to a shifted and smoothed out historical prices line. Therefore,
the shape of the historical predictions line is similar to the shape of the exponential moving
averages (EMA), where the price changes from ttot+1 heavily depends on the direction
historical prices. Other models in predicting stock prices of other stocks also show similar
results. Although price reflects all available information, the magnitude of price changes in
the future might need other data for forecasting purpose, such as market sentiment
company announcement, retail and institutional investors’ attention on the company, etc.
This is one of the possible explanation of why the 10-day interval prediction might have a
large difference to actual values as there are potential shifts in market momentum.
Therefore, the price might be too compact and other information is required to make a
23
Figure 5.9 10-day interval historical predictions (GE, Dense Neural Network)
24
From Figure 5.9 it shows that the 10-day interval historical predictions line do not follow
closely with the historical prices but could demonstrate the trend. For example, historical
predictions 1, 2, 3, 4, 7, 8, 9, 10 provided insights on the correct market direction, yet the
magnitude did not match the actual price movements. A possible reason for this error can
be the 10-day interval prediction has to predict more values while having fewer data
compared to the case of 1-day interval prediction, which for 1-day interval prediction, data
of close prices until previous day are available. Therefore, a longer period of interval
prediction could subject to greater changes in market fundamentals, including market
news, macroeconomic factors, earning reports, etc. Other models in predicting stock
prices of other stocks also show similar results.
As mentioned in approaches are tested in predicting the stock prices for the next
10days, predicting all 10-day stock prices directly and predicting each stock price one at
a time. The 2 different approaches frame the problem totally differently, which introduces
a significant language bias. According to the results (e.g. Figure 6.2a and 6.2b), for most
stocks, most models that predict10-day stock prices directly have a higher error than
predicting individual stock price. However, the errors in predicting different days in the
future are relatively constant for models thatpredict10-day stock prices directly, while the
error increases with the time from now for models that predict stock prices one day at a
time.
25
Figure 5.9 Prediction error in predicting stock price at different future
dates(GOOGL, 10-day predict)
26
CHAPTER 6
TESTING
27
CHAPTER 7
RESULT:
This is the login page of the project . Enter the http link in the google chrome ,then the
login page will be appear .Enter the company tricker symbol and submit by clicking submit
button
28
FIG 7.2 GRAPH
After submitting the company tricker symbol, it display the prediction graph of the stock
market.
29
DISCUSSION:
30
8 .CONCLUSION AND FUTUER WORK:
31
based on the previous stock prices. Other features could being corporated, such as market
news and sentiment .Combined with the development of more advanced machine learning
techniques, the accuracy of the information provided to retail investors might be improved
significantly. Second, a larger scale of evolution with larger population size and more
iterations could also be tested for achieving better results. Model inputs can also be
included into the evolution algorithm as a variable to optimize. Regularized evolution [38]
can be tested to eliminate old models regardless of their accuracy, which could allow the
algorithm to search for more distant models in the search space. Third, it is also possible
to use more finance-specific scores, like those introduced, as the objective function
instead of simple mean squared errors to achieve better results. Fourth, mobile
applications with better presentation of stock price predictions could be developed to help
investors understand the implications of the stock price predictions, e.g. when to buy or
sell. This would allow investors to make more informed decisions based on the machine
learning models and truly democratize machine learning technologies, which were
believed to be only in the hands of very few people.
32
REFERNCE
[1] “Survey Finds Hong Kong Securities Market Attracts Wide Range of Investors,”
HKEX, 13 Jul2017;http://www.hkex.com.hk/news/news-
release/2017/170713news?sc_lang=en. Y. Dai and Y. Zhang, “Machine Learning in
Stock Price Trend Forecasting,” Stan ford University;
http://cs229.stanford.edu/proj2013/DaiZhang-
MachineLearningInStockPriceTrendForecasting.pdf.
[2] J. Patel, S. Shah, P. Thakkar, and K. Kotecha, “Predicting stock and stock price
index movement using Trend Deterministic Data Preparation and machine learning
techniques, ”Expert Systems with Applications: An International Journal, Vol. 42, Jan.
2015, pp. 259-268
[3]B. Wanjawa and L. Muchemi, “ANN Model to Predict Stock Prices at Stock
Exchange Markets,” arXiv:1502.06434 [q-fin.ST], 2014
[4] D. Mandic and J. Chambers, Recurrent Neural Networks for Prediction, Wiley, 2001
[5] R. Williams and D. Zipser, “Gradient-based learning algorithms for recurrent
networksandtheircomputationalcomplexity”,inBack-
propagation:Theory,ArchitecturesandAppli-
Cations, Hillsdale, NJ: Erlbaum, 1992, pp. 433 - 486
[6] S. Hochreiter, Y. Bengio, P. Frasconi, J. Schmidhuber, “Gradient flow in recurrent
nets: the difficulty of learning long-term dependencies”, in A Field Guide to Dynamical
Recurrent Neural Networks, S. C. Kremer and J. F. Kolen, eds., IEEE press, 2001
[7] S. Hochreiter and J. Schmidhuber, “Long Short-term Memory”,Neural Computation,
vol. 9,no. 8, pp. 1735 - 1780, 1997
[8] K. Cho et al., “Learning Phrase Representations using RNN Encoder-Decoder for
Statistical Machine Translation” , arXiv:1406. 1078 [cs.CL], 2014.
[9] W. Gail, G. Yoav, and Y. Eran, "On the Practical Computational Power of Finite
PrecisionRNNs for Language Recognition", arXiv:1805.04908 [cs.NE], 2018
[10] J. Chung, C. Gulcehre, K. Cho and Y. Bengio, "Empirical Evaluation of Gated
RecurrentNeural Networks on Sequence Modeling". arXiv:1412.3555 [cs.NE]. 2014
[11] E. Real, et al. “Large-Scale Evolution of Image Classifiers,”arXiv:1703.01041
33
[cs.NE]. Jun2017.
[12] D. Alajbeg, Z. Bubas and D. Vasic, “Price Distance To Moving Averages And
SubsequentReturns”, International Journal of Economics, Commerce and
Management, Vol. V, Dec 2017,pp. 33 - 47
[13] Progressive Web Apps, Google.
Available:https://developers.google.com/web/progressive-
web-apps/
[14] Neoteric, “Single-page application vs. multiple-page
application”, Medium. 2016.
Available:https://medium.com/@NeotericEU/single-page-
application-vs-multiple-page-application-2591588efe58
[15] Keras: The Python Deep Learning library, Keras. Available:https://keras.io/.
34
[23] Cloud Storage, Google. Available: https://firebase.google.com/docs/storage/.
[24] Getting Started, The Investors Exchange.
Available :https://iextrading.com/developer/docs/.
[25] Cloud Functions for Firebase, Google.
Available:https://firebase.google.com/docs/funct
on/.
[26] Cloud Fire store, Google. Available: https://firebase.google.com/docs/firestore/.
[27] React – A JavaScript library for building user interfaces, Facebook Inc;https://reactjs.org/.
[28] React Router: Declarative Routing for React.js, React Training.
Available:https://reacttraining.com/react-router/web/guides/philosophy.
[29] Read Me - Redux, Redux. Available: https://redux.js.org/.
[30]Immutable collections for JavaScript, Facebook Inc.
Available:https://github.com/ face book/immutable-j s/.
[31] Introduction - Material Design, Google. Available :https://material.io/design/introduction/.
[32] Material UI, Material UI Team. Available :https://material-ui.com/
35
APPENDIX
A. SOURCE CODE:
Predict stock:
import os
import sys
import requests
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
FILE_NAME = 'historical.csv'
def get_historical(quote):
# Download our file from google finance
url =
'http://www.google.com/finance/historical?q=NASDAQ
%3A'+quote+'&output=csv'
r = requests.get(url, stream=True)
if r.status_code != 400:
with open(FILE_NAME, 'wb') as f:
for chunk in r:
f.write(chunk)
return True
def stock_prediction():
dataset = np.array(dataset)
model.compile(loss='mean_squared_error',optimizer=
adam')
model.fit(trainX, trainY, nb_epoch=200, batch_size=2,
verbose=2)
38
Prophet:
import pandas as pd
import numpy as np
import pandas_datareader.data as web
from fbprophet import Prophet
import datetime
from flask import Flask, render_template
from flask import request, redirect
from pathlib import Path
import os
import os.path
import csv
from itertools import zip_longest
app = Flask(__name__)
@app.after_request
def add_header(response):
"""
Add headers to both force latest IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=0'
return response
@app.route("/")
def first_page():
"""
original_end = 175
forecast_start = 200
39
stock = "IBM"
return render_template("plot.html", original = original_end, forecast = forecast_start,
stock_tinker = stock)
"""
tmp = Path("static/prophet.png")
tmp_csv = Path("static/numbers.csv")
if tmp.is_file():
os.remove(tmp)
if tmp_csv.is_file():
os.remove(tmp_csv)
return render_template("index.html")
def get_historical_stock_price(stock):
print ("Getting historical stock prices for stock ", stock)
40
df_whole = get_historical_stock_price(stock)
df = df_whole.filter(['Close'])
df['ds'] = df.index
#log transform the ‘Close’ variable to convert non-stationary data to stationary.
df['y'] = np.log(df['Close'])
original_end = df['Close'][-1]
model = Prophet()
model.fit(df)
num_days = 10
future = model.make_future_dataframe(periods=num_days)
forecast = model.predict(future)
#Prophet plots the observed values of our time series (the black dots), the forecasted
values (blue line) and
#the uncertainty intervalsof our forecasts (the blue shaded regions).
#forecast_plot = model.plot(forecast)
#forecast_plot.show()
41
viz_df = df.join(forecast[['yhat', 'yhat_lower','yhat_upper']], how = 'outer')
viz_df['yhat_scaled'] = np.exp(viz_df['yhat'])
#close_data = viz_df.Close.tail(plot_num)
#forecasted_data = viz_df.yhat_scaled.tail(plot_num)
#date = future['ds'].tail(num_days+plot_num)
close_data = viz_df.Close
forecasted_data = viz_df.yhat_scaled
date = future['ds']
#date = viz_df.index[-plot_num:-1]
forecast_start = forecasted_data[-num_days]
if __name__ == "__main__":
app.run(debug=True, threaded=True
42
prophet without flask:
import pandas as pd
import numpy as np
import pandas_datareader.data as web
from fbprophet import Prophet
import datetime
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize']=(20,10)
plt.style.use('ggplot')
def get_historical_stock_price(stock):
print ("Getting historical stock prices for stock ", stock)
def main():
43
stock = input("Enter stock name(ex:GOOGL, AAPL): ")
df_whole = get_historical_stock_price(stock)
df = df_whole.filter(['Close'])
df['ds'] = df.index
#log transform the ‘Close’ variable to convert non-stationary data to stationary.
df['y'] = np.log(df['Close'])
model = Prophet()
model.fit(df)
future = model.make_future_dataframe(periods=num_days)
forecast = model.predict(future)
#Prophet plots the observed values of our time series (the black dots), the forecasted
values (blue line) and
#the uncertainty intervalsof our forecasts (the blue shaded regions).
forecast_plot = model.plot(forecast)
forecast_plot.show()
44
fig = plt.figure()
ax1 = fig.add_subplot(111)
# ax1.xaxis_date()
ax1.plot(viz_df.index, viz_df.Close)
ax1.plot(viz_df.index, viz_df.yhat_scaled, linestyle=':')
ax1.set_title('Actual Close (Orange) vs Close Forecast (Black)')
ax1.set_ylabel('Closing Price in Dollars')
ax1.set_xlabel('Date')
plt.savefig('graph/prophet.png', bbox_inches='tight')
plt.show()
if __name__ == "__main__":
main()
45
INDEX HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Stock Value Prediction </title>
<link rel="stylesheet" href="../static/style.css">
</head>
</html>
HTML PLOT:
<html>
<head>
<meta charset="utf-8">
<title> Prediction Results </title>
<script src="/static/js/dygraph.js"></script>
<link rel="stylesheet" href="../static/style_result.css">
<link rel="stylesheet" href="/static/css/dygraph.css"/>
</head>
46
<h6>
<object class = "summary" data="../static/summary/{{stock_tinker}}.txt"
style="width:85%; height:40%;" ></object>
</h6>
<td>
<font color="grey">{{ stock_tinker }}</font>
</td>
<td>
<font color="grey">Last Closing Stock Value</font>
</td>
<td>
<font color="grey">Predicted Stock Value</font>
</td>
</tr>
<tr>
<td></td>
<td>
<font color="grey">{{original}}</font>
</td>
<td>
<script type="text/javascript">
</script>
</td>
</tr>
47
</table>
<script type="text/javascript">
if( {{original}} - {{forecast}} < 0)
{
document.write("<center><b><font color=\"green\"><font
size=\"5\">BUY</font><\/font></b></center>");
}
else
{
document.write("<center><b><font color=\"red\"><font size=\"5\">SELL - if stock
is owned </font><\/font></b></center>");
//document.write("<center><b><font color=\"red\">Sell - if stock is
owned<\/font></b></center>");
//document.write("<center><b><font color=\"green\">Short - if stock is not
owned<\/font></b></center>")
document.write("<center><b><font color=\"green\"><font size=\"5\">SHORT - if
stock is not owned</font><\/font></b></center>");
}
</script>
<table class="container">
<tr>
<td>
<div id="graph" style="width:1000px; height:500px;" class="graph"></div>
</td>
<td>
<div id="graphLegend" style="width:20px; height:3px;" class="graphbox"></div>
</td>
</tr>
<tr>
<td>
<div class = "labels">
Show Data:
<input type=checkbox id="0" checked onClick="change(this)">
<label for="0"> <font color="008000">Actual</font></label>
<input type=checkbox id="1" checked onClick="change(this)">
<label for="1"> <font color="#000080">Forecasted</font></label>
</div>
</td>
</tr>
</table>
<script type="text/javascript">
g2 = new Dygraph(
48
document.getElementById("graph"),
// CSV or path to a CSV file.
"{{ url_for('static', filename='numbers.csv') }}", // path to CSV file
{
visibility: [true, true],
labelsDiv: document.getElementById("graphLegend")
} // options
);
setStatus();
function setStatus() {
document.getElementById("visibility").innerHTML =
g2.visibility().toString();
}
function change(el) {
g2.setVisibility(parseInt(el.id), el.checked);
setStatus();
}
</script>
<div><marquee>
<table class="newsbox" scrollamount="1" >
<tr>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px" font-
family: "Comic Sans MS" href="https://www.cnbc.com/2017/12/03/bitcoin-hits-all-time-
high-above-11700-as-recovery-accelerates.html" target="_blank" ><font
color="808080"><b>Bitcoin hits all-time high above $11,700 as recovery
accelerates</font color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="http://beta.latimes.com/business/la-fi-markets-20171129-story.html"
target="_blank" ><b><font color="808080">Tech stocks drop steeply, offsetting bank and
healthcare shares' rise</font color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="https://www.cnbc.com/2017/11/30/amazon-gets-its-most-bullish-call-yet-1500-
price-target.html" target="_blank" ><b><font color="808080">Wall Street is giddy over
Amazon shares, gets its most bullish call yet: $1,500 price target</font color></b></a>
49
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="http://fortune.com/2017/03/31/amazon-stock-trillion-dollar-company-apple-tesla-
google/" target="_blank" ><b><font color="808080">Amazon and the Race to Be the First
$1 Trillion Company</font color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="https://www.forbes.com/sites/timworstall/2014/04/13/fun-number-apple-has-twice-
as-much-cash-as-the-us-government/#790e34d75570" target="_blank" ><b><font
color="808080">Apple Has Twice As Much Cash As The US Government</font
color></b></a>
</div>
</td>
</tr>
</table>
</marquee>
<marquee direction = "right">
<table class="newsbox" scrollamount="1">
<tr>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="http://www.latimes.com/business/hiltzik/la-fi-hiltzik-cvs-aetna-20171204-
story.html" target="_blank" ><b><font color="808080">CVS and Aetna say their huge
merger will be great for consumers. Here's why you should be skeptical</font
color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="https://www.cnbc.com/2017/12/01/amid-tax-bill-euphoria-one-big-part-of-the-
stock-market-is-getting-left-behind-tech.html" target="_blank" ><b><font
color="808080">Amid tax-bill euphoria, one big part of the stock market is getting left
behind: Tech</font color></b></a>
</div>
</td>
<td>
50
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="https://www.nytimes.com/2017/12/04/business/dealbook/broadcom-
qualcomm.html?rref=collection%2Fsectioncollection%2Fbusiness&action=click&content
Collection=business®ion=rank&module=package&version=highlights&contentPlace
ment=5&pgtype=sectionfront" target="_blank" ><b><font color="808080">Broadcom
Puts Qualcomm on the Clock</font color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="https://www.reuters.com/article/us-usa-stocks/dow-hits-record-as-investors-bet-
on-tax-cuts-idUSKBN1DY1EP" target="_blank" ><b><font color="808080">Dow hits
record as investors bet on tax cuts</font color></b></a>
</div>
</td>
<td>
<div>
<a style="display:block;color:black; width: 200px; margin-left: 20px"
href="http://www.businessinsider.com/meet-the-paypal-mafia-the-richest-group-of-men-
in-silicon-valley-2014-9" target="_blank" ><b><font color="808080">Meet The PayPal
Mafia, The Richest Group Of Men In Silicon Valley</font color></b></a>
</div>
</td>
</tr>
</table>
</marquee>
</div>
</body>
</html>
51
B .OUTPUT:
52
B.3 OPEN THE LINK IN THE BROWSER
53
B.5 OUTPUT OF THE GRAPH
54