Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Watch a Whole Year of World Markets in 12 Seconds: Build an Animated Heatmap in Python

11 min read

Animated heatmap Python tutorial banner: study desk with a laptop showing a coloured treemap, globe and film reel

This tutorial shows how to build an animated heatmap in Python that turns a whole year of world market returns into a 12 second video. Every tile is a country index, gold, silver or Bitcoin, sized by a fixed weight and coloured by its running YTD return, so you can watch the year unfold week by week. To do this, the script uses yfinance for prices, squarify for the treemap, Pillow to draw each frame and ffmpeg to encode the MP4.

Key takeaways

  • YTD for each week is the Friday close divided by the prior year’s last close, minus one, computed with a W-FRI resample in pandas.
  • Fixed tile weights give squarify one stable treemap layout, so only colours and numbers move in the video.
  • Frames are drawn with Pillow and piped as raw RGB bytes into ffmpeg, so no temporary image files are needed.
  • One flag, –vertical, renders a 1080×1920 version for Reels and Shorts.
  • Swap the ASSETS list for Nifty sectors or stocks, and use OpenAlgo history data if you prefer it to yfinance.
The finished video: 40 markets, gold, silver and Bitcoin, animated week by week through 2026.

What the animated heatmap Python script builds

In short, the output is a 1920×1080, 30 fps MP4 with a dark background, a title that reads “WORLD MARKETS · 2026 YTD” and a subtitle that ticks forward from “Jan 1” to the latest week. Below it, the animated heatmap in Python lays out a treemap of 40 assets. Every tile starts at 0% and then slides smoothly to its YTD return at the end of each week, so the colours shift from grey to green or red as the year plays out. Finally, the last frame holds for three seconds and is also saved as a PNG.

In this 2026 run, the final frame shows the US at +0.95%, Taiwan at +24.41%, Japan at +12.11%, India at −1.26%, gold at −19.02%, silver at −41.44% and Bitcoin at −30.59%. Note that these are simply the numbers that came out of the data on 22 Nov 2026. However, the point of the tutorial is the pipeline, so you can rerun it for any year or any basket of symbols.

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls

Prerequisites: Python, uv and ffmpeg

First, the animated heatmap Python script needs Python 3.10 or newer, five packages and the ffmpeg command line tool. The script carries a uv inline script header, so uv creates an isolated environment on the first run and you never touch pip:

# /// script
# requires-python = ">=3.10"
# dependencies = ["yfinance>=0.2.50", "pandas", "numpy", "pillow", "squarify"]
# ///

If you prefer pip, install the same packages yourself with pip install yfinance pandas numpy pillow squarify. In addition, ffmpeg must be on your PATH because Python hands every frame to it. For example, you can get builds from the official ffmpeg download page, or use a package manager:

Operating systemInstall uvInstall ffmpeg
Windowswinget install astral-sh.uvwinget install ffmpeg
macOSbrew install uvbrew install ffmpeg
Ubuntu / Debiancurl -LsSf https://astral.sh/uv/install.sh | shsudo apt install ffmpeg

After installing, open a fresh terminal and run ffmpeg -version. If that prints a version string, you are ready.

How the animated heatmap Python code is organised

Overall, the animated heatmap Python script is about 370 lines, and it splits into a data half and a rendering half. Here is the map before we walk through each part:

FunctionJob
ASSETSThe universe: label, ticker list with fallbacks, tile weight, flag code
fetch_weekly_ytd()Downloads daily closes with yfinance and builds a weekly YTD table
demo_weekly_ytd()Synthetic random walk data for offline testing
tile_color()Maps a return to a red, grey or green colour
render_frame()Draws one complete frame with Pillow
build_video()Computes the layout, interpolates between weeks and pipes frames to ffmpeg
main()Command line flags

Step 1: The asset universe and ticker fallbacks

First, each asset is a tuple of label, a list of yfinance tickers, a tile weight and a flag code. The first ticker in the list that returns usable data wins, so a country index can fall back to a US listed ETF when Yahoo has no history for the index. Also, codes that start with # are drawn as coloured coins instead of flags.

ASSETS = [
    ("US",           ["^GSPC"],                 30.0, "us"),
    ("GOLD",         ["GC=F", "GLD"],           13.0, "#Au"),
    ("CHINA",        ["000001.SS", "MCHI"],      8.0, "cn"),
    ("JAPAN",        ["^N225", "EWJ"],           6.5, "jp"),
    ("INDIA",        ["^NSEI", "INDA"],          4.5, "in"),
    ("HONG KONG",    ["^HSI", "EWH"],            4.0, "hk"),
    ("UK",           ["^FTSE", "EWU"],           3.5, "gb"),
    # ... 33 more rows ...
    ("VIETNAM",      ["VNM"],                    0.4, "vn"),
    ("AUSTRIA",      ["^ATX", "EWO"],            0.3, "at"),
]

