How To Import Stock Prices Data Using Python (Beginner’s Guide)

Investing and trading has become a hot topic recently, we have seen crazy price movements in all markets, especially the stock market. And with all the volatility, you may be thinking.

What if we can analyze these data by using python?

Since python is known for its ability to conduct high-level analysis, we can actually use mathematical analysis on the data, but the first step is to import stock prices.

That is why in this tutorial we will show you how to import stock prices and stock data using python.

If you’re interested in learning more about finance in python we suggest signing up to one of our free courses below.

Importing and managing financial data in python

Affiliate Disclaimer: We sometimes use affiliate links in our content. This won’t cost you anything but it helps keep our lights on and pays our writing and developer teams. We appreciate your support!

1. Import relevant Libraries/Packages

The first step is to import the relevant packages we need, these packages are what provide us the ability to manipulate and use our data.

Although there are many packages available to import stock data.

The package we recommend using is yfinance, which is a popular hassle-free open-source library developed by Ran Aroussi as a means to access the financial data available on Yahoo Finance.

The code below is how we can install and import the yfinance package:

!pip install yfinance
import yfinance as yf

What functions does yfinance have?

yfinance package actually has many functions we can use, a way we can check available functions is by using the dir() function on our package.

The dir() function is basically python’s standard function which helps return a list of the attributes and methods of any object.

The code below is how we can check the packages in yfinance.

dir(yf)

Here is the output:

['Ticker',
 'Tickers',
 '__all__',
 '__author__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__path__',
 '__spec__',
 '__version__',
 'base',
 'download',
 'multi',
 'pdr_override',
 'shared',
 'ticker',
 'tickers',
 'utils',
 'version']

2. Import and explore our stock data

The first step in any data analysis is to explore our data, so let’s analyze Elon musk’s famous Tesla stock.
To analyse the stock data, we first need to check its fundamentals, which basically tells us the main information that reveals the underlying value of a stock.

There are many functions included in the yfinance package to reveal the key information’s, but for simplicity purposes, we will output the key fundamentals, which are the Sector, Price Earnings Ratio, and Beta.

The code below is how we can output the values.

Tesla = yf.Ticker("TSLA")
#Company Sector
print("Company Sector:", Tesla.info['sector'])
#Price Earnings Ratio
print("Print Earnings Ratio:", Tesla.info['trailingPE'])
#Company Beta
print('Company Beta:", Tesla.info['beta'])

Here is the output:

Company Sector: Consumer Cyclical
Price Earnings Ratio: 379.7975
Company Beta: 2.008831

Next, let’s start importing the relevant stuff, which is our stock prices.

To import our stock data we can use the yfinance “download” function.

The code below is how we can output the values, what we want to do here is to call our ticker symbol which is the tesla stock symbol “TSLA” and the relevant periods we need.

tesla_price = yf.download("TSLA", start="2019-01-01", end="2021-11 01",group_by="ticker") 
print(tesla_price)

Here is the output:

Python Exchange Import financial data

What we can see here is the data outputted shows the first 5 and last 5 rows of TESLA stock price and the volume from 2019/01/01 – 2021/11/01.

3. Visualize our stock data using matplotlib

To visualize our stock data, we can use matplotlib.pyplot which is a library that contains useful visualization tools.
This is how we can import the graph, as shown below it is a line graph.

import matplotlib.pyplot as plt

plt.figure()
plt.plot(tesla_price.Open)
plt.title('TESLA STOCK PRICE')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend(['Price ($)'])
plt.xticks(rotation=90)
plt.show()

From reviewing our line graph we can see that TESLA stock price has been significantly increasing over the past years, but to actually review how the price of the stock is performing, we will need to use a candlestick chart.

If you don’t know what a candlestick chart is, it basically visualizes the open, close, high, and low of the stock price during a specified period. The benefit is it provides better visualization of the price action movement of the stock.

4. Graph Candlestick Chart using Mplfinance

Sadly, matplotlib does not offer the ability to graph candlestick charts. To plot a candlestick chart we will have to use Mplfinance.

There are plenty of other packages available to plot a candlestick chart, but the reason why I like Mplfinance is it comes with many other functions such as moving averages, volume analysis any many more. You can learn more on their github.


To use the mplfinance package, we have to firstly install the package using !pip, then import mplfinance as fplt.
Next, we can use its plot function to plot our candlestick chart.


The code below is how we can output the values.

!pip install mplfinance

import mplfinance as fplt

fplt.plot(tesla_price, type='candle', style='charles', title="Tesla Candle Stick Chart", ylabel='Price $')

This is what the chart should look like.

Tesla candle stick chart with python

As you can see the chart is a bit cluttered, this is because of the extended period of start time and end time, so you may get a warning sign saying you are “plotting too much data”.

So it’s better to visualize data on a smaller time frame, or for example for each candlestick, where it can be a “weekly”, or a longer time frame.

let’s adjust our program a bit and add an interval in our yf.download() function so each candlestick represents a week.

tesla_price = yf.download("TSLA", start="2019-01-01", end="2021-11-01",group_by="ticker", interval = '1wk') 

fplt.plot(tesla_price, type='candle', style='charles', title="Tesla Candle Stick Chart", ylabel='Price $')

When you output the line of code it should look something like this:

Tesla candle stick chart with python

See? much better.


Each candle is now represented on a weekly movement, so all the information that we had on a daily basis previously is combined into a weekly candlestick, this allows us to view the overall movements on a better visualization. Whereas, with a daily candlestick we tend to use those on a smaller time frame.


But, it’s still a bit difficult to actually see the values, luckily we have one more trick up our sleeve, which is using fig scale. Fig scale pretty much adjusts the figure of the scale so that it can better visualize the chart. This is the code to add a fig scale, I set mine to 1.5

fplt.plot(tesla_price, type='candle', style='charles', title="Tesla Candle Stick Chart", ylabel='Price $', figscale = 1.5)
Tesla price chart stock chart with figscale

5. Add technical indicators to the stock chart

Now that we’ve completed the chart, let’s add some more indicators to gather more information on the stock chart.

Volume

As mentioned previously, the good thing about Mplfinance is it comes with many technical indicators, one of which is the volume attribute.

You can just set “volume = True” on our fplt.plot function and the graph will automatically place a volume graph underneath our bar chart.

fplt.plot(tesla_price, type='candle', style='charles', title="Tesla Candle Stick Chart", ylabel='Price $', figscale = 1.5, volume = True)
tesla price chart using python showing volume

Moving average

Let’s add another attribute which is the moving average, the moving average visualizes the summary of the stock and reduces the noise within the chart, it’s pretty much an average of the candlesticks and uses a line graph to visualize the changes over time.

The code below shows how you can add a moving average using “MAV”.

fplt.plot(tesla_price, type='candle', style='charles', title="Tesla Candle Stick Chart", ylabel='Price $',figscale = 1.5, volume = True, mav=10)
Tesla candle stick chart with moving average using python

Conclusion

We have used yfinance as a way to import financial data from yahoo, and graphed our output in candlestick charts, and visualized using technical analysis with mplfinance.

You learned how to:

  • Import stock price and data using yfinance
  • Visualise stock price data with mplfinance
  • Add technical indicators on the stock chart using mplfinance

With these powerful tools, you can now go out and see what stock data you can analyze.

If you want to learn more about analysing financial data, we recommend trying our free course by clicking the link below: