OHLC.dev editorialMARKET

MarketFlow Trader Intelligence: Warren Buffett Portfolio & Stock Split Analysis

MarketFlow Trader Intelligence is a Python-based financial analytics system that evaluates Warren Buffett's portfolio concentration, analyzes stock split events, calculates HHI, and generates an automated trading intelligence dashboard.

November 18, 202619 min readRafatar
MarketFlow Trader Intelligence: Warren Buffett Portfolio & Stock Split Analysis

Financial market analysis involves more than monitoring stock prices and market movements. Investors and financial analysts also examine portfolio composition, investment concentration, and corporate actions to understand the characteristics of financial instruments and identify events that may require further investigation.

One important aspect of investment analysis is portfolio concentration. A portfolio with a large proportion of assets allocated to a limited number of companies may have different risk characteristics from a portfolio distributed across many holdings. Therefore, evaluating the distribution of portfolio weights is an important component of financial portfolio analysis.

Warren Buffett's investment portfolio provides an interesting case for examining portfolio composition and concentration. By retrieving portfolio records from financial data providers, analysts can identify reported holdings, examine their relative weights, and calculate concentration measurements.

Another important component of financial market intelligence is corporate action monitoring. Stock splits are corporate actions in which a company changes the number of outstanding shares by adjusting the number of shares held by existing shareholders. Although stock splits change share quantities and corresponding per-share prices, they do not independently establish whether a stock is bullish or bearish.

Combining portfolio information with corporate action data can provide an additional analytical perspective. For example, identifying stock split events associated with instruments appearing in a particular portfolio can help analysts organize corporate events according to their relevance to the selected portfolio.

Python offers an effective environment for automating these analytical processes. Through libraries such as Requests, Pandas, NumPy, and Matplotlib, financial information can be retrieved from APIs, transformed into structured datasets, evaluated statistically, and presented through visual dashboards.

This article presents the MarketFlow Trader Intelligence System, a Python-based analytical framework that integrates Warren Buffett portfolio information with stock split event records using the MarketFlow All-in-One Market Finance API through RapidAPI.

The system retrieves portfolio data using the /portofolio-checks endpoint with the investor identifier warren-buffett and the reference date 2024-06-30. It also retrieves stock split events using the /splits-events endpoint for the period November 2–9, 2025.

The analytical workflow includes five computational stages: API configuration and authentication, financial data extraction, data cleaning and normalization, portfolio and corporate action analysis, and dashboard generation.

The portfolio analysis module calculates the number of reported holdings, unique ticker symbols, top-five concentration, top-ten concentration, and portfolio HHI. Meanwhile, the stock split analysis module identifies corporate action events, standardizes ticker symbols, and compares event instruments against the retrieved portfolio holdings.

The framework also implements an event-based Trader Score to organize stock split records into priority categories. These classifications are used to generate a watchlist for further investigation.

The primary objective of this project is to develop an automated financial intelligence workflow that combines portfolio concentration analysis and corporate action monitoring into a single Python-based analytical platform.

An important consideration is that the portfolio and stock split datasets have different reference dates. Consequently, the matching process represents a comparison between two datasets from different periods rather than a synchronized historical portfolio-event analysis.

2. Methodology

The MarketFlow Trader Intelligence System is organized into five computational cells. Each cell performs a specific function within the financial data retrieval and analytical workflow.

Cell

Main function

Cell 1

Library imports, API authentication, configuration, and HTTP session.

Cell 2

Warren Buffett portfolio and stock split event extraction.

Cell 3

JSON extraction, data normalization, and CSV exports.

Cell 4

Portfolio concentration, HHI, ticker matching, and Trader Score.

Cell 5

Dashboard visualization, Excel export, and final reporting.

2.1. System Configuration and API Authentication

The first computational cell establishes the system configuration and API authentication.

The framework uses Requests for HTTP communication, Pandas for financial data processing, NumPy for numerical calculations, Matplotlib for visualization, and JSON for handling API responses.

The API host is configured as marketflow-all-in-one-market-finance-api.p.rapidapi.com.

Authentication uses a RapidAPI key retrieved from the RAPIDAPI_KEY environment variable. If the environment variable is unavailable, the program requests the key through Python's getpass function.

The analysis parameters define the investor identifier, portfolio reference date, stock split reporting period, and output directory.

The output directory is named MarketFlow_Trader_Intelligence.

A persistent Requests session is also established to reuse the authentication headers across API requests.

Code — Cell 1: Configuration and API Authentication

# ============================================================
# CELL 1 - MARKETFLOW TRADER INTELLIGENCE
# ============================================================

import os
import re
import json
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from pathlib import Path
from getpass import getpass
from datetime import datetime
from IPython.display import display, Markdown

# API CONFIGURATION
API_HOST = "marketflow-all-in-one-market-finance-api.p.rapidapi.com"
BASE_URL = f"https://{API_HOST}"

API_KEY = os.getenv("RAPIDAPI_KEY", "").strip()

if not API_KEY:
    API_KEY = getpass("Enter RapidAPI Key: ").strip()

if not API_KEY:
    raise ValueError("RapidAPI Key is required.")

HEADERS = {
    "x-rapidapi-key": API_KEY,
    "x-rapidapi-host": API_HOST
}

# ANALYSIS PARAMETERS
INVESTOR = "warren-buffett"
REPORT_DATE = "2024-06-30"

START_DATE = "2025-11-02"
END_DATE = "2025-11-09"

# OUTPUT DIRECTORY
OUTPUT_DIR = Path("MarketFlow_Trader_Intelligence")
OUTPUT_DIR.mkdir(exist_ok=True)

# HTTP SESSION
SESSION = requests.Session()
SESSION.headers.update(HEADERS)

def api_request(endpoint, params):

    url = f"{BASE_URL}/{endpoint}"

    response = SESSION.get(
        url,
        params=params,
        timeout=45
    )

    response.raise_for_status()

    return response.json()

print("=" * 65)
print("MARKETFLOW PORTFOLIO & CORPORATE ACTION INTELLIGENCE")
print("=" * 65)

print("Investor       :", INVESTOR)
print("Portfolio Date :", REPORT_DATE)
print("Split Period   :", START_DATE, "-", END_DATE)
print("Output Folder  :", OUTPUT_DIR)
print("System Status  : INITIALIZED")
print("=" * 65)

2.2. API Data Extraction

The second computational cell retrieves two financial datasets from the MarketFlow API.

The first dataset contains Warren Buffett's portfolio records. The system accesses the /portofolio-checks endpoint using three parameters:

  • lang: English language configuration.

  • report_date: June 30, 2024.

  • slug: warren-buffett.

The second dataset contains stock split event records. The system accesses the /splits-events endpoint using the skip, start_date, and end_date parameters.

Both API requests are executed independently using a loop. This allows the system to identify successful and failed requests without preventing the other dataset from being processed.

The original API responses are stored in JSON format to preserve the retrieved financial information.

An API collection status table is also generated to document the retrieval status of each dataset.

Code — Cell 2: API Data Extraction

# ============================================================
# CELL 2 - API DATA EXTRACTION
# ============================================================

api_results = {}
api_status = []

# 1. WARREN BUFFETT PORTFOLIO
requests_config = {
    "portfolio": {
        "endpoint": "/portofolio-checks",
        "params": {
            "lang": "en",
            "report_date": REPORT_DATE,
            "slug": INVESTOR
        }
    },

    # 2. STOCK SPLIT EVENTS
    "splits": {
        "endpoint": "/splits-events",
        "params": {
            "skip": 0,
            "start_date": START_DATE,
            "end_date": END_DATE
        }
    }
}

for name, config in requests_config.items():

    try:

        data = api_request(
            config["endpoint"],
            config["params"]
        )

        api_results[name] = data

        api_status.append({
            "Dataset": name.upper(),
            "Status": "SUCCESS",
            "Records": "Retrieved"
        })

        # Save raw JSON
        with open(
            OUTPUT_DIR / f"{name}_raw.json",
            "w",
            encoding="utf-8"
        ) as f:

            json.dump(
                data,
                f,
                indent=4,
                ensure_ascii=False,
                default=str
            )

        print(f"[SUCCESS] {name.upper()} retrieved.")

    except Exception as error:

        api_results[name] = None

        api_status.append({
            "Dataset": name.upper(),
            "Status": "FAILED",
            "Records": str(error)
        })

        print(f"[ERROR] {name.upper()}: {error}")

api_status_df = pd.DataFrame(api_status)

print("\nAPI COLLECTION STATUS")
display(api_status_df)

print("\nRAW RESPONSE PREVIEW")

for name, data in api_results.items():

    print(f"\n--- {name.upper()} ---")

    print(
        json.dumps(
            data,
            indent=2,
            ensure_ascii=False,
            default=str
        )[:2500]
        if data is not None else "No data available."
    )

2.3. Data Cleaning and Normalization

The third computational cell transforms the raw API responses into structured datasets.

The system implements an extract_records() function to identify financial records within nested JSON responses.

The function supports list and dictionary structures and prioritizes commonly used data containers, including:

  • data

  • results

  • items

  • portfolio

  • holdings

  • events

  • splits

  • records

When these preferred keys are unavailable, the function examines nested objects and selects the candidate containing the largest number of extracted records.

The normalize_data() function then converts the extracted records into Pandas DataFrames using pd.json_normalize().

After normalization, all column names are standardized into lowercase format to simplify subsequent field identification.

The resulting datasets are stored in two CSV files:

  • portfolio_normalized.csv

  • stock_splits_normalized.csv

This process establishes a consistent structure for the portfolio and corporate action analytical modules.

Code — Cell 3: Data Cleaning and Normalization

# ============================================================
# CELL 3 - DATA CLEANING & NORMALIZATION
# ============================================================

def extract_records(data):

    if data is None:
        return []

    if isinstance(data, list):

        if all(isinstance(x, dict) for x in data):
            return data

        results = []

        for item in data:
            results.extend(extract_records(item))

        return results

    if isinstance(data, dict):

        preferred = [
            "data", "results", "items",
            "portfolio", "holdings",
            "events", "splits", "records"
        ]

        for key in preferred:

            if key in data:

                records = extract_records(data[key])

                if records:
                    return records

        candidates = []

        for value in data.values():

            if isinstance(value, (dict, list)):

                records = extract_records(value)

                if records:
                    candidates.append(records)

        if candidates:
            return max(candidates, key=len)

        return [data]

    return []


def normalize_data(data):

    records = extract_records(data)

    if not records:
        return pd.DataFrame()

    return pd.json_normalize(records, sep="_")


# NORMALIZE DATASETS
portfolio_df = normalize_data(
    api_results["portfolio"]
)

splits_df = normalize_data(
    api_results["splits"]
)

# STANDARDIZE COLUMN NAMES
portfolio_df.columns = [
    str(c).strip().lower() for c in portfolio_df.columns
]

splits_df.columns = [
    str(c).strip().lower() for c in splits_df.columns
]

print("=" * 65)
print("DATA NORMALIZATION RESULTS")
print("=" * 65)

print("\nPORTFOLIO RECORDS :", len(portfolio_df))
print("SPLIT RECORDS     :", len(splits_df))

print("\nPORTFOLIO COLUMNS")
print(portfolio_df.columns.tolist())

print("\nSPLIT EVENT COLUMNS")
print(splits_df.columns.tolist())

print("\nPORTFOLIO DATA PREVIEW")
display(portfolio_df.head(10))

print("\nSTOCK SPLIT DATA PREVIEW")
display(splits_df.head(10))

# Save normalized data
portfolio_df.to_csv(
    OUTPUT_DIR / "portfolio_normalized.csv",
    index=False
)

splits_df.to_csv(
    OUTPUT_DIR / "stock_splits_normalized.csv",
    index=False
)

2.4. Portfolio and Corporate Action Analytics

The fourth computational cell represents the main analytical engine of the framework.

The analysis consists of five interconnected components.

A. Portfolio Analysis

The system identifies relevant portfolio fields, including ticker symbols, company names, market values, and portfolio weights.

The find_column() function searches for matching column names using predefined keywords.

The clean_symbol() function standardizes ticker symbols by converting them to uppercase and removing special characters.

The to_numeric() function transforms numerical fields into usable numeric values by removing currency symbols, percentage signs, and formatting characters.

If portfolio weights are unavailable but market values are present, the system calculates portfolio weights using the following formula:

\[ W_i=\frac{V_i}{\sum_{j=1}^{n}V_j}\times100 \]

Where:

  • \(W_i\) = Portfolio weight of asset \(i\).

  • \(V_i\) = Market value of asset \(i\).

  • \(n\) = Total number of portfolio holdings.

B. Portfolio Concentration

