杰瑞科技汇

Python mplfinance如何绘制K线图?

Of course! mplfinance is an excellent and popular Python library specifically designed for creating financial market plots. It's built on top of Matplotlib, making it familiar to many data scientists and analysts, but it provides a much simpler, high-level interface for common financial chart types.

Python mplfinance如何绘制K线图?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from installation to advanced features.


Installation

First, you need to install the library. It's recommended to also install pandas as mplfinance relies on it for data handling.

pip install mplfinance
pip install pandas

The Basics: Plotting a Candlestick Chart

The most common use case for mplfinance is plotting candlestick charts. To get started, you need a pandas DataFrame with the correct column names.

Required DataFrame Columns

Your DataFrame must have columns named:

Python mplfinance如何绘制K线图?-图2
(图片来源网络,侵删)
  • Open
  • High
  • Low
  • Close

It's highly recommended to also have a Date column, which mplfinance will use to set the x-axis.

Example: Getting Data and Plotting

Let's use yfinance to download some historical data for Apple (AAPL).

import yfinance as yf
import mplfinance as mpf
import pandas as pd
# 1. Download data
# The 'start' and 'end' dates are inclusive.
ticker = 'AAPL'
start_date = '2025-01-01'
end_date = '2025-06-30'
data = yf.download(ticker, start=start_date, end=end_date)
# 2. Plot a basic candlestick chart
mpf.plot(data, type='candle', style='charles', title=f'{ticker} Candlestick Chart')

Explanation:

  • yf.download(...): Fetches the historical OHLCV (Open, High, Low, Close, Volume) data.
  • mpf.plot(...): The main function to generate the plot.
    • data: The pandas DataFrame.
    • type='candle': Specifies that we want a candlestick chart. Other types include 'line', 'ohlc', and 'renko'.
    • style='charles': Chooses a color scheme. Other popular styles include 'mike', 'blueskies', and 'yahoo'.
    • title=...: Sets the title for the chart.

Customizing Your Plots

mplfinance offers a wide range of customization options.

Python mplfinance如何绘制K线图?-图3
(图片来源网络,侵删)

Adding Volume

Volume is a crucial part of financial analysis. You can easily add it as a subplot at the bottom.

mpf.plot(data, type='candle', style='charles', volume=True)

Adding Moving Averages (MAs)

Technical analysts often use moving averages. You can add them using the mav (moving average) argument.

# Add a 20-day and a 50-day moving average
mpf.plot(data, type='candle', style='charles', mav=(20, 50), volume=True)

Setting the Figure Size

You can control the dimensions of the output figure using the figratio and figscale arguments.

# figratio=(width, height), figscale is a multiplier
mpf.plot(data, type='candle', style='charles', mav=(20, 50), 
         volume=True, figratio=(16, 8), figscale=1.2)

Adding Lines and Markers

You can draw horizontal lines for support/resistance levels or mark specific events.

# Define a support level
support_level = 170.0
# Create additional plots for lines and markers
apds = [
    # Add a red horizontal line for the support level
    mpf.make_addplot([support_level] * len(data), panel=0, color='r', linestyle='--'),
    # Mark the days with the highest volume
    # We use the 'volume' panel for this marker
    mpf.make_addplot(data['Volume'].max(), panel=1, type='scatter', marker='v', markersize=100, color='g')
]
mpf.plot(data, type='candle', style='charles', addplot=apds, 
         volume=True, title='AAPL with Support Level')

Explanation of make_addplot:

  • mpf.make_addplot(...): A function to create "additional plots" that can be layered onto the main chart.
  • panel=0: Refers to the main price panel. panel=1 refers to the volume panel.
  • type='scatter': Specifies the type of plot (e.g., line, scatter).
  • addplot=apds: The apds list is passed to the mpf.plot function.

Different Chart Types

mplfinance supports several chart types beyond candlesticks.

OHLC Bar Chart

Shows the Open, High, Low, and Close as vertical bars.

mpf.plot(data, type='ohlc', style='charles', title='AAPL OHLC Chart')

Line Chart

A simple line connecting the closing prices.

mpf.plot(data, type='line', style='charles', title='AAPL Line Chart')

Renko Chart

A price-action chart that filters out "noise" by only plotting significant price movements.

# Renko charts require a 'brick_size' argument
mpf.plot(data, type='renko', brick_size=2, title='AAPL Renko Chart')

Heikin-Ashi Chart

A smoothed candlestick chart that helps identify trends more easily.

mpf.plot(data, type='heikin-ashi', style='charles', title='AAPL Heikin-Ashi Chart')

Saving Your Plots

You can save the generated plot to a file (e.g., PNG, JPG, PDF, SVG) using the savefig argument.

mpf.plot(data, type='candle', style='charles', mav=(20, 50), 
         volume=True, title='AAPL Chart to Save',
         savefig='aapl_chart.png')

Advanced Features: show_nontrading

Sometimes, market data includes non-trading days (like weekends or holidays). By default, mplfinance will show gaps in these dates. You can use show_nontrading=True to fill these gaps and create a continuous chart.

# Download data with a gap (e.g., including a weekend)
data_with_gap = yf.download(ticker, start='2025-05-19', end='2025-05-22')
print("Data with a gap:")
print(data_with_gap)
print("\n--- Plotting with default behavior (shows gap) ---")
mpf.plot(data_with_gap, type='candle', title='Default (Gap Shown)')
print("\n--- Plotting with show_nontrading=True (fills gap) ---")
mpf.plot(data_with_gap, type='candle', show_nontrading=True, title='show_nontrading=True (Gap Filled)')

Complete Example

Here is a complete, well-commented example that combines several features.

import yfinance as yf
import mplfinance as mpf
import pandas as pd
# --- 1. Get Data ---
ticker = 'TSLA'
start_date = '2025-01-01'
end_date = '2025-12-31'
# Download data and ensure the index is a DatetimeIndex
data = yf.download(ticker, start=start_date, end=end_date)
data.index = pd.to_datetime(data.index) # Ensure it's a DatetimeIndex
# --- 2. Define Customizations ---
# Style
s = mpf.make_mpf_style(base_mpf_style='yahoo', gridstyle=':')
# Moving Averages
mav = [20, 50, 200]
# Add a 200-day moving average as a separate plot for styling
apds = [
    mpf.make_addplot(data['Close'].rolling(window=200).mean(), color='purple', width=1.5, label='MA 200')
]
# --- 3. Create the Plot ---
mpf.plot(
    data,
    type='candle',
    style=s,f'{ticker} - 2025 Technical Analysis',
    ylabel='Price (USD)',
    volume=True,
    mav=mav,
    addplot=apds,
    figratio=(18, 10),
    figscale=1.1,
    show_nontrading=True # Fill in gaps for weekends
)
# --- 4. Save the Plot ---
mpf.plot(
    data,
    type='candle',
    style=s,f'{ticker} - 2025 Technical Analysis',
    volume=True,
    mav=mav,
    addplot=apds,
    savefig=f'{ticker}_full_analysis.png'
)
print(f"Chart for {ticker} has been generated and saved.")

This example demonstrates how to fetch data, apply a custom style, add multiple moving averages, include an additional plot for custom styling, and save the final result. mplfinance is a powerful and flexible tool that should be in the toolkit of anyone analyzing financial data in Python.

分享:
扫描分享到社交APP
上一篇
下一篇