Skip to main content

Basic Stocks Graph Plotter In Python

 


Plotting Graphs in Python

Python offers a wide range of graphs that can be plotted using the library Matplotlib. We can use the function Pyplot of Matplotlib to visualize data in many forms like Line charts, Bar charts, Histograms, Pie charts and many more. Today we will make a program to draw Line Charts for our Stock data in Python.

This post is in continuation of our previous post where we explained how to collect and store daily stocks data in your database, which you can go over here: Stock Data Collection in Python. We are going to use the stock data collected from the database we had created there, to get a peek at how a particular stock is performing. Skip to the end if you would like to get the free code!

Let's get started!

Modules Required

As mentioned earlier, we are going to work with matplotlib, specifically with the function matplotlib.pyplot. We will also use mysql.connector to connect Python with MySQL. Last but not the least, mysql.connector.errors for error management. mysql.connector.errors come with mysql.connector, so no need to install it seperately.

So go ahead and install matplotlib and mysql.connector, if you don't already, using pip or any other way you prefer.

The Code

Starting off with importing our modules and initializing the Python-MySQL connection, along with defining our cursor for data collection as follows:

We will have the usual command prompt to cater to our input of our desired Stock Symbol, whose records will be accessed using a for loop (for accessing each and every day's data) inside a while loop (for trying the program as many times as we want):

So we are inputting the stock symbol from the user using the variable ticker. Using this symbol we are passing a query to get all data from the table named by this ticker. If you remember from the last post, our program created tables with names as their stock symbols. Also remember that we had enclosed this name inside of a special character called backtick ('  `  '), which is present under the esc key on a standard keyboard:

Position of Backtick on standard keyboards

And for those who haven't understood the use of %s in the query, here's a short explanation: %s is used inside a string where we wish to place a value stored in any variable, but is not possible in a normal way (like in this cursor function). The string is followed by a tuple containing the variable of each %s in the same order they appear in the string. For example:

The output will be: My name is <inputted value of variable 'name'>
Don't forget the % between the string and tuple.

Continuing with our program, we access the data using cursor.fetchall() and run a for loop that appends the price and date of each row in the table to two empty lists prices and dates. These two lists will serve as the data to be plotted on the graph.

Below the for loop, is the code to plot the graph. Note that we have imported matplotlib.pyplot as plt for easy use.

plt.figure(figsize) will determine the width and height of the plot. plt.title sets the given string as title of the plot. plt.plot()  takes the two lists we have created as arguments, the first being the one to be plotted on the X-axis and the following one to be plotted on the Y-axis. plt.xlabel() and plt.ylabel() take the argument strings to be shown what data each of the two axes represent. Finally, plt.show() opens up the plotted graph.

Note that we have a try-except statements under the while loop, under which we performed the entire above code. The program first initiates the code under try, and in case it faces an error, the program comes to execute code present under except, instead of showing an error on the IDLE console, which just everyone hates.

If the user enters a symbol that doesn't exist in our database, then the query which we passed will fail with the error that it couldn't find any table named by the symbol the user has inputted. Therefore it jumps to the except statement, where we use our module mysql.connector.errors. When MySQL can't find a table, it gives the error with error number 1146. On such an occasion, the program will show the stock symbol entered by the user doesn't exist, and starts the program all over again.

The Working

The command prompt:

Command Prompt to input Stock Symbol



The Plotted Graph:

A line chart of dates vs prices



Note: Matplotlib also provides some inbuilt functions for these plots, the ones that you can see below the plot:

Inbuilt Functions of Matplotlib



Find out yourself what these functions do to our graph!

And yet again we have come to the end. This post covered the BASIC program to plot a SIMPLE graph. I will soon post more programs involving more complex Graphs and Plots!

Here's the download link for this entire program: Stock Plotter Program. To start working with this, all you need to do is make sure you have done the tweaks mentioned in the earlier post: Stock Data Collection in Python. Use it however you prefer, tweak whatever you want!

Peace Out.

Comments

Popular posts from this blog

Simple Omegle Bot Using Selenium With Python

Omegle is an online text-based and video-based chatting platform, which allows users from around the world to talk to complete strangers anonymously, for free! The text-based Omegle has a simple concept: Complete a Captcha  verification, connect automatically to a stranger, and after chatting get on to the next stranger. Apart from having a chit-chat with a stranger from the far side of the globe, Omegle poses as the perfect platform for other uses as well. At Omegle, you  can advertise your content, website, products and more for free. With access to about 40,000 strangers using Omegle at any given time, you can benefit if your ideas/advertisement is seen by potential customers. But of course, we can't advertise to each guy we meet again and again. I mean, come on, that's a lot of hard work, even if your message consists of a few words. But worry not, since that's where our Omegle Bot  comes in play. This bot works on a pre-determined set of messages that are to be conveye

Predicting Stock Prices using Machine Learning (XGBoost)

  Today, I'll show you how to create a machine learning program to predict stock prices. Machine learning is used in a variety of fields, and we can utilize its ability to learn and predict from data to predict useful variables, with minimal error. Therefore in theory, we can apply the same on stocks to predict the next closing price, so that we can make a killing gain. However, stock markets are highly unstable. Their price movement often depends on decisions taken by the company, favor and reaction of investors, social impact, human emotions, and price movements of some other related stocks. These types of data cannot be made available to a program. The prediction can be close only if the market remains relatively stable. You don't actually need to learn machine learning using python to understand how this program works, if not minimal. I'll describe each machine learning process. And don't forget to download the source code of this program, link provided at the end.

English Dictionary With Python And Tkinter!

English Dictionary on Python Have you ever tried to read from the small Oxford Dictionaries? Those small yet bulky books have thousands of words cramped on a page the length of your finger! And on top of that, not to forget the hassle of flipping across the pages, searching for your word, God knows where is hiding on which page! Nowadays though, hardly does anyone ever use the classic dictionaries. With the access of technology on our fingertips, one tap on Google, and you would be on with your way.  But how about making a program of your own which can do the same for you? Sounds interesting? Such a program can enable you to run it and keep it opened, while you are reading a book, so that you can search the definition of a new word you encountered. What if you are writing a book, perhaps a report? You know what you are supposed to write, but you choose to get a word for it, so that you sound professional. So you just search for a short definition and the program find the word with matc