<jupyter_start><jupyter_text>An example how to apply a strategy per trading session.<jupyter_code>import pandas as pd
import numpy as np
import vectorbt as vbt
from datetime import timedelta
# Generate sample price
price_idx = pd.date_range('2018-01-01 12:00:00', periods=48, freq='H')
np.random.seed(42)
price = pd.Series(np.random.uniform(size=price_idx.shape), index=price_idx)
print(price)
# Sessions must be equal - fill missing dates
# Fill on first date before 12:00 and on last date after 11:00
first_date = price.index[0].date()
last_date = price.index[-1].date()+timedelta(days=1)
filled_idx = pd.date_range(first_date, last_date, freq='H')
filled_price = price.reindex(filled_idx)
print(filled_price)
# Remove dates that are outside of trading sessions
session_price_idx = filled_price.between_time('9:00', '17:00', include_end=False).index
session_price = filled_price.loc[session_price_idx]
print(session_price)
# Select first and last ticks of each trading session and split price into ranges between those ticks
start_idxs = session_price.index[session_price.index.hour == 9]
end_idxs = session_price.index[session_price.index.hour == 16]
price_per_session = session_price.vbt(freq='1H').split_into_ranges(start_idxs=start_idxs, end_idxs=end_idxs)
print(price_per_session)
# Run your strategy (here using random signals)
entries, exits = pd.DataFrame.vbt.signals.generate_random_both(price_per_session.shape, n=2, seed=42)
portfolio = vbt.Portfolio.from_signals(price_per_session, entries, exits, freq='1H')
print(portfolio.total_return())<jupyter_output>range_start          range_end          
2018-01-01 09:00:00  2018-01-01 16:00:00   -0.786858
2018-01-02 09:00:00  2018-01-02 16:00:00    1.466807
2018-01-03 09:00:00  2018-01-03 16:00:00   -0.529509
Name: total_return, dtype: float64