Sector Area Chart

Display an area chart representing the weight of different industry sectors over time

In this cookbook, we'll walk through the process of creating a simple dashboard that plots a time series area chart for industry sectors using Finter, a quantitative finance library, and Gradio, a Python library for creating customizable UI components for machine learning models.

Prerequisites

Before you begin, ensure you have the following installed:

  • Python 3.6 or later

  • finter library

  • gradio library

  • pandas library

  • plotly library

  • python-dotenv library

You can install these with pip:

pip install finter gradio pandas plotly python-dotenv

Step 1: Load Environment Variables

First, we need to load environment variables from a .env file. This is where you would store sensitive information such as API keys.

import dotenv

# Load environment variables from .env file
dotenv.load_dotenv(dotenv.find_dotenv())

Step 2: Define Constants and Functions

Set the end date for the data you want to retrieve. In this example, we're using 20240401 as the end date.

END = 20240401

Define a function to plot the sector area chart. This function takes a model_name as input, loads the model data, and creates a chart.

def plot_sector_area_chart(model_name):
    # Load model data
    df = ModelData.load(model_name)
    df.columns = df.columns.astype(int)

    # Get sector data
    sector = BaseAlpha.get_cm(
        "content.handa.dataguide.company.krx-spot-sector.1d"
    ).get_df(20190101, END)
    sector_list = set(sector.unstack().dropna())

    # Helper function to get sector weights
    def get_sector(sector_name):
        return (df[sector == sector_name]).sum(axis=1).rename(sector_name)

    # Calculate weights for each sector
    weight = pd.concat([get_sector(sector_name) for sector_name in sector_list], axis=1)
    weight = pd.concat(
        [
            weight,
            df[sector.reindex(columns=df.columns).isna()].sum(axis=1).rename("Etc"),
        ],
        axis=1,
    )
    # Convert to long format for plotting
    df_long = weight.reset_index().melt(
        id_vars="index", var_name="Category", value_name="Value"
    )
    df_long.rename(columns={"index": "Date"}, inplace=True)

    # Create the area chart
    fig = px.area(
        df_long,
        x="Date",
        y="Value",
        color="Category",
        title="Time Series Area Chart for Industry Sectors",
    )
    return fig

Step 3: Create the Gradio Interface

Set up the Gradio interface with an input textbox for the model name and a button to plot the chart. The chart will be displayed as output.

import gradio as gr

if __name__ == "__main__":
    with gr.Blocks() as app:
        with gr.Row():
            model_input = gr.Textbox(
                value="alpha.krx.krx.stock.ldh0127.div_2",
                label="Enter model name"
            )
            submit_button = gr.Button("Plot Chart")
        chart_output = gr.Plot()

        # When the button is clicked, call the plot_sector_area_chart function
        submit_button.click(
            fn=plot_sector_area_chart, inputs=model_input, outputs=chart_output
        )

    # Launch the app
    app.launch(server_name="0.0.0.0", server_port=7860)

Expected Output

When you run the script, it will launch a web server and open a browser window with the Gradio interface. You can enter a model name into the textbox and click "Plot Chart" to generate the area chart. The chart will display the time series data for industry sectors, with each sector represented by a different color.

Conclusion

You've now created a simple dashboard that visualizes sector weights over time using Finter and Gradio. This dashboard can be easily modified to include additional features or to work with different datasets.

Last updated