DEV Community

Jesus Gonzalez
Jesus Gonzalez

Posted on

Create OHLC Candles with Python (Pandas + Plotly)

Many market datasets come as raw trade ticks (timestamp, price, size). To analyze trends we first convert ticks into OHLC candles. This tiny Python script builds 1‑minute candles with Pandas and plots them with Plotly.

How it works

  • Generate trade ticks at 1‑second resolution
  • Resample to a 1‑minute interval and compute open, high, low, close, and volume
  • Plot a candlestick chart

Open in Colab (public): paste the code below into https://colab.new and run.

import numpy as np, pandas as pd, plotly.graph_objects as go

FREQ, MINS = '1min', 10  # interval and number of candles
start = pd.Timestamp('2025-01-01 10:00:00', tz='UTC')
idx = pd.date_range(start, periods=MINS*60, freq='s', tz='UTC')

rng = np.random.default_rng(42)
price = 100 + rng.normal(0, 0.03, len(idx)).cumsum()
qty   = np.maximum(1, np.rint(rng.normal(2.0, 0.8, len(idx))))
df = pd.DataFrame({'price': price, 'qty': qty}, index=idx)

candles = pd.DataFrame({
    'open':  df['price'].resample(FREQ).first(),
    'high':  df['price'].resample(FREQ).max(),
    'low':   df['price'].resample(FREQ).min(),
    'close': df['price'].resample(FREQ).last(),
    'vol':   df['qty'].resample(FREQ).sum(),
}).dropna()

fig = go.Figure(go.Candlestick(
    x=candles.index, open=candles['open'], high=candles['high'],
    low=candles['low'], close=candles['close']))
fig.update_layout(template='plotly_dark', height=420,
                  title=f'{MINS}m Candles ({FREQ})')
fig.show()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)