top of page
Nikhil Adithyan

Creating Advanced Financial Charts with Python in One Line of Code

Master the most flexible python library to create great-looking financial visualizations



Introduction


The surge of programming and technology being applied into the field of finance is inevitable, and the growth never seems to be declining. One of the most interesting parts where programming is being applied is the interpretation and visualization of historical or real-time stock data.

Now, to visualize general data in python, modules like matplotlib, seaborn, and so on comes into play but, when it comes to visualizing financial data, Plotly would be the go-to since it provides built-in functions with interactive visuals. This is what I thought but there exists one unsung hero which is nothing but the cousin of matplotlib, the mplfinance library.


We all know how versatile the matplotlib package is and comes into handy to plot any kind of data. Even financial charts like candlesticks can also be plotted using the matplotlib package but in vain since we have to do it from scratch. But recently, I came to know that there is a separate module named mplfinance that is designed specifically to create advanced financial visualizations. In this article, we will dive deep into this python library and explore its functions to produce different types of charts.


Importing Packages


Importing the required packages into our python environment is an unskippable step. In this article, we would need a sum of three packages which are Pandas to deal with dataframes, Requests to make API calls and extract stock data, and mplfinance to create financial charts. For those who haven’t yet installed these packages, copy this code into your terminal:



pip install pandas
pip install requests
pip install mplfinance

After finished installing the packages, it’s time to import those into our python environment.



import pandas as pd
import requests
import mplfinance as mf

Extracting Stock Data


Now, that we have imported all the essential packages. Let’s pull the historical stock data of Amazon using an API endpoint provided by twelvedata.com. Before that, a note on twelvedata.com: Twelve Data is one of the leading market data providers having an enormous amount of API endpoints for all types of market data. It is very easy to interact with the APIs provided by Twelve Data and has one of the best documentation ever. Also, ensure that you have an account on twelvedata.com, only then, you will be able to access your API key (vital element to extract data with an API).


Python Implementation:



def get_historical_data(symbol, start_date):
    api_key = 'YOUR API KEY'
    api_url = f'https://api.twelvedata.com/time_series?symbol={symbol}&interval=1day&outputsize=5000&apikey={api_key}'
    raw_df = requests.get(api_url).json()
    df = pd.DataFrame(raw_df['values']).iloc[::-1].set_index('datetime').astype(float)
    df = df[df.index >= start_date]
    df.index = pd.to_datetime(df.index)
    return df

amzn = get_historical_data('AMZN', '2021-01-01')
amzn.tail()

Output:



Code Explanation: The first thing we did is to define a function named ‘get_historical_data’ that takes the stock’s symbol (‘symbol’) and the starting date of the historical data (‘start_date’) as parameters. Inside the function, we are defining the API key and the URL and stored them into their respective variable. Next, we are extracting the historical data in JSON format using the ‘get’ function and stored it into the ‘raw_df’ variable. After doing some processes to clean and format the raw JSON data, we are returning it in the form of a clean Pandas dataframe. Finally, we are calling the created function to pull the historic data of Amazon from the starting of 2021 and stored it into the ‘amzn’ variable.


OHLC chart


An OHLC chart is a type of bar chart that shows open, high, low, and closing prices for each period. OHLC charts are useful since they show the four major data points over a period, with the closing price being considered the most important by many traders. It is also helpful in showing increasing or decreasing momentum. When the open and close are far apart it shows strong momentum, and when they open and close are close together it shows indecision or weak momentum. The high and low show the full price range of the period, useful in assessing volatility. Now to create an OHLC chart with mplfinance, it just takes as low as one line of code:



mf.plot(amzn.iloc[:-50,:])

In the above code, we are first calling the 'plot' function and inside that, we are slicing the OHLC data of Amazon which we just extracted before to just the last fifty readings and the purpose of doing this is to just make the chart more cleaner so that the elements are visible. The above one-liner will produce an output that looks like this:



Candlestick chart


Candlestick charts are used by traders to determine possible price movement based on past patterns. Candlesticks are useful when trading as they show four price points (open, close, high, and low) throughout the period of time the trader specifies. The most interesting part about this type of chart is that it also helps traders read emotions which is the foremost driver of the market itself. To produce a candlestick chart with mplfinance, we just have to add another argument which is the 'type' argument to the 'plot' function and mention 'candle' in it. The code looks like this:



mf.plot(amzn.iloc[:-50,:], type = ‘candle’)

The above code will produce a candlestick chart that looks like this:



Renko Chart


A Renko chart is a type of chart that is built using price movement rather than both price and standardized time intervals like most charts are. The chart looks like a series of bricks and a new brick is created when the price moves a specified price amount, and each block is positioned at a 45-degree angle (up or down) to the prior brick. The primary usage of Renko charts is to filter out the noise and help traders to more clearly see the trend since all movements that are smaller than the box size are filtered out.


To my knowledge, mplfinance is the only python library to offer the Renko chart and the one we are going to see next, and this is the reason why this package holds a strong edge when it comes to financial visualization. Now to create a Renko, we just have to specify 'renko' in the 'type' argument of the 'plot' function. The code for the Renko chart would look like this:



mf.plot(amzn, type = ‘renko’)

We can also add an additional argument to the 'plot' function which is the 'renko_params' argument to modify the brick size to our needs and other similar kinds of stuff but I would prefer the default ones. The above code produces a Renko chart that looks like this:



Point and Figure chart


