LinearChart()

The ChartPlotter class is a tool for generating and visualizing different types of charts, including line charts and candlestick charts, based on a provided pandas DataFrame. It offers extensive customization options to tailor the appearance of the charts to your specific needs, making it an essential utility for quantitative analysis and data visualization within the marketquant library.

Import Statement

from marketquant.chart_plotter import ChartPlotter

Usage Overview

To utilize the ChartPlotter class, initialize it with a pandas DataFrame containing the relevant data, specify the type of chart you wish to create (either 'line' or 'candlestick'), and customize various visual aspects as needed. Once configured, call the plot_chart method to generate and display the chart.

Class: ChartPlotter

Method: plot_chart

ChartPlotter.plot_chart(line_color='green', candlestick_style='classic', candlestick_type='ohlc', **kwargs)

This is the primary method used for plotting the specified chart type with customizable styling options. It handles the rendering of both line and candlestick charts based on the provided parameters.

Arguments:

  • line_color (str, optional): Color of the line in line charts. Default is 'green'.

  • candlestick_style (str, optional): Style of the candlestick chart (e.g., 'classic', 'charles', 'yahoo'). Default is 'classic'.

  • candlestick_type (str, optional): Type of candlestick chart ('ohlc' for Open-High-Low-Close or 'candle' for traditional candlestick). Default is 'ohlc'.

  • kwargs: Additional keyword arguments for further customization and passing parameters directly to the plotting functions.

Returns:

  • None: The method generates and displays the chart but does not return any values.

How to Use ChartPlotter()

  1. Prepare Your Data

    Ensure your data is organized in a pandas DataFrame with the necessary columns based on the type of chart you intend to plot.

    • For Line Charts: The DataFrame should contain at least two columns, typically representing the x-axis and y-axis data points (e.g., 'x' and 'y').

    • For Candlestick Charts: The DataFrame must include the following columns:

      • 'Date': The date or time of each data point.

      • 'Open': Opening price.

      • 'High': Highest price.

      • 'Low': Lowest price.

      • 'Close': Closing price.

  2. Import the ChartPlotter Class

    from marketquant.chart_plotter import ChartPlotter
    import pandas as pd
  3. Initialize the ChartPlotter Class

    Create an instance of the ChartPlotter class by providing the necessary parameters:

    • dataframe (pd.DataFrame): The DataFrame containing your data.

    • plot_type (str): The type of chart to plot ('line' or 'candlestick').

    • Additional customization parameters as needed.

    # Example for Line Chart
    chart_plotter = ChartPlotter(
        dataframe=df_line,
        plot_type='line',
        title='Sample Line Chart',
        xlabel='X-Axis',
        ylabel='Y-Axis'
    )
    
    # Example for Candlestick Chart
    chart_plotter = ChartPlotter(
        dataframe=df_candle,
        plot_type='candlestick',
        title='Sample Candlestick Chart',
        xlabel='Date',
        ylabel='Price'
    )
  4. Generate and Display the Chart

    Call the plot_chart method on the instance to create and display the chart.

    pythonCopy code# For Line Chart
    chart_plotter.plot_chart(line_color='blue')
    
    # For Candlestick Chart
    chart_plotter.plot_chart(candlestick_style='charles', candlestick_type='candle')

Examples

Example 1: Basic Line Chart

from marketquant.chart_plotter import ChartPlotter
import pandas as pd

# Sample data for line chart
data = {
    'x': [1, 2, 3, 4, 5],
    'y': [10, 15, 13, 17, 20]
}
df_line = pd.DataFrame(data)

# Initialize the ChartPlotter for a line chart
line_plotter = ChartPlotter(
    dataframe=df_line,
    plot_type='line',
    title='Sample Line Chart',
    xlabel='X-Axis',
    ylabel='Y-Axis'
)

# Plot the line chart
line_plotter.plot_chart(line_color='blue')

Output:

A line chart displaying the data points with a blue line connecting them, along with the MarketQuant logo.


Example 2: Basic Candlestick Chart

from marketquant.chart_plotter import ChartPlotter
import pandas as pd

# Sample data for candlestick chart
data = {
    'Date': ['2023-01-01', '2023-01-02', '2023-01-03', 
             '2023-01-04', '2023-01-05'],
    'Open': [100, 102, 101, 105, 107],
    'High': [105, 106, 104, 108, 110],
    'Low': [99, 101, 100, 103, 106],
    'Close': [104, 103, 103, 107, 109]
}
df_candle = pd.DataFrame(data)

# Initialize the ChartPlotter for a candlestick chart
candle_plotter = ChartPlotter(
    dataframe=df_candle,
    plot_type='candlestick',
    title='Sample Candlestick Chart',
    xlabel='Date',
    ylabel='Price'
)

# Plot the candlestick chart
candle_plotter.plot_chart(
    candlestick_style='charles',
    candlestick_type='candle'
)

Output:

A candlestick chart displaying the open, high, low, and close prices with the Charles style from mplfinance, along with the MarketQuant logo.


Example 3: Customized Line Chart

from marketquant.chart_plotter import ChartPlotter
import pandas as pd

# Sample data for line chart
data = {
    'x': [0, 1, 2, 3, 4, 5],
    'y': [0, 1, 4, 9, 16, 25]
}
df_line_custom = pd.DataFrame(data)

# Initialize the ChartPlotter with customizations
custom_line_plotter = ChartPlotter(
    dataframe=df_line_custom,
    plot_type='line',
    title='Quadratic Growth',
    xlabel='Time',
    ylabel='Value',
    line_color='magenta',
    background_color='lightgrey'
)

