Chris Parmer — home

Candlestick + volume

AAPL daily OHLCV, ~1 year via Yahoo Finance API

Example from the compendium of canonical charts

Candlestick + volume — AAPL daily OHLCV, ~1 year via Yahoo Finance API

Python Code

"""Candlestick + volume — AAPL daily OHLCV, ~1 year via Yahoo Finance API."""


import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import requests, warnings, json

import time as _time
_jan1 = int(_time.mktime(_time.strptime(f"{_time.localtime().tm_year}-01-01", "%Y-%m-%d")))
URL = f"https://query1.finance.yahoo.com/v8/finance/chart/AAPL?period1={_jan1}&period2=9999999999&interval=1d"


def generate():
    print("fetching AAPL 1-year daily OHLCV from Yahoo Finance …")
    warnings.filterwarnings("ignore")
    requests.packages.urllib3.disable_warnings()

    headers = {"User-Agent": "Mozilla/5.0"}
    r = requests.get(URL, headers=headers, verify=False, timeout=30)
    r.raise_for_status()
    data = r.json()

    result = data["chart"]["result"][0]
    ts     = result["timestamp"]
    ohlcv  = result["indicators"]["quote"][0]

    dates  = pd.to_datetime(ts, unit="s").strftime("%Y-%m-%d").tolist()
    opens  = ohlcv["open"]
    highs  = ohlcv["high"]
    lows   = ohlcv["low"]
    closes = ohlcv["close"]
    vols   = ohlcv["volume"]

    # Drop any None rows
    df = pd.DataFrame({"date": dates, "open": opens, "high": highs,
                        "low": lows, "close": closes, "volume": vols})
    df = df.dropna()
    up_color   = [GREEN if c >= o else PINK for c, o in zip(df["close"], df["open"])]

    fig = make_subplots(
        rows=2, cols=1,
        shared_xaxes=True,
        row_heights=[0.75, 0.25],
        vertical_spacing=0.03,
    )

    fig.add_trace(go.Candlestick(
        x=df["date"],
        open=df["open"], high=df["high"],
        low=df["low"],   close=df["close"],
        increasing=dict(line=dict(color=GREEN), fillcolor=GREEN),
        decreasing=dict(line=dict(color=PINK),  fillcolor=PINK),
        name="AAPL",
        hovertext=[f"{d}<br>O:{o:.2f} H:{h:.2f} L:{l:.2f} C:{c:.2f}"
                   for d,o,h,l,c in zip(df["date"],df["open"],df["high"],df["low"],df["close"])],
        hoverinfo="text",
    ), row=1, col=1)

    fig.add_trace(go.Bar(
        x=df["date"], y=df["volume"],
        marker_color=up_color,
        marker_opacity=0.7,
        name="Volume",
        hovertemplate="%{x}<br>Vol=%{y:,.0f}<extra></extra>",
    ), row=2, col=1)

    fig.update_layout(
        title=dict(text="AAPL Daily Candlestick + Volume (1 Year)", x=0.5),
        xaxis=dict(rangeslider=dict(visible=False)),
        xaxis2=dict(title="", rangeslider=dict(visible=False)),
        yaxis=dict(title="Price (USD)"),
        yaxis2=dict(title="Volume"),
        legend=dict(orientation="h", y=1.05),
        margin=dict(t=60, b=50, l=70, r=40),
        height=520,
    )
    return fig


if __name__ == "__main__":
    generate()

Made with Plotly