The framework calculates the combined weights of the five and ten largest holdings.

\[ C_5=\sum_{i=1}^{5}W_i \]

\[ C_{10}=\sum_{i=1}^{10}W_i \]

The system also calculates the Herfindahl-Hirschman Index:

\[ HHI=\sum_{i=1}^{n}s_i^2 \]

Where \(s_i\) represents the normalized portfolio share of each holding.

A higher HHI indicates a more concentrated portfolio distribution, while a lower value indicates a more distributed allocation.

C. Stock Split Analysis

The stock split module identifies ticker symbols, split ratios, and event dates.

The event date is converted into a datetime format, while ticker symbols are standardized using the same cleaning function used in portfolio analysis.

D. Portfolio and Split Matching

The system compares the standardized portfolio ticker symbols with the ticker symbols associated with stock split events.

The matching process produces a Boolean variable named in_buffett_portfolio.

If an event instrument is found in the portfolio ticker set, its matching status is classified as True.

E. Trader Score and Priority Classification

The system implements an event-based scoring mechanism:

\[ TraderScore= \begin{cases} 85, & \text{if portfolio matched}\\ 50, & \text{otherwise} \end{cases} \]

Priority classification is then determined as follows:

Trader Score

Priority

80 or higher

HIGH

50 or higher

MEDIUM

Below 50

LOW

This score represents event-screening priority rather than the probability of investment success or future stock price movements.

Code — Cell 4: Full Portfolio and Stock Split Analytics Engine

# ============================================================
# CELL 4 - TRADER ANALYTICS ENGINE
# ============================================================

def find_column(df, keywords):

    for keyword in keywords:

        matches = [
            c for c in df.columns
            if keyword in c.lower()
        ]

        if matches:
            return matches[0]

    return None


def clean_symbol(value):

    if pd.isna(value):
        return ""

    return re.sub(
        r"[^A-Z0-9]",
        "",
        str(value).upper().split(".")[0]
    )


def to_numeric(series):

    return pd.to_numeric(
        series.astype(str).str.replace(
            r"[$,% ,]",
            "",
            regex=True
        ),
        errors="coerce"
    )


# ------------------------------------------------------------
# A. PORTFOLIO ANALYSIS
# ------------------------------------------------------------

ticker_col = find_column(
    portfolio_df,
    ["ticker", "symbol", "stock_code", "security"]
)

name_col = find_column(
    portfolio_df,
    ["company_name", "company", "name"]
)

value_col = find_column(
    portfolio_df,
    ["market_value", "position_value",
     "holding_value", "value"]
)

weight_col = find_column(
    portfolio_df,
    ["portfolio_weight", "weight", "percentage"]
)

portfolio = portfolio_df.copy()

if ticker_col:

    portfolio["ticker_clean"] = (
        portfolio[ticker_col].apply(clean_symbol)
    )

else:

    portfolio["ticker_clean"] = ""

if value_col:

    portfolio["numeric_value"] = to_numeric(
        portfolio[value_col]
    )

else:

    portfolio["numeric_value"] = np.nan

if weight_col:

    portfolio["numeric_weight"] = to_numeric(
        portfolio[weight_col]
    )

else:

    portfolio["numeric_weight"] = np.nan

# Calculate weights when market value is available
if (
    portfolio["numeric_weight"].isna().all()
    and portfolio["numeric_value"].notna().any()
):

    total_value = portfolio["numeric_value"].sum()

    if total_value > 0:

        portfolio["numeric_weight"] = (
            portfolio["numeric_value"] /
            total_value * 100
        )

# ------------------------------------------------------------
# B. PORTFOLIO CONCENTRATION
# ------------------------------------------------------------

valid_weights = (
    portfolio["numeric_weight"]
    .dropna()
    .sort_values(ascending=False)
)

top_5_weight = valid_weights.head(5).sum()

top_10_weight = valid_weights.head(10).sum()

if len(valid_weights) > 0:

    weights = valid_weights / valid_weights.sum()

    hhi = (weights ** 2).sum()

else:

    hhi = np.nan

# ------------------------------------------------------------
# C. STOCK SPLIT ANALYSIS
# ------------------------------------------------------------

split_ticker_col = find_column(
    splits_df,
    ["ticker", "symbol", "stock_code"]
)

ratio_col = find_column(
    splits_df,
    ["split_ratio", "ratio", "split"]
)

