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
Post a Comment