Stock Portfolio Visualization with Matplotlib in Python

NeuralNine · Intermediate ·⚡ Algorithms & Data Structures ·6y ago
Today's project is about building a good-looking stock portfolio visualizer in Python using Matplotlib. Blog Post: https://www.neuralnine.com/portfolio-visualizer-with-matplotlib-in-python/ ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 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/

What You'll Learn

The video demonstrates building a stock portfolio visualizer in Python using Matplotlib, covering the implementation of data visualization techniques for portfolio analysis.

Full Transcript

what is going on guys welcome to this Python finance project in today's video we're going to build a stock visualization tool or actually a portfolio visualizer so this is what we're going to end up with on the left you can see a text-based overview of our portfolio and on the right you can see a chart that shows how much percentage or what percentage of the portfolio is in what stocks so for example 40.1% an apple 3.9 in Wells Fargo and so on Goldman Sachs Nvidia Facebook by the way this is not my stock portfolio this is just a sample portfolio and you can of course customize it you can customize the whole tool here you can add some more data on right if you want but basically this is what we're going to build today and before we get into the tutorial let me just mention that we have a blog post on neural nine.com so if you're interested in a text-based version of this tutorial you can check out neural nine.com go to the blog and then check out this blog post now I'm not going to scroll through it because my GPU can handle it for some reason my computer is actually not that bad but still when I scroll this page the whole recording is laggy maybe I can do it a little bit slowly but you can see here we have the text-based version okay actually my recording tool is once again saying encoding overloaded so probably I shouldn't scroll but basically this would we're going to build the neural 9 portfolio visualizer and let us get into the code so the first thing that we need to do is we need to import a couple of libraries first of all daytime as DT which is part of the core Python stack then we're also going to import a matplotlib pipe lot SPL key because this is the visualization library and then we're going to import pandas data reader as WEP which is the tool that we're going to use to load the data into our script now before we can load any data into the script or before we can visualize any data we need to define what data we're interested in so what stocks do your own and how many of those or how many shares so we're going to create four lists here we're going to say tickers which are the ticker symbols so Apple or AAPL FB for Facebook G as for Goldman Sachs and so on and we're going to see amounts then we're going to save prices and then we're going to say told now tickers and amounts we have to specify manually so we're going to say we're going to put the values here manually and the prices is what we're going to load from the web from the finance API and the total is the amounts time the prices so pretty simple actually now we could also let the user input all the tickers in the mount so you could just go ahead and say I don't know some boolean equals true and then you can say while some boolean and you can say I don't know ticker equals input what stock do you want to add then you can say amount equals input how many shares and then you can just go ahead and say ticker dot append up ticker sorry tickers dot append ticker and amount set up an amount but we're not going to do that because unless you're a day trader your stocks are not changing every single day as a long-term investor your hold stocks for like multiple years so what you could do however is you could just define the stocks the tickers and the amounts once then save them into a file and every time add or remove stocks if you want but what we're going to do because we're programmers is we're just going to put this into the code so we're going to say okay let me say we have apples Apple shares here and we have Tesla shares here we have Facebook shares here we have and video shares here and we have Amazon shares here and let's just add Google now if you don't know the ticker symbols feel free to use Google just type the company name for example Facebook ticker symbol or Nvidia ticker symbol or Google or actually alphabet ticker same ticker symbol yes or Tesla ticker symbol then you get these symbols here if you don't know them and now we have to specify the amount so how many Apple shares let's say seven how many tests affairs let's say five how many Facebook shares let's say twelve and video sixteen Amazon two and Google for and what we now need to do is we now need to load the prices so we're going to save for ticker and tickers so for every ticker that we have we're going to create a data frame which is web dot data reader and we're going to specify the ticker and the API that we're going to use in this case the Yahoo Finance API and now we have to specify a time frame now the beginning point is not really important because we're only interested in the last value but we're going to say DT dot day time dot or how is it actually written yeah like that 2019 let's say I don't know the first of August and the end data point is day time dot now which is exactly now so the latest data point will be included and what we now need to do is we now need to determine the price and the price is the last element of the data frame which is minus 1 : and of this element we're interested in the closing value so the last closing value and then we're going to pick the zero F or the first element so this is the prize now what we now need to do is we now need to get the index of that price in order to match this R with the index of the amount so we're going to say prices dot at sorry append the price and now we're going to say index is the prices dot index I think this is how it's written yet the prices start index of that price okay now it's crashing okay of that price and this index that we now have is also the same index of the amount so we're going to say total dot append price time amounts so basically we're downloading the price or determining the price then we're adding it to the prices list and then we're multiplying it with the amount of this our share and actually I think it's not that intelligent to take the price because the price can be are the same let's say it is tickers dot index top ticker because that is unique we should get the same result actually yeah I think this should work and then we get total dot append price times amounts but not the amounts themselves but the amount at the index so this should work this should fill up the prices and the tolls we can check it out by saying print prices and print total and then just run a script we'll see might take a while though because the Yahoo Finance API doesn't always work sometimes it actually crashes so if it doesn't work for you just rerun the script but as you can see it kind of works we get the share prices um this should be pretty accurate for Apple this is accurate for Tesla this is accurate for Facebook this accurate for NVIDIA I don't know the amazon share price and i don't know the google share price but it looks right to me i just know that there are a thousand plus and this is the total value so basically just taking two hundred and ninety-eight no eighty-nine sorry times seven should result in two thousand yeah looks right so this part works so now we have all the values loaded you know script and the next thing that we need to do is we just need to visualize them unless you want to add some metrics unless you want to do some calculations we're done with the data this is a very small part of the whole thing we just want to have a nice visualization so the first thing that we need to do is we need to define the size of the windows so we're going to say figure access equals P LT dot subplots figure size I think was the argument you have fixed size equals 16 times 8 which is basically just making the window a little bit bigger because otherwise we have to always rescale it this is how we define a size and the next thing is that we need to do some Stalag so we're going to say axis dot color set face color is black so we're going to say that the basic background is black but the figure face color so we're going to sing axis down figure dot set face color this will be a little bit lighter so we're going to say one two one two one two in tax code and we're also going to set the ticks the tick parameters we're going to set their color to white so we're going to say access dot sick parents access equals x color equals white and we're going to do the same thing for the y-axis and that should be it I think this is right yes and then we can go ahead and show this so it will not look anything nothing will look impressive here but we're just checking if it looks right so we have basically a black axis here a black plot and a dark grey background and some ticks here we're going to remove these in a second because we're going to plot a different kind of chart here but as the next thing we're going to set a title first so we're going to say axis dot set title set underline title and this title will be neuro nine portfolio visualizer and we're going to adjust some parameters see we're going to say the color is the knurl 9 orange which is ef6 C 3 5 this is the orange of the logo of the current logo maybe I change it in the future and we want to choose a font size of 20 as a numerical value so we can check this out again and after that we're going to start our plotting the pie chart so you can see we have a good heading a good title and the next step is a little bit more complicated now because I use a little bit of unusual code we're going to use the PI function which is actually just a X at PI and we're going to plot the total values of course the total values that we calculated so that we have a pie chart a pie chart is basically giving you the relationships the proportions the percentages of the individual values and we're going to use as labels or don't use it tickers and we're going to defining out a percent parameter this is just the parameter for the percentage the percentage signs which gives you the format in this case we're going to say percentage one point one F percentage percentage you'll see the format in a second in practice and we're going to say P Ct distance percentage distance which basically means how where the percentage lies so just from the format where we put it we're going to say 0.8 so margin you could say this is the margin but we're not just going to use the function like that because we need to change some values so we're going to get the return values of these functions of that function sorry and the return values are patches texts and auto texts and we're not going to use all of them but we're going to say we're going to use a list comprehension here we're going to say text dot set so every text that is in there every text it isn't a return value every text that is in our pie chart we're going to say set the color to white because we have a dark background we want to see something so set the color to right for every text in the text so actually since we're not using the other parameters we could just define an underline here like that it doesn't matter but now we should have a decent pie chart that looks pretty good yeah as you can see we have the pie chart we have the white labels here and we have the percentage values in the right format this is the format that we specified and we also define the percentage distance so that we don't have the values too near to the middle and we're not done yet because what we want to do now is we want to have a ring chart here we want to have this the middle blacked out so we want to have the chart F as we saw it in the beginning this is also the reason why we push the percentages out to the borders but this is for now a pretty good result and now we're getting into the middle so now we need to black out the middle and to do that we're just going to define a circle so we're basically going to put a circle on top of our pie chart to make it a ring chart because we don't have a function for that so we're going to say my circle equals and we're going to say what was it PLT dot circle and this circle has the starting point zero zero and a radius of zero point five five and color equals black and now we're just going to say PLT dot get current axis I think this is what GCA means not sure but I think get current axis and we're going to say add artist my circle so we're basically adding the circle to our plot and as you will see this solves the problem we now have a black circle on top of our pie chart and of course if you know that it it is that way you maybe notice it but if you don't know it it looks like a ring chart so it is exactly what we want it and this is how we produce a ring chart with the individual percentages in Python with metal lip now the next step is to now add the text overview on the left that we saw in the beginning and for that I chose to do it a little bit in my own way which is not probably the most clean way that you can do it but maybe you'll find a better way to do it but basically what I did is I defined the two headings so I said ax dot text starting at a minus 2 and 1 minus 2 being the x coordinate and one being the y coordinate and we're going to decrease one over time since we're going down so I'm saying - 2 1 and then I say portfolio overview so this is basically the heading portfolio overview and we define a font size off 14 and we defined a color off I don't know what color we chose in the beginning but I think it was a yellow or so FF e 536 of course don't forget the hashtag and then we choose the vertical alignment equals center and the horizontal alignment equals centered Center so this basically puts our text in the right position with a centered alignment which is good and then we define a x dot text to be the total amount of dollars again - - but this time - not - sorry 0.85 which is basically subtracting 0.15 so basically just going down a little bit and here we're going to say total let's use an F string your total total USD amount is and then we use a formula we say the sum of total and we specify it sum of tol specify it as a point 2f so basically we're interested in two decimal places and this is how you form it out so you use an F string you put in the string that aesthetic and then use the formula formula for the sum of the total and here in the end after the Kohen you specify how many decimal places you're interested in so this is basically the string of course we can add the dollar sign in the end now we have to specify a couple of parameters for example font size will be 12 and then we have the color equals white point and again we have the horizontal that's vertical vertical alignment equals Center and horizontal alignment equals center so now this is the easy part the next thing is that we want to list all the individual tickers so we need to somehow iterate over all the tickers but also get right position so this is the part where don't know if its death clean or it's actually the way you do it so what I did is I said counter equals 0.15 or you could also say this is the subtractor this is the amount we subtract every time and then I set forth ticker in tickers I just said a X dot txt and every time that I every time that a new ticker was chosen I just decreased the counter by 0.15 so we actually start with minus 2 then we use 0.85 - counter now actually what I do in the end then is I say counter plus equals 0.15 so I'm actually not subtracting it I'm adding it but in the end the counter is the subtractor so the first time we're subtracting 0.15 the next time we're subtracting 0.3 and so on of course we can also go negative because 0 is the sender so if you go negative we're just going to load Center but the text is also the ticker so basically a ticker and after the ticker we specify : and we're interested in total tickers dot index off the ticker so what we're doing is we're saying okay ticker name : and then we're interested in a total value that calculated of the one ticker or actually off the index which the ticker has so we're getting the index of the ticker that we chosen get this index put it into a total list and then we got a total value for that particular ticker and then we can add a dollar sign in the end that's it of course we forgot to format so point 2f what is the wrong place here of course it was there you go um that's basically a text and I'm looking at the code all the time because this is actually quite confusing code here hard to memorize so font size again 12 and a collar will be wide again I think and yeah then again we do vertical vertical a line meant equals Center and horizontal alignment equals Center as well then we increase the counter with every iteration and that's actually it so then we show the plot and this should be it so the last piece of code was a little bit confusing but that is what you then end up with you got the portfolio structured in this ring chart or visualized in this ring chart and then you get the individual values on the left so let's recap the code real quick we load or we specify the tickers and the amounts manually we then load the prices calculate the total values define a plot then set some design stuff set a title then plot a pie chart set the order percentage to the right format so basically with one decimal place then we push these percentages out to the border so that we can put a ring in the middle set the color to white for every text that we have in the labels then we create a circle that we place in the middle by using the GCA method then we specify a heading or a title for the left text-based overview then we add the total amount and then we use an for loop to iterate over all the tickers to also put them into the overview so that's basically it and that's the project so that's it for today's video I hope you enjoyed it I hope you can make use of this portfolio visualizer of course you can tweak the individual parameters you can add some values you can calculate some more values some key statistics to enhance this tool but that's it for today's tutorial I hope you liked it if so hit the like button for me and also feel free to ask questions and give feedback in the comments section down below if you haven't subscribed to this channel yet go and do so to see more future videos so thank you very much for watching and see you in the next video [Music]
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 49 of 60

1 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
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 teaches how to create a stock portfolio visualizer using Matplotlib in Python, enabling viewers to analyze and visualize financial data effectively.

Key Takeaways
  1. Install Matplotlib
  2. Import necessary libraries
  3. Load financial data
  4. Preprocess data
  5. Create visualizations
  6. Customize plots
  7. Deploy the visualizer
💡 Effective data visualization is crucial for understanding complex financial data, and Matplotlib provides a powerful toolset for creating informative and engaging visualizations.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Media Narratives: How Media Shapes Youth Mindset? | Panel Discussion | Fareed Ahmad
Qasim Ali Shah Foundation
Watch →