date_col = find_column(
    splits_df,
    ["execution_date", "effective_date",
     "date", "split_date"]
)

splits = splits_df.copy()

if split_ticker_col:

    splits["ticker_clean"] = (
        splits[split_ticker_col].apply(clean_symbol)
    )

else:

    splits["ticker_clean"] = ""

if date_col:

    splits["event_date"] = pd.to_datetime(
        splits[date_col],
        errors="coerce"
    )

else:

    splits["event_date"] = pd.NaT

# ------------------------------------------------------------
# D. PORTFOLIO & SPLIT MATCHING
# ------------------------------------------------------------

portfolio_tickers = set(
    portfolio.loc[
        portfolio["ticker_clean"] != "",
        "ticker_clean"
    ]
)

splits["in_buffett_portfolio"] = (
    splits["ticker_clean"].isin(portfolio_tickers)
)

# Event-based priority scoring
splits["trader_score"] = np.where(
    splits["in_buffett_portfolio"], 85, 50
)

splits["priority"] = np.select(
    [
        splits["trader_score"] >= 80,
        splits["trader_score"] >= 50
    ],
    [
        "HIGH",
        "MEDIUM"
    ],
    default="LOW"
)

# Sort watchlist
watchlist = splits.sort_values(
    ["trader_score", "event_date"],
    ascending=[False, True]
).copy()

# ------------------------------------------------------------
# E. KEY METRICS
# ------------------------------------------------------------

portfolio_summary = {
    "Investor": INVESTOR,
    "Report Date": REPORT_DATE,
    "Portfolio Holdings": len(portfolio),
    "Unique Tickers": len(portfolio_tickers),
    "Top 5 Concentration (%)": round(top_5_weight, 2),
    "Top 10 Concentration (%)": round(top_10_weight, 2),
    "Portfolio HHI": round(hhi, 4) if pd.notna(hhi) else None,
    "Stock Split Events": len(splits),
    "Portfolio-Matched Events": int(
        splits["in_buffett_portfolio"].sum()
    )
}

print("=" * 65)
print("MARKETFLOW TRADER ANALYTICS")
print("=" * 65)

for key, value in portfolio_summary.items():
    print(f"{key:<32}: {value}")

print("\nTOP 10 PORTFOLIO HOLDINGS")

if value_col:
    display(
        portfolio.sort_values(
            "numeric_value",
            ascending=False,
            na_position="last"
        ).head(10)
    )
else:
    display(portfolio.head(10))

print("\nSTOCK SPLIT TRADING WATCHLIST")

display(watchlist.head(20))

2.5. Trader Dashboard and Final Results

The fifth computational cell integrates the portfolio analysis and corporate action results into a four-panel dashboard.

The visualization is generated using Matplotlib with a two-by-two subplot arrangement.

The dashboard contains four analytical components.

1. Top 10 Portfolio Holdings

This panel displays the ten largest portfolio holdings based on reported market values. If market value information is unavailable, the dashboard displays a message indicating that the required information is not available.

2. Portfolio Weight Distribution

This panel presents the portfolio allocation using a pie chart based on the available portfolio weights.

The visualization displays up to eight holdings to provide a simplified overview of the portfolio distribution.

3. Stock Split Event Priority

This panel illustrates the number of HIGH, MEDIUM, and LOW priority stock split events.

The visualization helps identify the distribution of events according to the predefined Trader Score classification.

4. Portfolio and Split Event Matching

This panel compares the number of stock split events that match the retrieved portfolio ticker symbols with the number of events that do not match.

The dashboard is exported as marketflow_trader_dashboard.png with a resolution of 300 DPI.

The system also generates a consolidated text report and an Excel workbook containing five worksheets:

  • Portfolio.

  • Stock Splits.

  • Trader Watchlist.

  • API Status.

  • Summary.

These outputs allow the analytical results to be examined using Python, Microsoft Excel, and other financial data analysis tools.

Code — Cell 5: Full Dashboard, Reporting, and Excel Export

# ============================================================
# CELL 5 - DASHBOARD & FINAL RESULTS
# ============================================================

plt.rcParams["figure.figsize"] = (15, 10)

fig, axes = plt.subplots(2, 2)

fig.suptitle(
    "MARKETFLOW TRADER INTELLIGENCE DASHBOARD",
    fontsize=17,
    fontweight="bold"
)