The Point and Figure chart, shortly known as the P&F chart, is similar to the Renko chart that plot the price movements of assets without taking into consideration the passage of time. Contrary to some other types of charts, like candlesticks, which mark the degree of an asset’s movement over set time periods, P&F charts utilize columns consisting of stacked X’s or O’s, each of which represents a set amount of price movement. The X’s illustrate rising prices, while O’s represent a falling price. The formation of a new column of X’s following O’s or a new column of O’s following X’s occur when the price reverses by the reversal amount.


Functions supporting the Point and Figure chart cannot be found elsewhere but only on the mplfinance library and it also makes the process easier where we can create the chart by just specifying 'pnf' in the 'type' argument of the 'plot' function. The code would look like this:



mf.plot(amzn, type = ‘pnf’)


Adding More Information


The mplfinance package is not just limited to producing different types of charts but also enables us to make those charts more insightful by adding additional indicators like the Simple Moving Average (SMA) and Volume. For those who don’t what these two are, Volume is the number of shares bought and sold by traders during a specific timeframe and the Simple Moving Average (SMA) is nothing but the average price of a specified period of time. It is a technical indicator and widely used in creating trading strategies.


Plotting these data with matplotlib would take a millennium whereas, mplfinance allows us to finish this task with just one line of code. In addition to the 'type' argument, we just have to introduce another two arguments which are the 'mav' argument where we must specify the lookback period of each SMAs, and the 'volume' argument where we must mention 'True' if we want to add the volume plot to our chart or 'False' if we don’t want to. The code to both these indicators would look like this:



mf.plot(amzn, mav = (10, 20), type = ‘candle’, volume = True)

The above code can be modified and experimented with in two ways. The first way would obviously be trying out different types of charts. In the above-represented code, we mentioned our chart type to be candlestick but you can change it to OHLC, Renko, or even P&F chart and observe how each of the charts looks with its two additional indicators. The next way is to play with the 'mav' argument where we can add any number of SMAs with different lookback periods. The output for the above code looks like this:



Saving the plot


If you wonder how to save any of these financial visualizations, just add another argument which is the 'savefig' argument where you just have to mention its file name, and the rest will be taken care of. Let’s say you want to save the above plot, then the code you have to follow looks like this:



mf.plot(amzn, mav = (10, 20), type = ‘candle’, volume = True, savefig = ‘amzn.png’)

That’s all you have to do in order to save your wonderful financial visualizations. Pretty easy, right?


Final Thoughts!


In my opinion, I feel like mplfinance is the most powerful library to plot financial data than other libraries like Plotly or Altair. This article is just a glimpse of what you can achieve with mplfinance but there a lot of new features that come along with this awesome library. It allows us to add custom technical indicators data and plot alongside the actual graph, we can customize the whole template or even every single element in the graph, add trend lines, and so on. The best part about this library is its ease of use and helps us producing advanced financial visualization with just one line of code. Though packages like Plotly have in-built functions to create these charts, it is not possible to do it in a line of code.


The only drawback the mplfinance has now is its poor documentation that makes people not even know what this package is about. Documentation is a crucial aspect and should be considered of paramount importance when it comes to open-source projects. Especially, critical and helpful projects like mplfinance must have fair documentation with clear-cut explanations on the tools and functions it offers. Other than that, I’m a die-hard fan of this library and hope you too would be. That’s it! You’ve reached the end of the article. If you forgot to follow any of the charts’ code, don’t worry. I’ve provided the full source code at the end. With that being said, happy visualizing!


Full code:



import pandas as pd
import requests
import mplfinance as mf

# Extracting stock data

def get_historical_data(symbol, start_date):
    api_key = 'YOUR API KEY'
    api_url = f'https://api.twelvedata.com/time_series?symbol={symbol}&interval=1day&outputsize=5000&apikey={api_key}'
    raw_df = requests.get(api_url).json()
    df = pd.DataFrame(raw_df['values']).iloc[::-1].set_index('datetime').astype(float)
    df = df[df.index >= start_date]
    df.index = pd.to_datetime(df.index)
    return df

amzn = get_historical_data('AMZN', '2021-01-01')
amzn.tail()

# 1. OHLC Chart

mf.plot(amzn.iloc[:-50,:])

# 2. Candlestick Chart

mf.plot(amzn.iloc[:-50,:], type = 'candle')

# 3. Renko Chart

mf.plot(amzn, type = 'renko')

# 4. Point and Figure Chart

mf.plot(amzn, type = 'pnf')

# 5. Technical chart

mf.plot(amzn, mav = (10, 20), type = 'candle', volume = True)

# 6. Plot customization

mf.plot(amzn, mav = (5, 10, 20), type = 'candle', 
        volume = True, figratio = (10,5), 
        style = 'binance', title = 'AMZN STOCK PRICE', 
        tight_layout = True)

# 7. Saving the plot

mf.plot(amzn, mav = (5, 10, 20), type = 'candle', 
        volume = True, figratio = (10,5), 
        style = 'binance', title = 'AMZN STOCK PRICE', 
        tight_layout = True, savefig = 'amzn.png')

 

4 comments

4 Comments


saravanakumaar.a
saravanakumaar.a
Jul 07, 2021

Interesting and useful one Nikhil.

Like

Rathinagiri Subbiah
Rathinagiri Subbiah
Jul 07, 2021

Data visualization is the name of the game today! Kudos Nikhil.

Like

209847 VEERABADRAN V
209847 VEERABADRAN V
Jul 07, 2021

Good one Nikhil

Like

M.Paramasivan Sivan
M.Paramasivan Sivan
Jul 07, 2021

Good effort on explaining data visualisation with mplfinannce. , of course with its limitations. Good work Nikil.

paramasivan

Like
bottom of page