OHLC.dev editorialMARKET

MarketFlow Trader Intelligence Analyzer Using Python: Warren Buffett Analysis

MarketFlow Trader Intelligence Analyzer is a Python-based financial analytics system that evaluates Warren Buffett's BUY and SELL transactions, measures trading activity, analyzes Bitcoin market conditions, and generates an automated financial dashboard.

November 19, 202622 min readRafatar
MarketFlow Trader Intelligence Analyzer Using Python: Warren Buffett Analysis

Financial market analysis requires an understanding of both trading behavior and broader market conditions. Investors and financial analysts examine transaction records, trading volumes, market prices, and historical volatility to identify patterns that may provide additional insights into financial activity.

One important component of financial intelligence is trader activity analysis. By examining BUY and SELL transactions, analysts can evaluate the distribution of trading activities, compare transaction values, and identify whether the recorded activity is dominated by buying or selling.

Transaction frequency alone, however, does not fully describe trading behavior. A trader may execute numerous small transactions while conducting only a few large transactions that represent a substantial proportion of total trading value. Therefore, transaction value analysis provides an additional perspective beyond simply counting the number of transactions.

Warren Buffett provides an interesting subject for examining reported investor trading activity. By retrieving available transaction records associated with his investor profile, analysts can organize BUY and SELL activities and calculate several descriptive financial measurements.

Another important component is market context. Trading activity should not be examined independently from the broader market environment. Historical market prices can provide additional information about price movements, trend direction, volatility, and potential downside exposure.

Bitcoin is selected as the contextual market instrument in this project, using the BINANCE:BTCUSDT trading pair. Historical daily market data are retrieved to calculate market returns, moving averages, annualized volatility, and maximum drawdown.

Python provides an effective environment for integrating these analytical processes. Through libraries such as Requests, Pandas, NumPy, and Matplotlib, financial data can be retrieved from external APIs, transformed into structured datasets, analyzed quantitatively, and presented through visual dashboards.

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

The system retrieves BUY and SELL transaction records using the /trade-activity endpoint. Both datasets are filtered using the investor identifier warren-buffett and the analysis period April 1 to July 1, 2025.

The framework also retrieves historical market information through the /v2/chart/historical endpoint using the BINANCE:BTCUSDT symbol, daily timeframe, and Asia/Jakarta timezone.

The analytical workflow consists of five computational stages:

  1. API configuration and authentication.

  2. Financial transaction and historical market data retrieval.

  3. JSON extraction and data normalization.

  4. Trader intelligence and quantitative market analysis.

  5. Dashboard visualization and analytical report generation.

The primary objective is to develop an automated financial analysis workflow capable of combining trader transaction behavior with historical market conditions.

An important distinction is that Bitcoin market data serve as contextual information within the framework. The retrieved BTCUSDT price movements do not establish a direct relationship with Warren Buffett's reported transactions.

2. Methodology

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

Cell

Main function

Cell 1

Library imports, API authentication, trader parameters, and market configuration.

Cell 2

BUY transactions, SELL transactions, and historical market data retrieval.

Cell 3

JSON extraction, transaction normalization, and OHLCV processing.

Cell 4

Transaction statistics, trader behavior classification, and market analysis.

Cell 5

Dashboard visualization, final report generation, and output exports.

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 data processing, NumPy for numerical calculations, Matplotlib for visualization, JSON for handling API responses, and OS for managing output directories.

The API host is configured as:

marketflow-all-in-one-market-finance-api.p.rapidapi.com

The trader profile is set to warren-buffett, with an analysis period from April 1 to July 1, 2025.

The market configuration uses BINANCE:BTCUSDT as the selected financial instrument. The timeframe is configured as daily (D), with a historical range parameter of 100 and an end-date parameter of December 31, 2025.

The timezone is set to Asia/Jakarta.

The system creates an output directory named marketflow_trader_output to store the retrieved datasets, analytical reports, and visualizations.

For security, the API key should be supplied through an environment variable or secure input rather than embedded directly in publicly shared source code.

Code — Cell 1: Library Imports, Configuration, and API Authentication


# ============================================================
# MARKETFLOW TRADER INTELLIGENCE ANALYZER
# CELL 1: CONFIGURATION & INITIALIZATION
# ============================================================

import requests
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
import os
import warnings
from datetime import datetime

warnings.filterwarnings("ignore")

# API CONFIGURATION
API_KEY = "fd8db84d91msh0aa9aa413565ca5p1c66c9jsn44cc1bc07eb2"

BASE_URL = "https://marketflow-all-in-one-market-finance-api.p.rapidapi.com"

HEADERS = {
    "x-rapidapi-key": API_KEY,
    "x-rapidapi-host": "marketflow-all-in-one-market-finance-api.p.rapidapi.com"
}

# TRADER PARAMETERS
TRADER = "warren-buffett"
START_DATE = "2025-04-01"
END_DATE = "2025-07-01"

# MARKET PARAMETERS
SYMBOL = "BINANCE:BTCUSDT"
TIMEFRAME = "D"
MARKET_RANGE = 100
MARKET_TO = "2025-12-31"
TIMEZONE = "Asia/Jakarta"

LIMIT = 100
OUTPUT_DIR = "marketflow_trader_output"

os.makedirs(OUTPUT_DIR, exist_ok=True)

print("=" * 65)
print("MARKETFLOW TRADER INTELLIGENCE ANALYZER")
print("=" * 65)
print(f"Trader       : {TRADER}")
print(f"Analysis     : {START_DATE} to {END_DATE}")
print(f"Market       : {SYMBOL}")
print(f"Timeframe    : {TIMEFRAME}")
print(f"Output       : {OUTPUT_DIR}")
print("=" * 65)

2.2. Financial Data Collection Through MarketFlow API

The second computational cell retrieves three financial datasets.

The first dataset contains BUY transaction records obtained through the /trade-activity endpoint. The request uses the buy transaction type, a maximum limit of 100 records, the selected trader slug, and the specified analysis period.

The second dataset contains SELL transaction records retrieved through the same endpoint, but with the transaction type configured as sell.

The third dataset contains historical market information obtained through /v2/chart/historical.

The historical market request uses the following parameters:

Parameter

Value

Symbol

BINANCE:BTCUSDT

Timeframe

D

Range

100

To

2025-12-31

Timezone

Asia/Jakarta

Each API response is stored separately in JSON format to preserve the original data.

The system also displays the response type, available JSON keys, and a sample of the retrieved information.

This process provides an initial examination of the API responses before data normalization.

Code — Cell 2: MarketFlow API Data Collection


# ============================================================
# CELL 2: MARKETFLOW API DATA COLLECTION
# ============================================================

def fetch_api(endpoint, params):
    url = f"{BASE_URL}{endpoint}"

    response = requests.get(
        url,
        headers=HEADERS,
        params=params,
        timeout=60
    )

    response.raise_for_status()
    return response.json()


if API_KEY == "MASUKKAN_RAPIDAPI_KEY_ANDA":
    raise ValueError("Masukkan RapidAPI Key pada Cell 1 terlebih dahulu.")

# 1. TRADER BUY ACTIVITY
buy_data = fetch_api(
    "/trade-activity",
    {
        "skip": 0,
        "trade_type": "buy",
        "limit": LIMIT,
        "slug": TRADER,
        "time_range": f"{START_DATE}:{END_DATE}"
    }
)

# 2. TRADER SELL ACTIVITY
sell_data = fetch_api(
    "/trade-activity",
    {
        "skip": 0,
        "trade_type": "sell",
        "limit": LIMIT,
        "slug": TRADER,
        "time_range": f"{START_DATE}:{END_DATE}"
    }
)

# 3. HISTORICAL MARKET DATA
market_data = fetch_api(
    "/v2/chart/historical",
    {
        "range": MARKET_RANGE,
        "timeframe": TIMEFRAME,
        "to": MARKET_TO,
        "timezone": TIMEZONE,
        "symbol": SYMBOL
    }
)

# Save raw API responses
with open(f"{OUTPUT_DIR}/buy_activity.json", "w") as f:
    json.dump(buy_data, f, indent=4)

with open(f"{OUTPUT_DIR}/sell_activity.json", "w") as f:
    json.dump(sell_data, f, indent=4)

with open(f"{OUTPUT_DIR}/historical_market.json", "w") as f:
    json.dump(market_data, f, indent=4)

print("API COLLECTION COMPLETED")
print("-" * 50)

for name, data in [
    ("BUY ACTIVITY", buy_data),
    ("SELL ACTIVITY", sell_data),
    ("HISTORICAL MARKET", market_data)
]:
    print(f"\n{name}")
    print("Response type:", type(data).__name__)

    if isinstance(data, dict):
        print("Available keys:", list(data.keys()))

    print("Sample:", str(data)[:700])

2.3. Data Processing and Normalization

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

The system implements three primary functions.

First, extract_records() identifies meaningful record collections within nested JSON responses. The function examines common data containers such as data, results, trades, items, activity, history, candles, and prices.

Second, find_column() identifies relevant data fields using predefined column aliases. This allows the framework to accommodate differences in field naming between API responses.

Third, normalize_trades() transforms BUY and SELL transaction records into a consistent data structure.