# ------------------------------------------------------------
# 1. TOP PORTFOLIO HOLDINGS
# ------------------------------------------------------------

ax = axes[0, 0]

if value_col and portfolio["numeric_value"].notna().any():

    top = portfolio.nlargest(
        10, "numeric_value"
    )

    labels = (
        top["ticker_clean"]
        .replace("", "UNKNOWN")
    )

    ax.barh(labels, top["numeric_value"])
    ax.set_title("TOP 10 PORTFOLIO HOLDINGS")
    ax.invert_yaxis()
    ax.set_xlabel("Reported Market Value")

else:

    ax.text(
        0.5, 0.5,
        "Market value data unavailable",
        ha="center",
        va="center"
    )

    ax.set_title("PORTFOLIO HOLDINGS")

# ------------------------------------------------------------
# 2. PORTFOLIO WEIGHT DISTRIBUTION
# ------------------------------------------------------------

ax = axes[0, 1]

weights = portfolio["numeric_weight"].dropna()

if len(weights) > 0:

    ax.pie(
        weights.head(8),
        labels=portfolio.loc[
            weights.head(8).index,
            "ticker_clean"
        ],
        autopct="%1.1f%%",
        startangle=90
    )

    ax.set_title("PORTFOLIO WEIGHT DISTRIBUTION")

else:

    ax.text(
        0.5, 0.5,
        "Weight data unavailable",
        ha="center",
        va="center"
    )

    ax.set_title("PORTFOLIO ALLOCATION")

# ------------------------------------------------------------
# 3. SPLIT EVENT PRIORITY
# ------------------------------------------------------------

ax = axes[1, 0]

if len(watchlist) > 0:

    priority_counts = (
        watchlist["priority"]
        .value_counts()
        .reindex(
            ["HIGH", "MEDIUM", "LOW"],
            fill_value=0
        )
    )

    ax.bar(
        priority_counts.index,
        priority_counts.values
    )

    ax.set_title("STOCK SPLIT EVENT PRIORITY")
    ax.set_ylabel("Number of Events")

else:

    ax.text(
        0.5, 0.5,
        "No split events available",
        ha="center",
        va="center"
    )

    ax.set_title("EVENT PRIORITY")

# ------------------------------------------------------------
# 4. PORTFOLIO MATCHING
# ------------------------------------------------------------

ax = axes[1, 1]

matched = int(
    splits["in_buffett_portfolio"].sum()
)

unmatched = len(splits) - matched

ax.bar(
    ["Portfolio Match", "Other Events"],
    [matched, unmatched]
)

ax.set_title("PORTFOLIO & SPLIT EVENT MATCH")
ax.set_ylabel("Number of Events")

plt.tight_layout(rect=[0, 0, 1, 0.95])

dashboard_path = (
    OUTPUT_DIR / "marketflow_trader_dashboard.png"
)

plt.savefig(
    dashboard_path,
    dpi=300,
    bbox_inches="tight"
)

plt.show()

# ------------------------------------------------------------
# FINAL REPORT
# ------------------------------------------------------------

report = []

report.append("=" * 65)
report.append("MARKETFLOW TRADER INTELLIGENCE REPORT")
report.append("=" * 65)

for key, value in portfolio_summary.items():

    report.append(f"{key:<32}: {value}")

report.append("\nTRADER INTERPRETATION")

if len(portfolio) > 0:

    report.append(
        f"- Portfolio records retrieved: {len(portfolio)}"
    )

if pd.notna(hhi):

    report.append(
        f"- Portfolio HHI concentration: {hhi:.4f}"
    )

if len(splits) > 0:

    report.append(
        f"- Total stock split events: {len(splits)}"
    )

    report.append(
        f"- Portfolio-matched events: {matched}"
    )

    report.append(
        f"- High-priority events: "
        f"{int((watchlist['priority'] == 'HIGH').sum())}"
    )

else:

    report.append("- No stock split events retrieved.")

report.append("\nANALYTICAL LIMITATIONS")

report.append(
    "- Portfolio and split datasets have different reference dates."
)

report.append(
    "- Trader Score represents event-screening priority, "
    "not a predictive probability."
)

report.append(
    "- Stock splits do not independently indicate bullish "
    "or bearish price direction."
)

