DEV Community

Cover image for A Developer's Guide to Visualizing Tesla's Financial Data with XBRL
Maciej Józefowicz for FinFeedAPI

Posted on

A Developer's Guide to Visualizing Tesla's Financial Data with XBRL

Tesla, Inc., led by Elon Musk, is more than just a car company; it's a major force in the technology and energy sectors. Its performance and strategic decisions have a significant impact on the market, influencing everything from supply chains to investor sentiment in renewable energy and artificial intelligence. The company's frequent announcements and Musk's public statements make it one of the most-watched stocks in the world. For investors, analysts, and anyone interested in the future of technology and transportation, having access to detailed, accurate financial data on Tesla is not just useful—it's essential. Structured financial data allows for a clear view of the company's health and trajectory, cutting through the noise of daily news cycles.

Analyzing a company's financial statements is essential for understanding its performance, but manually extracting data from SEC filings can be a slow process. XBRL (eXtensible Business Reporting Language) data provides a structured, machine-readable format that is ideal for automated analysis.

This guide demonstrates how to use FinFeedAPI to access aggregated XBRL data from Tesla's 10-K filings. You will see how to write a Python script to fetch key financial metrics, process the data, and create several visualizations to analyze trends in revenue, expenses, and profitability.

This guide covers:

  • Fetching aggregated XBRL financial data for a specific company.
  • Processing and structuring time-series financial data with pandas.
  • Visualizing revenue, cost of revenue, and net income trends.
  • Creating a pie chart to show the distribution of operating expenses.
  • Calculating and plotting gross and net margin percentages over time.

What you need:

  • Python 3.x with pandas and matplotlib.
  • The api-bricks-sec-api-rest library.
  • Your personal FinFeedAPI key.

1. Environment Setup
First, you need to install the FinFeedAPI client library.

pip install api-bricks-sec-api-rest
Enter fullscreen mode Exit fullscreen mode

Next, prepare your Python script by importing the necessary libraries and configuring the API client with your key.

# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import re
import api_bricks_sec_api_rest

# --- API Configuration ---
# IMPORTANT: Replace "YOUR_API_KEY_HERE" with your actual key.
API_KEY = "YOUR_API_KEY_HERE"
api_client_config = api_bricks_sec_api_rest.Configuration()
api_client_config.api_key['Authorization'] = API_KEY
api_client = api_bricks_sec_api_rest.ApiClient(configuration=api_client_config)

# --- Plotting Configuration ---
plt.style.use('seaborn-v0_8-darkgrid')
plt.rcParams['figure.figsize'] = (14, 7)
Enter fullscreen mode Exit fullscreen mode

2. Fetching Aggregated XBRL Data
The /v1/xbrl/facts/aggregated endpoint is a powerful tool for this type of analysis. It returns a clean, time-series set of financial facts for a given company and form type, which saves you from having to parse the raw XBRL from each filing individually.

Let's use this endpoint to get the financial data from Tesla's (CIK: 1318605) 10-K filings.

# Initialize the XBRL API client
xbrl_api = api_bricks_sec_api_rest.XBRLApi(api_client)

# Define the target CIK and form type
target_cik = 1318605
target_form_type = "10-K"

# Fetch the aggregated financial facts
try:
    aggregated_facts = xbrl_api.v1_xbrl_facts_aggregated_get(
        cik=target_cik,
        form_type=target_form_type
    )
    # Convert the results to a pandas DataFrame
    df_aggregated = pd.DataFrame.from_records([vars(x) for x in aggregated_facts])
    print(f"Successfully fetched {len(df_aggregated)} aggregated financial facts for CIK {target_cik}.")
except api_bricks_sec_api_rest.ApiException as e:
    print(f"Exception when calling XBRLApi: {e}")
    df_aggregated = pd.DataFrame()

Enter fullscreen mode Exit fullscreen mode

3. Processing and Structuring the Data
The API returns the data in a "long" format. To make it easier to work with, we'll pivot the DataFrame so that each financial metric is a row and each time period is a column. We will also clean the data to ensure it's in a numeric format suitable for plotting.

if not df_aggregated.empty:
    # Pivot the table
    df_aggregated = df_aggregated.pivot(index='fact', columns='period', values='value')

    # Function to extract dates and sort columns chronologically
    def sort_columns_by_date(df):
        def get_end_date(col_name):
            try:
                # Extracts date from a string like '2022-01-01T00:00:00Z/2022-12-31T00:00:00Z'
                match = re.search(r'/(\d{4}-\d{2}-\d{2})', col_name)
                if match:
                    return pd.to_datetime(match.group(1))
            except (ValueError, TypeError):
                return pd.NaT
            return pd.NaT

        sorted_columns = sorted(df.columns, key=get_end_date)
        return df[sorted_columns]

    df_aggregated = sort_columns_by_date(df_aggregated)

    # Clean numeric data
    for col in df_aggregated.columns:
        df_aggregated[col] = pd.to_numeric(df_aggregated[col].astype(str).str.replace(r'[$,]', '', regex=True), errors='coerce')

    print("Transformed and Cleaned Data Head:")
    print(df_aggregated.head())

Enter fullscreen mode Exit fullscreen mode

4. Visualizing Financial Performance
With the data cleaned and structured, we can now create several visualizations to analyze Tesla's performance.

Revenue, Cost of Revenue, and Net Income
This bar chart shows the relationship between revenues, the cost to generate them, and the resulting net income or loss for each period.

if 'Revenues' in df_aggregated.index and 'CostOfRevenue' in df_aggregated.index:
    # Select the relevant data
    plot_data = df_aggregated.loc[['Revenues', 'CostOfRevenue', 'NetIncomeLoss']].T / 1e9

    # Create the bar chart
    plot_data.plot(kind='bar', figsize=(14, 7))
    plt.title(f'Tesla (CIK: {target_cik}) - Revenue, Cost, and Net Income (Form {target_form_type})')
    plt.ylabel('Amount (in billions USD)')
    plt.xlabel('Fiscal Period')
    plt.xticks(rotation=45, ha='right')
    plt.grid(True, axis='y', linestyle='--')
    plt.legend(title='Financial Metric')
    plt.show()

Enter fullscreen mode Exit fullscreen mode

A bar chart titled
Distribution of Operating Expenses
A pie chart is a good way to see how a company's operating expenses are distributed. Here, we look at the most recent period available.

op_expense_metrics = ['ResearchAndDevelopmentExpense', 'SellingGeneralAndAdministrativeExpense']
if all(metric in df_aggregated.index for metric in op_expense_metrics):
    # Select the last period for the pie chart
    last_period = df_aggregated.columns[-1]
    expense_data = df_aggregated.loc[op_expense_metrics, last_period]

    # Create the pie chart
    expense_data.plot(kind='pie', autopct='%1.1f%%', startangle=90, figsize=(8, 8))
    plt.title(f'Distribution of Operating Expenses for Period Ending {last_period.split("/")[-1]}')
    plt.ylabel('') # Hide the y-label
    plt.show()
Enter fullscreen mode Exit fullscreen mode

A pie chart titled

Gross Margin and Net Margin Analysis
Finally, we can calculate and plot the gross and net margins to see how profitability has changed over time.

if 'Revenues' in df_aggregated.index and 'CostOfRevenue' in df_aggregated.index:
    # Calculate margins
    gross_margin = (df_aggregated.loc['Revenues'] - df_aggregated.loc['CostOfRevenue']) / df_aggregated.loc['Revenues'] * 100
    net_margin = df_aggregated.loc['NetIncomeLoss'] / df_aggregated.loc['Revenues'] * 100
    margin_df = pd.DataFrame({'Gross Margin (%)': gross_margin, 'Net Margin (%)': net_margin})

    # Create the line chart
    margin_df.plot(kind='line', marker='o', figsize=(14, 7))
    plt.title(f'Tesla (CIK: {target_cik}) - Profitability Margins (Form {target_form_type})')
    plt.ylabel('Margin (%)')
    plt.xlabel('Fiscal Period')
    plt.xticks(rotation=45, ha='right')
    plt.grid(True)
    plt.axhline(0, color='red', linestyle='--', linewidth=0.8) # Add a line at 0%
    plt.legend()
    plt.show()
Enter fullscreen mode Exit fullscreen mode

A line chart titled

This bar chart visualizes Tesla's Net Income or Loss for each fiscal period from 2011 to 2023. The chart clearly shows a transition from consistent net losses in the earlier years to significant and growing net income in the more recent years, indicating a strong trend toward profitability.

This bar chart compares Tesla's Revenues and Cost of Revenue from 2011 to 2023. Both metrics show a dramatic and consistent upward trend over the years, reflecting the company's rapid growth. The revenue bars are consistently taller than the cost of revenue bars, especially in later years.

This line chart tracks Tesla's Gross Margin and Net Margin as percentages from 2011 to 2023. The Net Margin starts below zero, indicating net losses, but crosses into positive territory around 2020 and has been increasing since. The Gross Margin remains positive throughout the period and is consistently higher than the Net Margin, showing the company's core profitability from its operations.

Final Thoughts
This guide showed how to use FinFeedAPI's aggregated XBRL endpoint to perform a quick but insightful analysis of a company's financial performance. By fetching structured data directly, you can bypass the complexities of parsing HTML or raw XBRL and move straight to analysis and visualization. You can extend this script to compare multiple companies, track different financial metrics, or integrate the data with other market information.

Top comments (0)