# Plot the customized line chart
custom_line_plotter.plot_chart()

Output:

A magenta line chart displaying quadratic growth with a light grey background and the MarketQuant logo.


Example 4: Customized Candlestick Chart

from marketquant.chart_plotter import ChartPlotter
import pandas as pd

# Sample data for candlestick chart
data = {
    'Date': ['2023-02-01', '2023-02-02', '2023-02-03', 
             '2023-02-04', '2023-02-05'],
    'Open': [150, 152, 151, 155, 157],
    'High': [155, 156, 154, 158, 160],
    'Low': [149, 151, 150, 153, 156],
    'Close': [154, 153, 153, 157, 159]
}
df_candle_custom = pd.DataFrame(data)

# Initialize the ChartPlotter with customizations
custom_candle_plotter = ChartPlotter(
    dataframe=df_candle_custom,
    plot_type='candlestick',
    title='Customized Candlestick Chart',
    xlabel='Date',
    ylabel='Price',
    background_color='beige',
    candlestick_style='yahoo',
    candlestick_type='ohlc'
)

# Plot the customized candlestick chart
custom_candle_plotter.plot_chart()

Output:

A candlestick chart with the Yahoo style, displaying open, high, low, and close prices on a beige background, along with the MarketQuant logo.

Customization Options for Charts

When plotting charts using the ChartPlotter class, you can control various aspects of the visualization through the initialization parameters and the plot_chart method.

Common Customization Parameters

  • Figure and Resolution:

    • figure_size (tuple): Specifies the width and height of the figure. Default is (12, 8).

    • dpi (int): Dots per inch for the figure resolution. Default is 100.

  • Fonts and Labels:

    • font_size (int): Base font size for labels. Default is 12.

    • title (str): Title of the chart.

    • title_font_size (int): Font size of the chart title. Default is 16.

    • title_font_color (str): Color of the chart title. Default is 'navy'.

    • xlabel (str): Label for the x-axis.

    • ylabel (str): Label for the y-axis.

    • xlabel_font_size (int): Font size for the x-axis label. Default is 14.

    • ylabel_font_size (int): Font size for the y-axis label. Default is 14.

    • label_color (str): Color for both x and y labels. Default is 'purple'.

  • Grid and Axes:

    • grid (bool): Enable (True) or disable (False) grid lines. Default is True.

    • grid_color (str): Color of the grid lines. Default is 'grey'.

    • grid_line_style (str): Style of the grid lines (e.g., '--', '-'). Default is '--'.

    • grid_line_width (float): Thickness of the grid lines. Default is 0.5.

    • axis_color (str): Color of the axis lines. Default is 'black'.

    • tick_color (str): Color of the tick marks. Default is 'black'.

    • axis_line_width (float): Width of the axis lines. Default is 1.0.

  • Plot Specifics:

    • plot_type (str): Type of chart to plot ('line' or 'candlestick').

    • line_color (str, optional): Color of the line in line charts. Default is 'green'.

    • candlestick_style (str, optional): Style of the candlestick chart (e.g., 'classic', 'charles', 'yahoo'). Default is 'classic'.

    • candlestick_type (str, optional): Type of candlestick chart ('ohlc' or 'candle'). Default is 'ohlc'.

  • Miscellaneous:

    • x_rotation (int): Rotation angle for x-axis labels. Default is 45 degrees.

    • legend (bool): Whether to display a legend (True or False). Default is True.

    • background_color (str): Background color of the chart. Default is 'white'.

    • logo_path (str): File path to the MarketQuant logo image. Default is 'marketquant/MarketQuant_Logo.png'.

Additional Customizations via plot_chart Method

The plot_chart method accepts additional keyword arguments (**kwargs) that are passed directly to the plotting functions, allowing for further customization as needed.

  • Line Chart Customizations:

    • linewidth (float): Thickness of the line.

    • linestyle (str): Style of the line (e.g., '-', '--').

  • Candlestick Chart Customizations:

    • Additional parameters supported by mplfinance.plot can be passed via **kwargs, such as:

      • volume (bool): Whether to include volume in the chart.

      • ylabel_lower (str): Label for the lower y-axis (e.g., volume).

      • title (str): Override the chart title.

Example of Additional Customizations:

# For Line Chart with Custom Line Width and Style
line_plotter.plot_chart(line_color='blue', linewidth=2.5, linestyle='--')

# For Candlestick Chart with Volume and Custom Title
candle_plotter.plot_chart(
    candlestick_style='charles',
    candlestick_type='candle',
    volume=True,
    ylabel_lower='Volume',
    title='Candlestick Chart with Volume'
)

Output

The output of the ChartPlotter class will be:

  • A Visual Chart: Depending on the plot_type specified, the class will generate either a line chart or a candlestick chart, rendered with the specified customizations.

    • Line Chart: Displays data points connected by a line, useful for showing trends over time or other continuous data.

    • Candlestick Chart: Visualizes the open, high, low, and close prices for financial instruments, essential for technical analysis in trading.

  • MarketQuant Logo: The MarketQuant logo is integrated into the bottom left corner of the chart for branding purposes.

Example Outputs:

  1. Line Chart Output:

  2. Candlestick Chart Output:

Note: Replace path_to_line_chart_image and path_to_candlestick_chart_image with actual paths or remove these lines if images are not available.

Last updated