The weights are roughly proportional to market size, but they are fixed on purpose. Because the treemap is computed once from these weights, no tile jumps around mid video. As a result, only the colour and the number change.

Step 2: Download prices with yfinance and compute weekly YTD returns

Next, the YTD definition is simple: for week W, YTD = Close on the last trading day of W divided by the close on the last trading day of the previous year, minus one. Also, weeks end on Friday. So the download starts on 15 December of the prior year to be sure it captures that base close. If yfinance is new to you, start with our yfinance guide for traders.

def fetch_weekly_ytd(year: int) -> pd.DataFrame:
    """Weekly running YTD returns (fraction), one column per asset label."""
    import yfinance as yf

    start = dt.date(year - 1, 12, 15)          # need last close of prior year
    end = min(dt.date(year, 12, 31), dt.date.today()) + dt.timedelta(days=1)

    all_tickers = sorted({t for _, ts, _, _ in ASSETS for t in ts})
    print(f"Downloading {len(all_tickers)} tickers {start} -> {end} ...")
    raw = yf.download(all_tickers, start=start, end=end, interval="1d",
                      auto_adjust=True, progress=False, group_by="column",
                      threads=True)
    close = raw["Close"] if isinstance(raw.columns, pd.MultiIndex) else raw
    close.index = pd.to_datetime(close.index).tz_localize(None)

    year_start = pd.Timestamp(year, 1, 1)
    out = {}
    last_seen = None                           # latest date with real data
    for label, tickers, _, _ in ASSETS:
        for t in tickers:
            if t not in close:
                continue
            s = close[t].dropna()
            prev = s[s.index < year_start]
            cur = s[s.index >= year_start]
            if prev.empty or len(cur) < 3:
                continue
            base = prev.iloc[-1]
            weekly = cur.resample("W-FRI").last().ffill()
            out[label] = weekly / base - 1.0
            if last_seen is None or cur.index[-1] > last_seen:
                last_seen = cur.index[-1]
            print(f"  {label:<12} {t:<11} YTD {out[label].iloc[-1]*100:+7.2f}%")
            break
        else:
            print(f"  {label:<12} -- no data, skipped")

Next, notice how holidays are handled. dropna() removes days when a market was shut, resample("W-FRI").last() picks the last real close inside each week, and ffill() carries a value forward through a week with no trading at all. As a result, Diwali or Lunar New Year closures never leave gaps in the animation.

In addition, two more details at the end of the function matter. First, the final, partial week is relabelled with the last date that actually has data, which is why the 2026 video says “Nov 22, 2026” on a Sunday: Bitcoin trades at weekends. Second, a zero row is inserted on 31 December so the video starts with every tile at 0%.

    df = pd.DataFrame(out).sort_index().ffill().fillna(0.0)
    # W-FRI bins are labelled with their Friday. For the final, partial week
    # that Friday can lie in the future (or in the next year for a past year),
    # so relabel the last row with the last date that actually has data.
    if len(df) and last_seen is not None and df.index[-1] > last_seen:
        idx = df.index.tolist()
        idx[-1] = last_seen
        df.index = pd.DatetimeIndex(idx)
    # Week 0 = Jan 1 baseline, everything at 0%
    df.loc[pd.Timestamp(year, 1, 1) - pd.Timedelta(days=1)] = 0.0
    return df.sort_index()

Step 3: A stable squarify treemap layout for the animated heatmap in Python

Next, squarify turns a list of sizes into rectangles with aspect ratios close to square, which keeps small tiles readable. The script sorts assets by weight, normalises the weights to the drawing area under the header and computes the rectangles once:

    lookup = {a[0]: a for a in ASSETS}
    labels = [c for c in df.columns]
    weights = [lookup[l][2] for l in labels]
    codes = [lookup[l][3] for l in labels]
    order = np.argsort(weights)[::-1]
    labels = [labels[i] for i in order]
    weights = [weights[i] for i in order]
    codes = [codes[i] for i in order]
    vals = df[labels].to_numpy()
    dates = df.index

    header_h = int(H * (0.07 if H > W else 0.09))
    sizes = squarify.normalize_sizes(weights, W, H - header_h)
    rects = squarify.squarify(sizes, 0, 0, W, H - header_h)

