程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Creating advanced financial charts with one line of Python code

編輯:Python

Today, I'll take you to learn about a minority , But a powerful visualization Library mplfinance, Master the most flexible... Together python Library to create a beautiful financial Visualization .

Introduce

The proliferation of programming and technology applications in the financial sector is inevitable , Growth never seems to decline . One of the most interesting parts of application programming is the interpretation and visualization of historical or real-time stock data .

Now? , In order to be in python Visualize general data in ,matplotlib、seaborn When the module starts to work , however , When it comes to visualizing financial data ,Plotly Will be the first choice , Because it provides built-in functions with interactive visual effects . Here I want to introduce an unknown hero , It's just mplfinance library matplotlib Brother Library .

We all know matplotlib The versatility of the package , And you can easily draw any type of data . Even financial charts like candlesticks can be used matplotlib Package drawing , But we have to start from scratch .

lately , I began to know that there was a man named mplfinance Separate modules , Designed to create advanced financial visualization . In this paper , We will delve into this Python library , And explore its function of generating different types of charts .

Import package

Import the required packages into our python Environment is an essential step . In this paper , We need three bags , They process data frames Pandas、 call API And extracting stock data requests, And creating financial charts mplfinance. For those who have not yet installed these packages , Please copy this code to your terminal :

pip install pandas 
pip install requests
pip install mplfinance

After installing the package , It's time to import them into our python In the environment .

import pandas as pd
import requests
import mplfinance as mf

Extract stock data

Now? , We have imported all the necessary packages . Let's use 12data.com[1] Provided API The endpoint pulls Amazon's historical stock data . Before that ,12data.com A note on :12data Is one of the leading market data providers , Have a large amount of data for all types of markets API Endpoint . With twelve data provided API Interaction is very easy , And one of the best documents ever . Besides , Please make sure you are in 12data.com Have an account on , That's the only way , You can access your API secret key ( Use API Extract important elements of data ).

Python Realization

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 instructions

The first thing we do is define a name called 'get_historical_data' Function of , This function takes the stock code ('symbol') And the start date of historical data ('start_date') Is the parameter .

Inside the function , We defined API Key and URL, And store them in their own variables .

Next , We use 'get' Function to JSON Format extracts historical data and stores it in  'raw_df' variable . On the original JSON After some data cleaning and formatting , We use an empty Pandas DataFrame Return it as .

Last , We call created Function to pull Amazon from 2021 Historical data from the beginning of the year , And store it to "amzn" variable .

OHLC chart

OHLC A chart is a bar chart , Displays the opening price for each period 、 Highest price 、 The lowest price and closing price .

OHLC Charts are useful , Because they show four main data points over a period of time , Many traders think the closing price is the most important . It also helps to show increased or decreased momentum . Strong performance when opening and closing are far apart , When the opening and closing are similar, it shows indecision or weak kinetic energy .

The highest and lowest prices show the full price range for the period , Helps to assess volatility 1[2]. Now I'm going to use mplfinance Create a OHLC Chart , Just one line of code :

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

In the code above , We first call the plot function , And in which we extracted Amazon OHLC The data slice is the last 50 Readings , The purpose of this is just to make the chart clearer , So that the element is visible . The single line code above will produce the output shown below :

Candlestick chart

Traders use candlestick charts to determine possible price changes based on past patterns . Candlesticks are very useful in trading , Because they show four price points throughout the time period specified by the trader ( Opening price 、 Closing price 、 The highest price and the lowest price ).

The most interesting part of this type of chart is that it can also help traders read emotions , This is the primary driver of the market itself  2[3]. To use mplfinance Generate Candlestick diagram , We just need to add another parameter , That is, the of the function type Parameters plot and candle Mention in it . The code is as follows :

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

The above code will generate a candlestick chart as shown below :

Brick diagram

