Back to Community
Custom Intraday Bars

Anyone ever have trouble getting custom intraday bars (e.g. 15-minute or 30-minute bars)? Q gives you access to one-minute bars via the data.history() function that you can easily turn into any bar length that you want. Thank you pandas! This tripped me up when I got started, so hopefully it can help some of you out there.

The attached algo is setup to get variable minute bars for Apple. It logs the one-minute bars and logs the custom bars so that you can easily check to see if the bars are calculated correctly. A couple of key points:

  • How to call a function every x minutes of the trading day (lines 24-27).
  • How to use the pandas DataFrame resample function (lines 51-60).

For those that want a detailed description for how this works, you can see my write up on this.


Clone Algorithm
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
Intraday bar test
By: Aaron Eller
[email protected]

import pandas as pd
def initialize(context):
    Quantopian function called once at the start of the algorithm.
    # Verify version of Pandas used'Current version of pandas is {}'.format(pd.__version__))
    # Asset to trade
    context.asset = sid(24) # AAPL
    # Number of minutes for the desired intraday bars
    context.intraday_bar = 5

    # Update bars every x minutes of trading day
    for i in range(1, 390): # Loop through max of 390 minutes in a trading day
        if i % context.intraday_bar == 0:
            schedule_function(get_intraday_bar, date_rules.every_day(), time_rules.market_open(minutes=i))

def handle_data(context, data):
    Quantopian function called every minute throughout the trading day.
    # Print one minute bars for the asset to check calculations
    ohlcv = data.current(context.asset, ['open', 'high', 'low', 'close', 'volume'])'{}: open={}, high={}, low={}, close={}, volume={}'.format(
            context.asset.symbol, ohlcv['open'], ohlcv['high'], ohlcv['low'], ohlcv['close'], ohlcv['volume']))
def get_intraday_bar(context, data):
    Function calculates historical ohlcv bars for a custom intraday period.
    # Get enough data to form the past 3 intraday bars
    bar_count = context.intraday_bar * 3
    df = data.history(context.asset, ['open', 'high', 'low', 'close', 'volume'], bar_count, '1m') # returns a pandas DataFrame

    # Resample dataframe for desired intraday bar
    resample_period = str(context.intraday_bar)+'T' # T = minute frequency
    #print(df.resample(resample_period)) # print statement to see resample default values
    result = df.resample(resample_period, base=1).first()
    result['open'] = df['open'].resample(resample_period, base=1).first()
    result['high'] = df['high'].resample(resample_period, base=1).max()
    result['low'] = df['low'].resample(resample_period, base=1).min()
    result['close'] = df['close'].resample(resample_period, base=1).last()
    result['volume'] = df['volume'].resample(resample_period, base=1).sum()    
    # Log the results'{} {} minute bar: open={}, high={}, low={}, close={}, volume={}'.format(
            context.asset.symbol, context.intraday_bar, result['open'][-1], result['high'][-1], 
            result['low'][-1], result['close'][-1], result['volume'][-1]))
There was a runtime error.
5 responses

Thanks for sharing this helper code!


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hi Aaron,

Thanks for putting this together for intraday bars. Really helpful.

I was wondering if there's an elegant way to get INTER-day bars as well?

4 hour interday bars. With ohlcv values calculted every 4 hours through the backtest timeframe with:
- 1st bar at 1:30 pm of day 1 (9:30am to 1:30pm = 4 hr)
- 2nd bar at 11:00 am of day 2 (1:30pm to 11:00am = 4 hr; 2.5 from last day and 1.5 from current day)
- 3rd bar at 2:00 pm of day 2 (11:00am to 3:00pm)
- 4th bar at 12:00 pm of day 3 (3:00pm to 12:00pm)
- .
- .


Quantopian doesn't supply equity price/volume data outside of trading hours. So the coverage of any intraday bars is restricted to 9:30am-4pm, on trading days only.

@Dan Dunn - how about for 24 hour futures contracts?

Forgive the elementary question, how can I get these bars once defined this way?
What historical depth do they have?
Can I perform backtests on periods like 3 ~ 5 years intraday on 5, 10, 15, 30, 60, 240 etc. minutes bars?
On which stocks can I do it?