In the animated heatmap Python code, each rectangle is a dict with x, y, dx and dy. Since the weights never change, the same list of rectangles is reused for every one of the roughly 370 frames. For a static, interactive alternative, see our Plotly treemap of Nifty 50 market cap.

Step 4: Colour mapping with the cap

Then the animated heatmap in Python needs a colour for every tile, and it uses a diverging scale: neutral grey at 0%, deep green for gains and deep red for losses. The cap argument sets the return at which the colour is fully saturated, 15% by default. Also, the power of 0.6 lifts small moves so a +2% tile is visibly green rather than almost grey.

def tile_color(r: float, cap: float) -> tuple[int, int, int]:
    """Diverging color: deep red <- grey -> deep green, saturating at +-cap."""
    t = float(np.clip(abs(r) / cap, 0, 1)) ** 0.6
    neutral = np.array([58, 62, 70])
    pos = np.array([22, 168, 72])
    neg = np.array([222, 38, 38])
    c = neutral + ((pos if r >= 0 else neg) - neutral) * t
    return tuple(int(x) for x in c)

For example, with the default cap a +7.5% return gives t = 0.5 ** 0.6, about 0.66, so the tile is two thirds of the way from grey to full green. Anything beyond ±15% looks identical, therefore raise the cap to 0.30 in a year with very large moves.

Step 5: Draw tiles, flags and auto-fitted text with Pillow

Meanwhile, flags come from flagcdn.com and are cached in a flags/ folder next to the script, so only the first real run needs the network for them. circle_flag() crops each flag to a square and applies a 4x supersampled circular mask for smooth edges:

def circle_flag(img: Image.Image, d: int) -> Image.Image:
    w, h = img.size
    s = min(w, h)
    sq = img.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2))
    sq = sq.resize((d, d), Image.LANCZOS)
    mask = Image.new("L", (d * 4, d * 4), 0)
    ImageDraw.Draw(mask).ellipse((0, 0, d * 4 - 1, d * 4 - 1), fill=255)
    out = Image.new("RGBA", (d, d))
    out.paste(sq, (0, 0), mask.resize((d, d), Image.LANCZOS))
    return out

Similarly, text size is driven by the tile. The percentage gets about 20% of the tile size, then fit_text() shrinks it one point at a time until it fits within 86% of the tile width. Also, the label is sized relative to the percentage, and the flag is skipped when a tile is too short to hold all three items.

def fit_text(draw, text, max_w, size):
    while size > 6 and draw.textlength(text, font=font(size)) > max_w:
        size -= 1
    return size
        tw, th = rect["dx"] - 2 * gap, rect["dy"] - 2 * gap
        if tw < 18 or th < 18:
            continue
        cx = int(x0 + rect["dx"] / 2)
        base = min(tw, th * 1.3)
        pct = f"{r * 100:+.2f}%".replace("-", "−")
        pct_size = fit_text(d, pct, tw * 0.86, int(base * 0.20))
        lab_size = fit_text(d, label, tw * 0.86, int(pct_size * 0.62))
        icon_d = int(min(tw * 0.42, th * 0.34, pct_size * 2.4))

        show_icon = th > pct_size * 3.2 and icon_d >= 10
        block_h = (icon_d + pct_size * 0.3 if show_icon else 0) + lab_size * 1.15 + pct_size
        top = y0 + rect["dy"] / 2 - block_h / 2
        if show_icon:
            draw_icon(img, d, code, cx, int(top + icon_d / 2), icon_d, flags)
            top += icon_d + pct_size * 0.3
        if th > lab_size + pct_size:
            d.text((cx, top), label, font=font(lab_size), fill=(255, 255, 255), anchor="mt")
            top += lab_size * 1.15
        d.text((cx, top), pct, font=font(pct_size), fill=(255, 255, 255), anchor="mt")

Finally, one small touch: the hyphen in negative numbers is swapped for a true minus sign (U+2212), which lines up better with the plus sign in bold fonts.

Step 6: Smoothstep easing for a smooth animated heatmap in Python

Weekly data alone would make the animated heatmap jerky, so the Python loop inserts fpw frames between each pair of weeks. With the defaults (30 fps, 0.2 seconds per week) that is 6 frames per week. Then each in-between frame blends the two weeks with smoothstep easing, which starts and ends slowly:

    frame_i = 0
    for k in range(len(dates) - 1 + 1):
        steps = fpw if k < len(dates) - 1 else 1
        for s in range(steps):
            a = s / fpw
            a = a * a * (3 - 2 * a)                     # smoothstep easing
            nxt = vals[min(k + 1, len(dates) - 1)]
            rets = vals[k] * (1 - a) + nxt * a
            day = dates[k] + (dates[min(k + 1, len(dates) - 1)] - dates[k]) * a
            date_label = ("Jan 1" if k == 0 and s == 0
                          else f"Week {min(k + (1 if a > .5 else 0), len(dates)-1)} · {day:%b %d, %Y}")
            img = render_frame(W, H, rects, labels, codes, rets, date_label,
                               year, flags, cap, header_h)
            ff.stdin.write(img.tobytes())
            frame_i += 1
    for _ in range(n_hold):                              # hold on final frame
        ff.stdin.write(img.tobytes())

The date in the subtitle is interpolated the same way, and the week number flips once the blend passes the halfway mark. After that, the last frame of the animated heatmap in Python is written fps * hold more times to create the three second hold.

Step 7: Pipe raw frames to ffmpeg from Python

Instead of saving hundreds of PNG files, the script opens ffmpeg as a subprocess and writes raw RGB bytes straight into its standard input. In turn, ffmpeg encodes them to H.264 with yuv420p pixels, which plays everywhere, including WhatsApp and Instagram. Also, the +faststart flag moves the index to the front so the video starts playing in a browser before it is fully downloaded.

    ff = subprocess.Popen(
        ["ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
         "-s", f"{W}x{H}", "-r", str(fps), "-i", "-", "-c:v", "libx264",
         "-pix_fmt", "yuv420p", "-crf", "18", "-preset", "medium",
         "-movflags", "+faststart", str(out)],
        stdin=subprocess.PIPE)

Because of this, the animated heatmap Python script needs no temporary folder and finishes quickly. On our test box, the 1920×1080 demo render of 373 frames took about 13 seconds including the one-time package install by uv.

Step 8: Vertical mode for Reels and Shorts

Lastly, the --vertical flag flips the canvas to 1080×1920. As a result, the header shrinks from 9% to 7% of the height, and squarify lays the same weights out in a tall rectangle. Nothing else changes, so one animated heatmap Python script serves YouTube, Reels and Shorts.

    header_h = int(H * (0.07 if H > W else 0.09))
# ...
    W, H = (1080, 1920) if a.vertical else (1920, 1080)
    out = Path(a.out or f"ytd_heatmap_{a.year}{'_demo' if a.demo else ''}.mp4")

How to run the animated heatmap Python script

First, save the script as ytd_heatmap.py and use these commands. However, the first run with uv takes a few seconds longer while it builds the environment.

uv run ytd_heatmap.py                     # current year, real data
uv run ytd_heatmap.py --year 2025         # a full past year
uv run ytd_heatmap.py --demo              # synthetic data (no internet)
uv run ytd_heatmap.py --vertical          # 1080x1920 for Reels/Shorts
uv run ytd_heatmap.py --csv ytd.csv       # also dump the weekly YTD table
uv run ytd_heatmap.py --cap 0.30 --sec-per-week 0.3 --hold 5 --out slow.mp4

We also tested the commands on a Linux box before publishing. The --demo run produced a 1920×1080, 30 fps, 12.4 second MP4 of 373 frames. Meanwhile, a real run with --vertical --csv downloaded 75 tickers, found data for all 40 assets and wrote a 1080×1920 video plus the weekly CSV. Yahoo returned nothing for the Chile index ^IPSA, so the script quietly used the ECH ETF instead, which is exactly what the fallback list is for. No code changes were needed.

In addition, the console prints one line per asset showing which ticker it used, which is the quickest way to audit the data:

  US           ^GSPC       YTD   +0.95%
  GOLD         GC=F        YTD  -19.02%
  INDIA        ^NSEI       YTD   -1.26%
  TAIWAN       ^TWII       YTD  +24.41%
  CHILE        ECH         YTD  -15.82%
Rendering 379 frames (12.6s) -> ytd_vertical_2026.mp4
FlagDefaultWhat it changes
--yearcurrent yearWhich calendar year to animate
--demooffSynthetic data, no internet, no flags
--verticaloff1080×1920 instead of 1920×1080
--fps30Frames per second
--sec-per-week0.2Seconds spent moving between two weeks
--hold3.0Seconds to hold the final frame
--cap0.15Return at which colour is fully saturated
--outytd_heatmap_YEAR.mp4Output file name
--csvnoneAlso save the weekly YTD table (in %)

Customise the YTD heatmap for Indian sectors and Nifty stocks

Because everything is driven by the ASSETS list, switching to an Indian view is mostly a data change. For example, a sector heatmap can use Yahoo index tickers such as ^CNXIT, ^NSEBANK, ^CNXAUTO, ^CNXPHARMA and ^CNXFMCG, with weights set to each sector’s share of the Nifty 50. Likewise, a Nifty 50 stock version can use RELIANCE.NS, HDFCBANK.NS and so on, weighted by free float market cap.

Next, set the fourth field to a # code so the tile shows a coin instead of a flag, and add a matching colour pair to ICON_COLORS. Otherwise draw_icon() raises a KeyError. For stocks, however, it is cleaner to show no icon at all, which happens automatically when the code is not in the flags cache. You can also reuse the same yfinance and seaborn pattern from our Nifty monthly returns heatmap tutorial to cross-check the numbers.

Using OpenAlgo history data instead of yfinance

If you already run OpenAlgo, then its history API returns daily candles for NSE symbols from your own setup, which avoids Yahoo symbol gaps. The function below is our adaptation, not part of the original script: it returns a daily close series, and you would drop it into fetch_weekly_ytd() in place of the yfinance download. Otherwise, the rest of the pipeline stays the same.

import requests
import pandas as pd

def openalgo_close(symbol, exchange, start, end,
                   host="http://127.0.0.1:5000", apikey="YOUR_OPENALGO_API_KEY"):
    r = requests.post(f"{host}/api/v1/history", json={
        "apikey": apikey, "symbol": symbol, "exchange": exchange,
        "interval": "D", "start_date": start, "end_date": end}, timeout=60)
    data = r.json()["data"]
    df = pd.DataFrame(data)
    idx = pd.to_datetime(df["timestamp"], unit="s").dt.tz_localize("UTC").dt.tz_convert("Asia/Kolkata")
    return pd.Series(df["close"].values, index=idx.dt.tz_localize(None).dt.normalize())

s = openalgo_close("RELIANCE", "NSE", "2025-12-15", "2026-11-22")

Because the timestamps arrive as Unix seconds, convert them to IST before resampling. For a walkthrough of the OpenAlgo data calls, see our OpenAlgo historical charts tutorial.

Common mistakes and troubleshooting

  • FileNotFoundError for ffmpeg. Python cannot find the ffmpeg executable. So install it, then open a new terminal so the updated PATH is loaded. On Windows, winget only updates PATH for new sessions.
  • An asset shows “no data, skipped”. This means none of its tickers returned a prior year close plus at least three closes this year. Add a fallback ticker (usually a US listed country ETF) or remove the row. Also, a tile that is skipped disappears from the layout.
  • Index and ETF returns are not in the same currency. Index tickers give local currency returns, while ETF fallbacks such as ECH or VNM are priced in US dollars. So a tile that falls back to an ETF includes currency moves; keep that in mind before comparing two tiles.
  • Blank weeks or NaN values. The script already uses dropna, a Friday resample, ffill and fillna(0.0). If you edit the data step, keep those calls, otherwise Pillow receives NaN and the colour function breaks.
  • Tiny or ugly text on Windows. The font list includes C:/Windows/Fonts/arialbd.ttf. If none of the listed fonts load, Pillow falls back to load_default(size), which needs Pillow 10.1 or newer. Add your own TTF path at the top of FONT_BOLD if you want a different look.
  • Rate limits from Yahoo. Usually, 75 tickers in one call is usually fine. However, if yfinance returns empty frames, wait a few minutes and rerun; the flag images are already cached by then.
  • The video looks too fast. In that case, raise --sec-per-week to 0.3 or 0.4 and --hold to 5. For example, a full year at 0.4 seconds per week gives about a 22 second video.

Get the full source code of the animated heatmap in Python

The complete script, the flag cache, the 2026 weekly YTD CSV and the sample video are on GitHub at marketcalls/world-markets-ytd-heatmap. Clone it and render your first animated heatmap in Python with three commands:

git clone https://github.com/marketcalls/world-markets-ytd-heatmap.git
cd world-markets-ytd-heatmap
uv run ytd_heatmap.py --demo

Once the demo works, drop the --demo flag to pull live data, then add --vertical for a Reels or Shorts version. After that, swap the asset list for Nifty sectors or your own watchlist and you have a fresh year in review video every week.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More