Visualizing Stock Data With Candlestick Charts in Python

NeuralNine · Beginner ·🛠️ AI Tools & Apps ·6y ago

Key Takeaways

This video tutorial by NeuralNine demonstrates how to visualize stock data using candlestick charts in Python, utilizing libraries such as Pandas, Matplotlib, and MPL Finance. The tutorial covers installing necessary libraries, importing them, and using them to load and visualize stock data from Yahoo Finance API.

Full Transcript

what is going on guys welcome to this Python tutorial for Finance in today's video we're going to visualize stock data using Python with so called candlestick charts candlestick charts are just a very efficient way to or a very good way to visualize stock data because each individual candlestick in this chart here represents or visualizes four values at the same time so this is a counseling charge for the Apple share price and as you can see each day has a certain candlestick that is either red or green and it represents four values these four values are the open the high the low and the close so the open value is basically the value which the share or the stock has when the markets open and of course the close value is the price that the stock has when the markets close and in between that time of the opening and the closing of the market this stock can can go up and code can go down and when it reaches its maximum point of the day this is the high value and the lowest point the minimum point of the day is the low value so we can say our markets or the markets open and our stock starts at 100 US dollars then over the course of the day it goes down to 80 dollars then it goes up to 160 dollars and then closes and 140 dollars for example this would be this candlestick or this movement could be represented by this candlestick for example which would be a green one because the markets open at a certain price and close at a higher price this is a positive movement an upward movement which means we have a green candlestick in case we have a red candlestick or in case the markets open a certain price and close and a lower price we have a downward movement which means that we have to plot a red candlestick because the stock went down and by using these candlesticks we end up with a chart like this over the course of multiple days weeks months or years and we can visualize the stock data and each single day or each individual day as a candlestick that shows the volatility of this day of the stock this at the particular day we can see the maximum value and the lowest value the open and close and these charts are just used most of the time when visualizing stock data so let's start with the coding first of all we need a couple of libraries that we need to import maybe you have some of them already installed but if not just open your command line and install the PAC just using pip so if you have ordinary Python you can just type in pip install into package names or if you have a certain and a Kannada environment you can activate it first activate my case neural nine and then you can use the pip in here to install the packages and the packages we're going to need are first of all pandas which we will need for dealing with data frames and stuff also we're going to need panas data reader because this is the library that we're going to use to download our data from the web from the API we're also going to need matplotlib since we're going to visualize the data and we're going to show plots and stuff but in particular we're going to need MPL finance as well because this is the library that allows us to actually plot the candlestick chart because map table itself does not have a function that offers plotting account stick chart and I think that's it what you could also install is maybe numpy if it does not get installed automatically because pandas actually and also map level it build on nan pi but maybe you won't need it so the most important modules are pandas pandas data reader and PL finance and matplotlib I think that's it and we can start with the coding so you open a new file and let's call this candlestick chart and the first thing that we need to do is of course import the libraries that we're going to use in our case we're going to need daytime this is a module or a library of core Python and we're going to give a deal alias of DT then import panas data reader as web also we're going to need map table PI plot the basic module for plotting SPO T and we're going to need matlab dot dates because we're going to need to convert our dates into a specific format later on and last but not least we're going to need MPL finance or we're going to need the method candlestick dot o h LC which means open high/low close notice that we have another type of candlestick chart here OCH L which is opened close high-low its the difference is just the order of the values so we're going to use open high/low close which will be important because we're going to restructure the data frame later on and we need to put our data in this specific order to plot it so first of all let's start with defining our time frame we need to define two dates in in between which we want to plot or look at the data we plot the data in this time frame so let's write a comment here define time frame and we'll need a start date and an end date so the start date we define by using the date/time function of the date/time module so DT date time and in here we can just put in three parameters we start by the year or we start with the year the month and the day so in this case we would start with the first of January 2019 you can actually pick whatever date you want you can also go back to 2015 or 2001 or to whatever you want but this might be a problem if you pick a company that has not existed back then for example you could go with Facebook and you can enter 2002 but Facebook did not exist 2002 so you got an error message but I'm going to go with 2019 because I want a quite short time frame so then I can look at the data in more detail then let's to find the end date you can also define a custom end date here for example maybe you just want to look up until February or March but I usually go with the now function here which means that the endpoint or the aunt date is the moment right now which in this case is the 21st of August and you can go with whatever timeframe you want but I'm going to pick this one so first of January 2019 up until now so in the second step we're going to load our data and to do this we're going to need the panas data reader module so let's define our new data frame you can call it data you can call it DF whatever you want and we're going to need the data reader of the panas data reader module so we write web dubbed a Torito now here we need to pass four parameters and the first parameter is the ticker symbol of the stock we're interested in and we can pick whatever stop we want for example we could go with Apple but we don't need to pass more we can't just pass the main Apple or Facebook but we need to pass the ticker symbol off this particular company and in order to to know the ticker symbol you can just use Google or you can use the Yahoo Finance API so you go to financed or yahoo.com and then you can just write the name of your company for example face book and you can see the symbol of Facebook is FB or you can go with Apple and you can see a a PL or Amazon and you can see AMZN whatever you want you just put in the name of the company and you look for stock symbol alternatively of course you can also use just Google you can find symbols pretty easily so we're going to go with Apple here so AAPL the second parameter is the Finance API that we're going to use and in our case we're going to use the Yahoo Finance API which means that we have to pass a string Yahoo and the last two parameters are actually quite simple it's just a start date and the end date so by doing that we get a data frame downloaded into our script which has the stock data of Apple from the start date up until the end date so we can go ahead and print the data frame sorry charge and we'll see that we have all the data here structured in a specific way we have the date column which is our index column with the individual dates and we have all kinds of columns here high and low in between we have open close and then we also have the volume and the adjusted close if you want to take a look at the columns you just print data columns and we will get an array or a list of the columns so high-low open closed volume and adjusted closed now for our candlestick function we only and we only need four of those values high open low and close and to that we just restructure our data in a specific way so restructure data and what we do is we define our data frame to be our data frame but just for specific columns namely open hi low and close it's important that we keep this order here we need it to be in the order open high/low close because if you swap two columns you for example open low high close the chart will look completely different because the function candlestick ohlc takes the data in or assumes that the data is in this particular order so it's very important that we put the values or the column names in that order here now what we have is the data frame with the date column and only those four columns left so we don't have a volume and we don't have an adjusted closed value anymore but in order to plot our data we also need the date the date column in a specific format because right now the date column as we saw earlier on is in the date format but for our function we need it to be in the number format in a numerical format and to do that we need to convert it but since our data column is or the date column is now the index column we cannot manipulate it so the first thing that we need to do is to reset the index and we're going to pass the parameter in place equals true which just means that we replace the actual or the current data frame by the new one which has now reset the index because otherwise we would need to write data equals data and don't resent index but instead of doing that we just pass this parameter or set this parameter to true and now we could go ahead and print our data frame or the hat and we will see that our date column is no longer the index no sorry this is still being printed here but you can see that the date column right now says it's an individual column which is not the index column because the index column is just now counting from zero upward until the end of the until just the end of the data frame so what we now can do is manipulate the date column so the next step is to map a certain function onto our date values so we say the date column is now the date column and we're going to use a map function to map a specific function of the dates the dates module from map table so we write M dates dot dates to num so what we do here is we take each entry of the date column and map this function onto it the date - num function is just converting data from the date format into the numerical format and by using the map function we just apply this function to every entry every single entry of our date column so now we're good to go we can print one more time to see how it looks like right now and you can see that now our date has a numerical format we cannot see the day format anymore we just have numbers that our function will be able to work with now the next step is just plotting the data it's not allowed to do any more we're just going to plot the data in a very simple way first and then we're going to take care about the style or take care off the style because first of all we just want to put our accounts tick chart out there and then we can adjust colors and titles and all that stuff so visualization so first of all we need to define a and axis here which is basically just a subplot don't ask me why it's called axis I don't know it's just a convention but basically when you define a cell plant you you usually give it a name ax so we just defined a new suppler why are we doing this because the candlestick function takes is the first parameter a subplot so we need to pass the subplot to our function otherwise we wouldn't need it but we're just going to define it right now and after defining this subplot the next thing that we need to do is call a function called x-axis underline date because this function indicates or says that our x-axis will be used for the dates so our dates which are now in number format are going to be again convert it into date format format ellipse so that we can plot the dates because we don't want our numbers to be on the x-axis but we want actual dates so that we know which day we're talking about but we still need the number format for our Candlestick functions so by using this function we just define that matplotlib visualizes the data width or labels the data with the actual date format and finally we can use the Candlestick ohlc function to plot our data so the first parameter as a set is the subplot and the second one is the data we actually want to plot so we write data dollar values by referring to the values attribute we just got the columns and the function uses the first column the date column has the x-axis and the the open high low and close values for the candlesticks we could actually go ahead and just print it or it plot it as it is right now so PLT dot show but you'll notice that it looks quite ugly at least that's how I think it is because you can see first of all we have red and black there way too thin and we have a white background and basically it it looks shitty so the next step or the final step is now to take a little bit care of the design and style of our plot so we have a grid and we have a dark background and we can choose the colors for upward and downward movement and this is what we're going to do right now first of all let's activate a grid here so X dot grid and we can set it to true this will take care of the grid and the next thing that we're going to do is to put the grid below the candlesticks because right now if we would do it like that our grid would go over our candlestick chart but we wanted to go behind it we wanted to put it one level or one layer behind our actual candlesticks and in order to do this we just use the function set axis below and we set it to true now we have now we're done with the grid so what's left is taking care of the colors and as I said I prefer black or dark colors and because I want my candlestick chart to look like this in the end if you prefer light colors or lighter colors you can go with whatever you want you can use the same function and set different values but I'm going to go with black so the next function that we're going to use is the set face color function and we're going to set the face color to black the face color is basically the background of our plot so what was white will now be black but at the same time we're also going to set the face color of the figure to a pretty dark grey I'm going to show you what this looks like in a second we can pass hex code here as well we don't have to write out the color names because these are predefined colors but we can also go with hex codes here so I'm going to go with one two one two one two which is a pretty dark grey and when we now plot the chart we'll see that the first face color let me see the first face color is the background of the actual plot here it's completely black and what we have here is the figure face color which is pre dark gray but as you notice right now we cannot really see anything from from tickers here we cannot see the price we cannot see the the date and also the colors in the candlestick itself are not very beautiful so we're going to set our tickers or the tick parameters to a white color so ax don't tick param is the function we're going to use here and we define the taxes to be the x-axis and we set the colors to basically we could go with white and we do the same thing for the y-axis now the last thing that we need to do is to set the width of the candlesticks and also the color for the upward movement because the downward movement is already read but we want the upward movement to be agree so first let's go with the width of I like 0.5 to 1 you can choose whatever you want and the last parameter that we're going to set is the color up and we're going to set it to G which means green and finally it looks like this pretty beautiful actually I'm not using the predefined green I noticed right now because it's quite dark I use a hex code here which is 0 0 FF 0 0 because I like the green bit to be a bit lighter so you can go with whatever color you want you can also go with pink if you want but I think this looks pretty damn awesome so you can see green for upward movement right for downward movement and this is our count stick the last thing that we're missing here is the title which we're going to set right now ax down steps title and we're going to say Apple share price color equals white and we should be done with that yeah as you can see we can now see that it's the Apple share price we have a grid that goes behind our candlesticks we have everything in a nice color and we can use mapped ellipse to zoom into certain time frames for example if we're interested from June up until now we can just zoom into that time frame we can move our chart however you want it's a bit laggy in my computer it's not the newest one and we can analyze these candlesticks just one last optimization that we can take care of is maybe we want to have different different ticker symbols different companies two plots so we can put our ticker symbol in a bearable Apple and then use this variable here and also use it for the title so we can use a placeholder placeholder instead of Apple and then use the format function to inject the ticker and we can go with Facebook right now FB and it should plot the Facebook share price and also we can see FPS in the title so that's it for this video I hope it was helpful to you you could get some value out of it leave comments down below ask questions what you want give the video like if you liked it subscribe if you want to see more and see you in the next video bye [Music]