The normalized transaction dataset contains five principal fields:

  • date: transaction date.

  • symbol: financial instrument identifier.

  • price: transaction price.

  • quantity: transaction quantity.

  • value: transaction value.

  • type: BUY or SELL classification.

Transaction dates are converted into UTC datetime format, while numerical fields are converted into numeric data types.

When the transaction value is unavailable but price and quantity are available, the system estimates transaction value using:

\[ Transaction\ Value=Price\times Quantity \]

The framework then combines BUY and SELL datasets into one unified transaction DataFrame.

For historical market information, the system extracts OHLCV fields:

  • Open.

  • High.

  • Low.

  • Close.

  • Volume.

These fields are normalized into a structured market dataset, with timestamps converted into UTC datetime format.

The processed datasets are subsequently exported into CSV files for additional analysis.

Code — Cell 3: Full Data Processing and Normalization


# ============================================================
# CELL 3: DATA PROCESSING & NORMALIZATION
# ============================================================

def extract_records(payload):
    """Find the first meaningful list of records in API response."""

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

        for item in payload:
            result = extract_records(item)
            if result:
                return result

    elif isinstance(payload, dict):
        preferred = [
            "data", "results", "trades", "items",
            "activity", "history", "candles", "prices"
        ]

        for key in preferred:
            if key in payload:
                result = extract_records(payload[key])
                if result:
                    return result

        for value in payload.values():
            if isinstance(value, (dict, list)):
                result = extract_records(value)
                if result:
                    return result

    return []


def find_column(df, candidates):
    lookup = {str(c).lower(): c for c in df.columns}

    for candidate in candidates:
        if candidate.lower() in lookup:
            return lookup[candidate.lower()]

    return None


def normalize_trades(payload, trade_type):
    records = extract_records(payload)

    if not records:
        return pd.DataFrame()

    df = pd.json_normalize(records)

    aliases = {
        "date": [
            "date", "timestamp", "created_at",
            "time", "trade_date", "transaction_date"
        ],
        "symbol": ["symbol", "ticker", "asset"],
        "price": ["price", "trade_price", "execution_price"],
        "quantity": [
            "quantity", "qty", "shares",
            "amount", "units", "size"
        ],
        "value": [
            "value", "trade_value", "total_value",
            "market_value", "amount_usd"
        ]
    }

    output = pd.DataFrame(index=df.index)

    for target, candidates in aliases.items():
        col = find_column(df, candidates)
        output[target] = df[col] if col else np.nan

    output["type"] = trade_type

    output["date"] = pd.to_datetime(
        output["date"], errors="coerce", utc=True
    )

    for col in ["price", "quantity", "value"]:
        output[col] = pd.to_numeric(
            output[col], errors="coerce"
        )

    # Estimate transaction value when price and quantity exist
    missing_value = output["value"].isna()

    output.loc[missing_value, "value"] = (
        output.loc[missing_value, "price"] *
        output.loc[missing_value, "quantity"]
    )

    output["symbol"] = output["symbol"].astype("string")

    return output.drop_duplicates().reset_index(drop=True)


# Process BUY and SELL
buy_df = normalize_trades(buy_data, "BUY")
sell_df = normalize_trades(sell_data, "SELL")

trades = pd.concat(
    [buy_df, sell_df],
    ignore_index=True
)

# Normalize historical OHLCV
market_records = extract_records(market_data)

market_df = pd.json_normalize(market_records)

if not market_df.empty:
    market_aliases = {
        "date": ["time", "timestamp", "date", "datetime"],
        "open": ["open", "o"],
        "high": ["high", "h"],
        "low": ["low", "l"],
        "close": ["close", "c"],
        "volume": ["volume", "vol", "v"]
    }

    normalized_market = pd.DataFrame(index=market_df.index)

    for target, candidates in market_aliases.items():
        col = find_column(market_df, candidates)
        normalized_market[target] = (
            market_df[col] if col else np.nan
        )

    normalized_market["date"] = pd.to_datetime(
        normalized_market["date"],
        errors="coerce",
        utc=True
    )

    for col in ["open", "high", "low", "close", "volume"]:
        normalized_market[col] = pd.to_numeric(
            normalized_market[col], errors="coerce"
        )

    market_df = normalized_market.dropna(
        subset=["date", "close"]
    ).sort_values("date").reset_index(drop=True)

# Save processed datasets
trades.to_csv(
    f"{OUTPUT_DIR}/trader_transactions.csv",
    index=False
)

market_df.to_csv(
    f"{OUTPUT_DIR}/historical_market.csv",
    index=False
)

print("DATA PROCESSING COMPLETED")
print("-" * 50)
print("BUY records :", len(buy_df))
print("SELL records:", len(sell_df))
print("Total trades:", len(trades))
print("Market bars :", len(market_df))

print("\nTransaction sample:")
display(trades.head())

print("\nMarket sample:")
display(market_df.head())

2.4. Trader Intelligence and Quantitative Analysis

The fourth computational cell performs the main analytical calculations.

The analysis is divided into six components.

A. Trader Activity Analysis

The system calculates the total number of BUY and SELL transactions.

\[ Total\ Trades=BUY+SELL \]

The transaction count ratios are calculated as:

\[ BUY\ Ratio=\frac{N_{BUY}}{N_{Total}}\times100 \]

\[ SELL\ Ratio=\frac{N_{SELL}}{N_{Total}}\times100 \]

The framework also calculates the total BUY and SELL transaction values.

\[ Net\ Transaction\ Value=BUY\ Value-SELL\ Value \]

A negative net transaction value indicates that the recorded SELL transaction value exceeds the recorded BUY transaction value.

B. Transaction Value Distribution

The system calculates the following descriptive statistics:

  • Average trade value.

  • Median trade value.

  • Largest trade value.

  • Average daily transactions.

The average trade value is calculated using:

\[ Average\ Trade\ Value= \frac{\sum Transaction\ Values}{N} \]

The median provides a measure of central tendency that is less sensitive to extremely large transactions.

C. Market Analysis

The historical market dataset is used to calculate daily returns.

\[ R_t=\left(\frac{P_t}{P_{t-1}}-1\right)\times100 \]

Where \(P_t\) represents the closing price at time \(t\).

The framework also calculates:

  • Simple Moving Average 20 (SMA 20).

  • Simple Moving Average 50 (SMA 50).

  • Annualized volatility.

  • Highest market price.

  • Lowest market price.

  • Maximum drawdown.

Annualized volatility is calculated using the standard deviation of daily returns multiplied by the square root of 252.

\[ \sigma_{annual}=\sigma_{daily}\times\sqrt{252} \]

Maximum drawdown is calculated from the relationship between the closing price and its historical running maximum.

\[ MDD=\min\left(\frac{P_t}{Peak_t}-1\right)\times100 \]

D. Trader Intelligence Score

The Trader Activity Score measures the imbalance between BUY and SELL transaction values.

\[ Activity\ Score= 50+\frac{|BUY\ Ratio-Sell\ Ratio|}{2} \]

The score is limited to a maximum of 100.

The behavior classification uses the following rules:

Condition

Classification

BUY value ratio greater than 55%

BUY DOMINANT

SELL value ratio greater than 55%

SELL DOMINANT

Neither ratio exceeds 55%

BALANCED ACTIVITY

No valid transaction value

INSUFFICIENT TRANSACTION VALUE DATA

The score measures transaction value dominance, not trader profitability, investment skill, or predictive accuracy.

E. Analytical Interpretation

The system compares total BUY and SELL transaction values to generate a descriptive interpretation.

If BUY value exceeds SELL value, the framework identifies BUY dominance in transaction value.

If SELL value exceeds BUY value, the framework identifies SELL dominance in transaction value.

If both values are equal, the system classifies the transaction values as balanced.

F. Report Generation

All analytical measurements are combined into a dictionary and converted into a structured DataFrame.

The final report includes trader activity, transaction statistics, market performance, market volatility, trend classification, maximum drawdown, and analytical interpretation.

Code — Cell 4: Full Trader Intelligence and Quantitative Analysis Engine


# ============================================================
# CELL 4: TRADER INTELLIGENCE & QUANTITATIVE ANALYSIS
# ============================================================

# ----------------------------
# A. TRADER ACTIVITY ANALYSIS
# ----------------------------

total_buy = len(buy_df)
total_sell = len(sell_df)
total_trades = total_buy + total_sell

buy_value = buy_df["value"].sum()
sell_value = sell_df["value"].sum()

total_value = buy_value + sell_value

buy_ratio = (
    total_buy / total_trades * 100
    if total_trades else 0
)

sell_ratio = (
    total_sell / total_trades * 100
    if total_trades else 0
)

buy_value_ratio = (
    buy_value / total_value * 100
    if total_value > 0 else 0
)

sell_value_ratio = (
    sell_value / total_value * 100
    if total_value > 0 else 0
)

net_transaction_value = buy_value - sell_value

# ----------------------------
# B. TRANSACTION STATISTICS
# ----------------------------

valid_values = trades["value"].dropna()

average_trade_value = (
    valid_values.mean() if len(valid_values) else 0
)

median_trade_value = (
    valid_values.median() if len(valid_values) else 0
)

largest_trade = (
    valid_values.max() if len(valid_values) else 0
)

trade_days = (
    trades["date"].dropna().dt.date.nunique()
)

average_daily_trades = (
    total_trades / trade_days if trade_days else 0
)

# ----------------------------
# C. MARKET ANALYSIS
# ----------------------------

if not market_df.empty:

    market_df["daily_return"] = (
        market_df["close"].pct_change() * 100
    )

    market_df["SMA_20"] = (
        market_df["close"].rolling(20).mean()
    )

    market_df["SMA_50"] = (
        market_df["close"].rolling(50).mean()
    )

    market_df["volatility"] = (
        market_df["daily_return"].rolling(20).std()
        * np.sqrt(252)
    )

    market_df["volume_sma_20"] = (
        market_df["volume"].rolling(20).mean()
    )

    first_price = market_df["close"].iloc[0]
    last_price = market_df["close"].iloc[-1]

    market_return = (
        (last_price / first_price - 1) * 100
        if first_price else 0
    )

    market_volatility = (
        market_df["daily_return"].std() * np.sqrt(252)
        if market_df["daily_return"].count() > 1
        else 0
    )

    highest_price = market_df["high"].max()
    lowest_price = market_df["low"].min()

    max_drawdown = (
        market_df["close"] /
        market_df["close"].cummax() - 1
    ).min() * 100

    if len(market_df) >= 50:
        trend = (
            "BULLISH"
            if last_price > market_df["SMA_50"].iloc[-1]
            else "BEARISH"
        )
    else:
        trend = "INSUFFICIENT DATA"

else:
    market_return = 0
    market_volatility = 0
    highest_price = 0
    lowest_price = 0
    max_drawdown = 0
    trend = "NO MARKET DATA"

# ----------------------------
# D. TRADER INTELLIGENCE SCORE
# ----------------------------

# Score measures activity dominance, not trading skill.
# It is NOT a profitability or predictive score.

activity_score = (
    50 + abs(buy_value_ratio - sell_value_ratio) / 2
    if total_value > 0 else 0
)

activity_score = min(activity_score, 100)

if total_value > 0:
    if buy_value_ratio > 55:
        behavior = "BUY DOMINANT"
    elif sell_value_ratio > 55:
        behavior = "SELL DOMINANT"
    else:
        behavior = "BALANCED ACTIVITY"
else:
    behavior = "INSUFFICIENT TRANSACTION VALUE DATA"

# ----------------------------
# E. ANALYTICAL INTERPRETATION
# ----------------------------

if total_trades == 0:
    interpretation = "No transaction records available."
elif buy_value > sell_value:
    interpretation = (
        "BUY transaction value exceeds SELL transaction value."
    )
elif sell_value > buy_value:
    interpretation = (
        "SELL transaction value exceeds BUY transaction value."
    )
else:
    interpretation = "BUY and SELL transaction values are balanced."

# ----------------------------
# F. REPORT GENERATION
# ----------------------------

report = {
    "Trader": TRADER,
    "Analysis Period": f"{START_DATE} to {END_DATE}",
    "Total Trades": total_trades,
    "BUY Transactions": total_buy,
    "SELL Transactions": total_sell,
    "BUY Value": buy_value,
    "SELL Value": sell_value,
    "Net Transaction Value": net_transaction_value,
    "BUY Value Ratio (%)": buy_value_ratio,
    "SELL Value Ratio (%)": sell_value_ratio,
    "Average Trade Value": average_trade_value,
    "Median Trade Value": median_trade_value,
    "Largest Trade Value": largest_trade,
    "Average Daily Trades": average_daily_trades,
    "Trader Activity Score": activity_score,
    "Trader Behavior": behavior,
    "Market Symbol": SYMBOL,
    "Market Return (%)": market_return,
    "Market Volatility (%)": market_volatility,
    "Market Trend": trend,
    "Maximum Drawdown (%)": max_drawdown,
    "Market High": highest_price,
    "Market Low": lowest_price,
    "Interpretation": interpretation
}

report_df = pd.DataFrame(
    list(report.items()),
    columns=["METRIC", "RESULT"]
)

print("=" * 70)
print("MARKETFLOW TRADER INTELLIGENCE REPORT")
print("=" * 70)

for key, value in report.items():
    if isinstance(value, (int, float, np.number)):
        print(f"{key:32}: {value:,.4f}")
    else:
        print(f"{key:32}: {value}")

print("=" * 70)

report_df.to_csv(
    f"{OUTPUT_DIR}/trader_intelligence_report.csv",
    index=False
)

2.5. Dashboard Visualization and Final Report Generation

The fifth computational cell generates the final analytical dashboard and reporting outputs.

The dashboard uses a two-by-two subplot configuration containing four visualization panels.

1. Trader Transaction Distribution

The first panel compares the number of BUY and SELL transactions.

This visualization provides a direct overview of transaction frequency and identifies which transaction category has the greater number of records.

2. Transaction Value Comparison

The second panel compares the total BUY and SELL transaction values.

Unlike transaction frequency, this visualization focuses on the monetary magnitude of recorded trading activities.

3. Historical Bitcoin Market Price

The third panel displays the historical BTCUSDT closing price together with SMA 20 and SMA 50.

This visualization provides a descriptive overview of historical price movements and moving average relationships.

4. Trader Activity Intelligence Score

The fourth panel presents the calculated Trader Activity Score on a scale of 0–100.

The complete dashboard is saved as trader_dashboard.png with a resolution of 300 DPI.

The system also generates final_trader_report.txt, which consolidates the trader profile, transaction statistics, market measurements, interpretation, and analytical limitations.

Finally, the program lists all generated output files to confirm the completion of the analytical workflow.

Code — Cell 5: Full Dashboard, Final Report, and Export


# ============================================================
# CELL 5: VISUALIZATION & FINAL REPORT
# ============================================================

fig, axes = plt.subplots(2, 2, figsize=(16, 10))

# 1. BUY vs SELL TRANSACTIONS
axes[0, 0].bar(
    ["BUY", "SELL"],
    [total_buy, total_sell]
)
axes[0, 0].set_title("Trader Transaction Distribution")
axes[0, 0].set_ylabel("Number of Transactions")

# 2. BUY vs SELL VALUE
axes[0, 1].bar(
    ["BUY", "SELL"],
    [buy_value, sell_value]
)
axes[0, 1].set_title("Transaction Value Comparison")
axes[0, 1].set_ylabel("Transaction Value")

# 3. HISTORICAL MARKET PRICE
if not market_df.empty:
    axes[1, 0].plot(
        market_df["date"],
        market_df["close"],
        label="BTC Close"
    )

    if market_df["SMA_20"].notna().any():
        axes[1, 0].plot(
            market_df["date"],
            market_df["SMA_20"],
            label="SMA 20"
        )

    if market_df["SMA_50"].notna().any():
        axes[1, 0].plot(
            market_df["date"],
            market_df["SMA_50"],
            label="SMA 50"
        )

    axes[1, 0].legend()

axes[1, 0].set_title(f"Historical Market: {SYMBOL}")
axes[1, 0].tick_params(axis="x", rotation=25)

# 4. TRADER ACTIVITY SCORE
axes[1, 1].bar(
    ["Activity Score"],
    [activity_score]
)
axes[1, 1].set_ylim(0, 100)
axes[1, 1].set_title("Trader Activity Intelligence Score")

plt.suptitle(
    "MARKETFLOW TRADER INTELLIGENCE DASHBOARD",
    fontsize=16,
    fontweight="bold"
)

plt.tight_layout()

plt.savefig(
    f"{OUTPUT_DIR}/trader_dashboard.png",
    dpi=300,
    bbox_inches="tight"
)

plt.show()

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

final_report = f"""
============================================================
MARKETFLOW TRADER INTELLIGENCE REPORT
============================================================

TRADER PROFILE
Trader                  : {TRADER}
Analysis Period         : {START_DATE} to {END_DATE}

TRANSACTION ANALYSIS
Total Transactions      : {total_trades}
BUY Transactions        : {total_buy}
SELL Transactions       : {total_sell}

BUY Transaction Value   : {buy_value:,.2f}
SELL Transaction Value  : {sell_value:,.2f}
Net Transaction Value   : {net_transaction_value:,.2f}

BUY Value Ratio         : {buy_value_ratio:.2f}%
SELL Value Ratio        : {sell_value_ratio:.2f}%

Average Trade Value     : {average_trade_value:,.2f}
Median Trade Value      : {median_trade_value:,.2f}
Largest Trade Value     : {largest_trade:,.2f}

TRADER INTELLIGENCE
Activity Score          : {activity_score:.2f}/100
Behavior Classification : {behavior}

MARKET ANALYSIS
Symbol                  : {SYMBOL}
Market Return           : {market_return:.2f}%
Annualized Volatility   : {market_volatility:.2f}%
Market Trend            : {trend}
Maximum Drawdown        : {max_drawdown:.2f}%

INTERPRETATION
{interpretation}

ANALYTICAL LIMITATIONS
- Activity score measures transaction value imbalance,
  not trader performance or investment skill.
- BUY and SELL data may represent different transactions.
- Missing transaction values cannot be treated as zero.
- BTCUSDT market data is contextual, not proof of a
  relationship with Warren Buffett's trading decisions.
- Historical prices do not establish future performance.
- API pagination and response completeness must be verified.

============================================================
PROJECT COMPLETED
============================================================
"""

print(final_report)

with open(
    f"{OUTPUT_DIR}/final_trader_report.txt",
    "w",
    encoding="utf-8"
) as f:
    f.write(final_report)

print("\nOUTPUT FILES")
print("-" * 50)

for filename in os.listdir(OUTPUT_DIR):
    print(f"✓ {filename}")

print("\nMARKETFLOW ANALYSIS FINISHED SUCCESSFULLY")

3. Results and Discussion

3.1. API Data Collection Results

The API data collection module retrieves three datasets associated with the MarketFlow Trader Intelligence Analyzer.

The first dataset contains Warren Buffett's BUY transaction records, while the second contains SELL transaction records.

Both datasets are retrieved using the same investor identifier and analysis period, allowing the system to compare the recorded trading activities.

The third dataset contains historical BTCUSDT market information, which is used as contextual financial data for the quantitative market analysis.

The system preserves the original API responses in three JSON files:

  • buy_activity.json

  • sell_activity.json

  • historical_market.json

Preserving the original responses provides an opportunity to examine the retrieved records and verify the data structure independently of the normalized datasets.

3.2. Trader Transaction Distribution

The transaction distribution analysis evaluates the frequency of BUY and SELL activities.

The system calculates the total number of BUY transactions and SELL transactions separately before combining them into the overall transaction count.

This comparison provides an initial overview of the recorded trader activity.

A higher number of BUY transactions indicates greater buying frequency, while a higher number of SELL transactions indicates greater selling frequency.

However, transaction frequency does not necessarily reflect the monetary magnitude of trading activities. Therefore, the transaction value analysis provides an additional measurement.

3.3. BUY and SELL Transaction Value Analysis

The transaction value analysis compares the total monetary value of recorded BUY and SELL activities.

The framework calculates:

  • Total BUY transaction value.

  • Total SELL transaction value.

  • Net transaction value.

  • BUY transaction value ratio.

  • SELL transaction value ratio.

The net transaction value represents the difference between total BUY and SELL transaction values.

A positive value indicates that BUY transaction value exceeds SELL transaction value, whereas a negative value indicates the opposite.

This comparison provides a descriptive measurement of transaction value distribution within the selected reporting period.

Nevertheless, the difference between BUY and SELL values should not automatically be interpreted as portfolio inflow or outflow. The underlying transaction records may represent different reporting mechanisms or financial activities.

3.4. Transaction Value Distribution and Statistical Characteristics

The system calculates the average, median, and largest transaction values.

These measurements provide additional information about the distribution of recorded transactions.

The average transaction value represents the arithmetic mean of available transaction values, while the median represents the middle observation after sorting the values.

The largest transaction value identifies the highest individual transaction value recorded in the normalized dataset.

These measurements can help identify whether the transaction dataset contains a relatively balanced distribution or is influenced by a small number of large transactions.

The framework also calculates average daily trading activity by dividing the total transaction count by the number of distinct transaction dates.

3.5. Bitcoin Historical Market Analysis

The market analysis module evaluates historical BTCUSDT prices using daily OHLCV information.

The system calculates daily percentage returns, SMA 20, SMA 50, annualized volatility, highest price, lowest price, and maximum drawdown.

The moving averages provide reference measurements for evaluating historical price direction.

SMA 20 represents the average closing price over the latest 20 observations, while SMA 50 represents the average over the latest 50 observations.

The framework classifies market trend according to the relationship between the latest closing price and SMA 50.

If the latest closing price is above SMA 50, the market is classified as BULLISH. Otherwise, it is classified as BEARISH.

When fewer than 50 observations are available, the system returns INSUFFICIENT DATA.

The annualized volatility calculation provides an estimate of price fluctuation based on historical daily returns.

Maximum drawdown measures the largest percentage decline from a previous running price peak.

These indicators provide a descriptive overview of historical market behavior but do not independently predict future price movements.

3.6. Trader Activity Intelligence Score

The Trader Activity Score is developed to summarize the imbalance between BUY and SELL transaction values.

The score begins at 50 and increases according to the absolute difference between the BUY and SELL value ratios.

A score closer to 50 indicates a relatively balanced transaction value distribution, while a higher score indicates a greater imbalance between the two categories.

The behavior classification identifies whether the recorded activity is BUY DOMINANT, SELL DOMINANT, or BALANCED ACTIVITY.

This mechanism provides a simplified quantitative description of transaction behavior.