report.append(
    "- Price action, volume, valuation, and risk management "
    "must be evaluated separately."
)

report.append("=" * 65)

final_report = "\n".join(report)

print(final_report)

# Save report
with open(
    OUTPUT_DIR / "trader_analysis_report.txt",
    "w",
    encoding="utf-8"
) as f:

    f.write(final_report)

# ------------------------------------------------------------
# EXPORT EXCEL
# ------------------------------------------------------------

excel_path = OUTPUT_DIR / "marketflow_trader_analysis.xlsx"

with pd.ExcelWriter(
    excel_path,
    engine="openpyxl"
) as writer:

    portfolio.to_excel(
        writer,
        sheet_name="Portfolio",
        index=False
    )

    splits.to_excel(
        writer,
        sheet_name="Stock Splits",
        index=False
    )

    watchlist.to_excel(
        writer,
        sheet_name="Trader Watchlist",
        index=False
    )

    api_status_df.to_excel(
        writer,
        sheet_name="API Status",
        index=False
    )

    pd.DataFrame(
        list(portfolio_summary.items()),
        columns=["Metric", "Value"]
    ).to_excel(
        writer,
        sheet_name="Summary",
        index=False
    )

print("\n" + "=" * 65)
print("PROJECT COMPLETED SUCCESSFULLY")
print("=" * 65)

print("\nOUTPUT FILES:")

for file in OUTPUT_DIR.iterdir():

    print(f"- {file.name}")

print("\nDashboard :", dashboard_path)
print("Excel     :", excel_path)
print("Report    :", OUTPUT_DIR / "trader_analysis_report.txt")

Result:

3. Results and Discussion

3.1. API Data Collection Results

The API extraction module retrieves two independent financial datasets: Warren Buffett's portfolio information and stock split event records.

The portfolio dataset uses a reference date of June 30, 2024, while the stock split dataset covers November 2–9, 2025.

The API collection module records the retrieval status of each dataset and preserves the original responses in JSON format.

This separation allows the system to process each financial information source independently and maintain the original data for verification.

3.2. Portfolio Composition and Concentration Analysis

Portfolio concentration analysis evaluates how reported portfolio weights are distributed across the retrieved holdings.

The framework calculates the combined allocation of the five largest holdings and the ten largest holdings.

The HHI calculation provides an additional measurement of portfolio concentration by considering the squared normalized weights of individual holdings.

The combination of these measurements allows analysts to examine the relative distribution of reported investments.

A higher concentration indicates that a larger proportion of portfolio exposure is allocated to a smaller number of holdings.

However, concentration measurements alone do not establish whether a portfolio is financially attractive or whether its holdings will generate positive returns.

3.3. Stock Split Event Analysis

The stock split module processes corporate action records retrieved from the MarketFlow API.

Each event is standardized through ticker cleaning and date conversion.

The resulting dataset contains the normalized instrument symbol, event date, and portfolio matching status.

This structure provides a consistent basis for examining the relationship between stock split events and the selected portfolio.

The system also creates a watchlist containing the retrieved events, ordered according to their Trader Score and event date.

3.4. Portfolio and Corporate Action Matching

Portfolio-event matching is performed by comparing normalized ticker symbols.

The matching mechanism identifies whether an instrument associated with a stock split event is present in the retrieved portfolio dataset.

The results are divided into two groups:

  • Portfolio Match: stock split events associated with instruments found in the portfolio.

  • Other Events: stock split events associated with instruments not found in the portfolio.

This classification provides a simple way to prioritize corporate action records for additional examination.

Nevertheless, the matching results must be interpreted carefully because the portfolio reference date and stock split event period are different.

A match indicates symbol overlap between the two datasets, not proof that the investor held the security on the stock split event date.

3.5. Trader Score and Priority Classification

The Trader Score mechanism assigns a value of 85 to portfolio-matched events and 50 to events that do not match the selected portfolio.

These scores are converted into HIGH and MEDIUM priority classifications under the predefined rules.

The classification provides a systematic event-screening mechanism that allows analysts to organize stock split records according to their relationship with the selected portfolio.

The score should not be interpreted as a prediction of future stock price performance, trading success, or investment probability.

3.6. Financial Dashboard Visualization

The final dashboard combines four analytical components into one visual interface.

MarketFlow Trader Intelligence Dashboard