Brick diagram ( Renko chart) Is a chart constructed using price changes , Instead of using both prices and standardized intervals like most charts . The chart looks like a series of bricks , When the price moves the specified price amount, a new brick is created , And each block is made of the previous brick 45 Degree angle ( Up or down ).Renko The main purpose of charts is to filter out noise and help traders see trends more clearly , Because all motions smaller than the frame size are filtered out  3[4] .

as far as I am concerned ,mplfinance Is the only provider Renko Chart's Python library , That's what we're going to see next , That's why this package has a strong advantage in financial Visualization . Now create a Renko, We just need to be in the function renko Of type Specified in parameter plot.Renko The code of the chart is as follows :

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

We can also ask plot Add an extra argument to the function , This parameter is based on renko_params We need and other similar types to modify the parameters of brick size , But I prefer the default . The above code generates a brick diagram that looks like this :

Dot graph

Dot graph , abbreviation P&F chart , Be similar to Renko chart , It plots the price trend of assets without considering the passage of time . With some other types of charts ( For example, Candlestick ) contrary , The candlestick indicates the degree of change of assets within a set period of time , and P&F The chart uses a stack of X or O The columns that make up , Each column represents a certain number of price changes .X Represents a rise in prices , and O Represents a decline in prices . When the price reverses, the reverse volume  4[5]  when , Will be in O Then form a new X Column or in X Then form a new O Column .

The function supporting point graph cannot be found elsewhere , Only in mplfinance Found in Library , And it also allows us to pass only pnf In function type The process of creating a chart specified in the parameter is easier plot. The code is as follows :

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

Point chart add more information

mplfinance Packages are not limited to generating different types of charts , It also allows us to add a simple moving average (SMA) Additional indicators such as and trading volume make these charts more insightful . For those who don't know both , Trading volume is the number of stocks bought and sold by traders within a specific time frame , And the simple moving average (SMA) It's just the average price over a specific period of time . It is a technical index , Widely used to create trading strategies .

use matplotlib It takes a thousand years to plot these data , and mplfinance Allow us to do this in one line of code . except type Besides the parameters , We just need to introduce two other parameters , One is mav We must specify each SMA Parameters of the backtracking period , The other is volume The parameters we must mention ,True  If we want to add the volume chart to our chart , perhaps False  We don't want to . The codes of these two indicators are as follows :

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

The above code can be modified and tested in two ways . The first approach is obviously to try different types of charts . In the above code , We mentioned that our chart type is Candlestick , But you can change it to OHLC、Renko even to the extent that P&F Chart , And observe the appearance of each chart and its two additional indicators . The next method is to use mav We can add any number of... With different review periods SMA Parameters of . The output of the above code is shown below :

Save the picture

If you want to know how to save any of these financial visualizations , Just add another parameter ,savefig That is, you only need to mention the parameters of its file name , The rest will be processed . Suppose you want to save the picture above , Then the code you must follow is as follows :

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

That's all you need to do to save a wonderful financial Visualization . be prone to , Right ?

At the end

in my opinion , And Plotly or Altair Wait for the library to compare ,mplfinance It is the most powerful library for drawing financial data . This article simply introduces the use of mplfinance Functions that can be realized , But this great library comes with many new features . It allows us to add custom technical indicator data , And draw with the actual chart , We can customize the whole template , Even every element in the chart , Add trendline , wait .

The best part of this library is its ease of use , And help us generate high-level financial visualization with one line of code . Though like Plotly Such packages have built-in functions to create these charts , But it can't be done in one line of code .

mplfinance The only drawback now is its poor documentation , This makes people don't even know what the bag is about . Documentation is a crucial aspect , When it comes to open source projects , Documentation should be considered critical . Special like mplfinance Such critical and useful projects must be clearly documented , Have a clear explanation of the tools and functions it provides .

Come here , After you read this article . If you forget the code of the chart , Don't worry about , Finally, I provide the complete source code . You can also collect this article , Check it when you need it .

Complete 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')

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved