Is it possible to align asset performance by trading session in python?

Viewed 57

I have time series data in one minute intervals for the last 7 business days and I want to calculate and plot the cumulative change by trading session like this:

BTC returns by trading session

The 23-Jun 'Asia' trading session overlaps two days (i.e. 23:00 on 22-Jun > 07:00 on 23-Jun) and I am unable to align the cumulative change calculation to take into account the 23:00 > 23:59 portion of the trading session which falls in the prior day.

My code:

cl1 = con.bdib('CO1 Comdty', start_datetime=start, 
         end_datetime=end, event_type='TRADE', interval=interval)

cl1['Timestamp'] = pd.to_datetime(cl1.index)
cl1['Time'] = cl1['Timestamp'].dt.time

def bin_f(x):
    if x.time() < datetime.time(7):
        return 'Asia'
    elif x.time() < datetime.time(14):
        return 'Europe'
    elif x.time() < datetime.time(22):
        return 'US'
    else:
        return 'Open'

cl1['Timezone'] = cl1['Timestamp'].apply(bin_f)

perf = cl1[['close', 'Timezone']]
perf['Count'] = 1

perf['Minute'] = perf.groupby([perf.index.date, 'Timezone'])['Count'].cumsum()
perf['Session'] = perf.index.date

perf = perf.pivot(index=['Session', 'Minute'], columns='Timezone', values='close')

perf = perf[['Asia', 'Europe', 'US']]

perf = perf.diff()

perf = perf.cumsum()

Result

Result

Raw Data

Raw Data

Desired output:

Two new columns: TimeZone and Session.

enter image description here

2 Answers

You can use xbbg to download intraday prices and use pd.concat([...], axis=1) directly to align the time series. Because the price data from xbbg carries timezone info and pandas deals with alignment automatically.

One solution is to split the problem into two parts:

Related