Portfolio Holdings

Top ten holdings by reported market value.

Portfolio Allocation

Distribution of portfolio weights.

Split Event Priority

HIGH, MEDIUM, and LOW event classifications.

Portfolio Matching

Matched and unmatched stock split events.

Dashboard layout generated by the supplied Python implementation. Numerical chart values depend on actual API responses.

The dashboard is exported as a PNG image with 300 DPI resolution, allowing the visualization to be incorporated into financial reports and research documentation.

3.7. Exported Analytical Outputs

The system generates several output files to support further examination of the financial data.

Filename

Description

portfolio_raw.json

Original portfolio API response.

splits_raw.json

Original stock split API response.

portfolio_normalized.csv

Normalized portfolio dataset.

stock_splits_normalized.csv

Normalized stock split dataset.

marketflow_trader_dashboard.png

Four-panel analytical dashboard.

trader_analysis_report.txt

Consolidated financial intelligence report.

marketflow_trader_analysis.xlsx

Excel workbook with five analytical worksheets.

The Excel workbook contains Portfolio, Stock Splits, Trader Watchlist, API Status, and Summary worksheets.

This provides a structured environment for reviewing portfolio information, examining corporate action records, and inspecting the analytical results.

3.8. Analytical Limitations and Future Improvements

Several limitations should be considered when interpreting the framework's results.

First, the datasets have different reference dates. The portfolio information is dated June 30, 2024, while stock split events are retrieved for November 2025. Therefore, the matching results cannot establish historical ownership at the event date.

Second, ticker matching depends on symbol availability and standardization. If the API returns different ticker formats, missing symbols, or identifiers that are not directly comparable, some matching results may be incomplete.

Third, the Trader Score uses fixed values. The scores of 85 and 50 are predefined screening parameters, not statistically validated predictive measurements.

Fourth, portfolio concentration depends on the availability and interpretation of weight data. If weights are missing, the system attempts to calculate them using reported market values.

Fifth, the framework does not calculate investment returns or price reactions following stock splits. It therefore cannot determine whether the corporate actions produce positive or negative market performance.

Sixth, stock splits do not independently indicate bullish or bearish market direction. Further evaluation requires price action, trading volume, valuation, and risk management information.

Future improvements could include:

  • Historical portfolio snapshots aligned with corporate action dates.

  • More robust security identifier matching.

  • Stock split ratio normalization.

  • Historical price and volume integration.

  • Post-split price performance analysis.

  • Portfolio return and volatility calculations.

  • Dividend and earnings event integration.

  • Backtesting of corporate action monitoring strategies.

  • Weighted event prioritization based on additional financial variables.

  • Automated event alerts and scheduled portfolio monitoring.

These improvements could transform the framework into a more comprehensive financial research and investment monitoring platform.

4. Conclusion

This article presents the MarketFlow Trader Intelligence System, a Python-based financial analytics framework developed using the MarketFlow All-in-One Market Finance API through RapidAPI.

The system integrates Warren Buffett portfolio data dated June 30, 2024, with stock split event records retrieved for November 2–9, 2025.

The analytical workflow incorporates API authentication, financial data extraction, JSON normalization, portfolio concentration analysis, HHI calculation, stock split event identification, ticker matching, and event-based priority classification.

The portfolio analysis module evaluates the number of holdings, unique ticker symbols, top-five concentration, top-ten concentration, and portfolio HHI.

Meanwhile, the corporate action module identifies stock split events and compares their associated ticker symbols against the retrieved portfolio holdings.

The framework also implements a Trader Score mechanism to classify stock split events into HIGH, MEDIUM, and LOW priority categories.

The final dashboard integrates portfolio holdings, portfolio weight distribution, split event priority, and portfolio-event matching into a single visualization.

Additionally, the system generates normalized CSV datasets, an Excel workbook, a dashboard image, and a consolidated financial intelligence report.

Overall, the MarketFlow Trader Intelligence System demonstrates how Python and financial APIs can be integrated to automate portfolio analysis and corporate action monitoring.

However, the system should be considered an event-screening and financial data analysis framework rather than a predictive trading system. The differences in dataset reference dates, limitations in ticker matching, and rule-based Trader Score require careful interpretation.

Future integration of historical portfolio snapshots, market prices, trading volumes, and performance evaluation could further improve the framework's analytical capabilities.