It is important to emphasize that the score does not measure investment performance, trading accuracy, profitability, or predictive capability.

3.7. Financial Intelligence Dashboard

The visualization module integrates the main analytical results into a four-panel dashboard.

MarketFlow Trader Intelligence Dashboard

Transaction Distribution

BUY versus SELL transaction frequency.

Transaction Value

Comparison of BUY and SELL values.

Bitcoin Historical Market

BTCUSDT closing price, SMA 20, and SMA 50.

Trader Activity Score

Transaction value imbalance on a 0–100 scale.

Dashboard structure based on the original Python implementation. Actual chart values are generated during API execution.

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

This visualization provides a consolidated overview of trader activity and contextual market conditions.

3.8. Exported Analytical Outputs

The framework generates five principal output files.

Filename

Description

buy_activity.json

Original BUY transaction API response.

sell_activity.json

Original SELL transaction API response.

historical_market.json

Original BTCUSDT historical market response.

trader_transactions.csv

Combined and normalized BUY/SELL transactions.

historical_market.csv

Normalized historical OHLCV dataset.

trader_intelligence_report.csv

Structured analytical metrics.

trader_dashboard.png

Four-panel financial dashboard.

final_trader_report.txt

Consolidated financial intelligence report.

These outputs provide a reproducible record of the data collection and analytical workflow.

The JSON files preserve original API information, while the CSV files provide structured datasets suitable for additional statistical analysis.

3.9. Analytical Limitations and Future Improvements

Several limitations should be considered when interpreting the analytical results.

First, API data completeness must be verified. The source code requests a maximum of 100 records for each transaction type and does not implement automatic pagination. Therefore, the retrieved transactions may not represent the complete reporting period.

Second, BUY and SELL transactions may represent different financial activities. Their value differences should not automatically be interpreted as portfolio cash inflows or outflows.

Third, missing transaction values require careful interpretation. The system estimates missing values using price multiplied by quantity when both fields are available. Records without sufficient information remain unavailable rather than being assigned a confirmed transaction value.

Fourth, the Trader Activity Score is rule-based. The score measures the imbalance between BUY and SELL transaction values and is not a measure of investment performance or trading skill.

Fifth, BTCUSDT market information is contextual. Bitcoin price movements do not establish a direct relationship with Warren Buffett's reported transaction decisions.

Sixth, historical market retrieval parameters require verification. The source specifies range=100, timeframe=D, and to=2025-12-31. The actual coverage and meaning of the returned observations depend on the API implementation.

Seventh, the annualization factor uses 252 trading days. This is a conventional market calculation, although cryptocurrency markets operate continuously throughout the week.

Future improvements could include:

  • Automatic API pagination.

  • Transaction identifier deduplication.

  • Currency and transaction unit normalization.

  • Historical transaction trend visualization.

  • Additional volatility measurements.

  • RSI and MACD integration.

  • Bitcoin volume analysis.

  • Rolling maximum drawdown analysis.

  • Historical market event comparison.

  • Backtesting and predictive model evaluation.

  • Automated trader activity alerts.

  • Statistical validation of trader behavior classifications.

These developments could expand the framework into a more comprehensive financial intelligence platform.

4. Conclusion

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

The system integrates Warren Buffett's BUY and SELL transaction records for April 1 to July 1, 2025, with historical Bitcoin market information obtained through the BINANCE:BTCUSDT trading pair.

The analytical workflow incorporates API authentication, financial data extraction, JSON normalization, transaction value calculations, trader behavior classification, historical market analysis, and dashboard visualization.

The transaction analysis module calculates the number of BUY and SELL transactions, total transaction values, net transaction value, average trade value, median trade value, and largest transaction value.

The market analysis module evaluates Bitcoin market return, annualized volatility, SMA 20, SMA 50, maximum drawdown, and historical trend classification.

The framework also implements a Trader Activity Score to describe the relative imbalance between BUY and SELL transaction values.

The final dashboard combines transaction distribution, transaction value comparison, Bitcoin historical price movements, and trader activity intelligence into a single visualization.

Additionally, the system generates normalized CSV datasets, original JSON responses, a structured analytical report, and a high-resolution dashboard image.

Overall, the MarketFlow Trader Intelligence Analyzer demonstrates how Python and financial APIs can be integrated to automate trader activity analysis and contextual cryptocurrency market monitoring.

However, the system should be considered a descriptive financial analytics framework rather than a predictive trading platform. The completeness of API records, interpretation of transaction values, and separation between trader activity and Bitcoin market behavior must be considered when evaluating its results.

Future integration of complete transaction histories, additional market indicators, and statistical validation could improve the analytical capabilities of the framework.