Original Description

In this Python tutorial for finance, we are visualizing stock data by using so-called candlestick charts. A pretty useful method that allows us to visualize four values at the same time! ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🖥️ My Coding Setup 🖥️ ⌨️ Keyboard: http://hyperurl.co/neuralkeyboard 🖱️ Mouse: http://hyperurl.co/neuralmouse 🖥️ Monitor: http://hyperurl.co/neuralmonitor 🎙️ Microphone: http://hyperurl.co/neuralmicrophone ✏️ Drawing Tablet: http://hyperurl.co/neuraldraw 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 1 of 60

← Previous Next →
Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video tutorial teaches how to visualize stock data using candlestick charts in Python. It covers installing necessary libraries, importing them, and using them to load and visualize stock data from Yahoo Finance API. The tutorial is practical and hands-on, with code examples and step-by-step instructions.

Key Takeaways
  1. Install necessary libraries using pip
  2. Import necessary libraries
  3. Open a new file and start coding
  4. Define time frame using datetime module
  5. Load stock data using pandas data reader module
  6. Pass ticker symbol, finance API, start date, and end date to data reader
  7. Restructure data to include only open, high, low, and close values
  8. Convert date column to numerical format using map function from datetime module
  9. Plot data using candlestick function
💡 Candlestick charts are a useful method for visualizing stock data, allowing for the representation of four values (open, high, low, and close) at the same time.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →