Skip to main content

Time of Day effects in FX

Time of day is critical for trading, it is even possible building trading strategies solely depending on time of day (I will keep this for another post)

I will be using the concept of quality and define a high quality market, from an intraday timing perspective, as a market when trading range and volume are high and spread is low. I assume this as a good time to trade as trading cost (spread) is low compared to trading opportunity (range and volume)

I start importing libraries,

In [23]:
import matplotlib.pyplot as plt
import pandas as pd
import bulk_tester as bt
import numpy as np
%matplotlib inline

I then load data for a couple of years for EURUSD, here I am using my own library for loading it from a csv file containing 15 minute bars and sampling at each 60 minutes.

In [24]:
pair = "EURUSD"
dftest = bt.get_data(pair, 'BT', resample_period='60T')

Then I add three columns; hour for doing the hourly grouping, spread and range

In [25]:
dftest['hour'] = dftest.index.hour
dftest['spread'] = (dftest.Ask - dftest.Bid)
dftest['range'] = (dftest.highAsk - dftest.lowBid)

I use 3 pivot tables for caclulating and grouping volume, spread and range by hour

In [26]:
#find hourly mean volume
table_volume = pd.pivot_table(dftest, values='volume', index=['hour'],
                     aggfunc=np.mean)
In [27]:
#find hourly mean spread
table_spread = pd.pivot_table(dftest, values='spread', index=['hour'],
                   aggfunc=np.mean)
In [28]:
#find hourly mean range
table_range = pd.pivot_table(dftest, values='range', index=['hour'],
                   aggfunc=np.mean)

I then create a new dataframe with normalized values for range, volume and spread so that they can fit into the same vertical range in a plot. Note that these are not the actual values!

In [29]:
summary=pd.DataFrame()
summary["Range"] = table_range/sum(table_range.values)*100
summary["Volume"] = table_volume/sum(table_volume.values)*100
summary["Spread"] = table_spread/sum(table_spread.values)*100
In [30]:
title = "Normalized Hourly Averages for Trading Range, Volume and Spread"
summary.plot(kind='line', figsize = (10,6), title=title)
Out[30]:
<matplotlib.axes._subplots.AxesSubplot at 0x10b399668>

Looking at trading GMT hours for FX sessions:

Australia = [20,21,22,23,0,1,2,3,4]

Tokyo = [0,1,2,3,4,5,6,7,8]

Europe = [8,9,10,11,12,13,14,15,16]

Americas = [13,14,15,16,17,18,19,20,21]

it can be seen that average volume and range peaks at around US open and spread is close to its minumum at 15:00

In line with my definition of market quality and considering we have normalized figures, I calculate market quality as:

(Volume + Range) / 2 - Spread

and calculate a market quality index (MQI) which peaks at 100 indicating that the opportunity-cost gap is at maximum.

In [31]:
summary["Quality"] = (((summary.Volume)+(summary.Range))/2-(summary.Spread))
mqi = summary.Quality*100/summary.Quality.max()
mqi.plot(kind="line", figsize = (10,6), title='Market Quality Index')
Out[31]:
<matplotlib.axes._subplots.AxesSubplot at 0x10c001e80>

MQI peaks at 12:00 - 15:00 which is the overlap of Europe and US sessions. MQI bottoms at 20:00 before US session closing. Tokyo and Australia sessions are low range, low volume and high spread sessions

Putting all this together and checking for a set of pairs... an obvious pattern. So what...For intraday traders holding positions for a couple of hours, executing trades when MQI is at its peaks is a good idea as it maximizes the opportunity to cost gap. And it is important to note that despite the similarities, MQI pattern is not the same for all pairs. As an example, looking at USDCAD, MQI peaks in a relatively narrow range and Europe session does not contribute much as it does to other pairs.

In [39]:
plt.figure(1, figsize=(16, 30))

#get a list of pair names to loop
df = pd.read_csv('/xxxx/PAIRLIST/PAIRLIST.csv', names=['PAIRNAME'])

a=0#counter for plotting

#loop a list of pairs and plot MQI
for pair in df.PAIRNAME: 
    
    s="";
    pair = s.join([pair[:3], pair[4:7]])
    
    dftest = bt.get_data(pair, 'BT', resample_period='60T')
    dftest['hour'] = dftest.index.hour
    dftest['spread'] = (dftest.Ask - dftest.Bid)
    dftest['range'] = (dftest.highAsk - dftest.lowBid)
    #find hourly mean volume
    table_volume = pd.pivot_table(dftest, values='volume', index=['hour'],
                         aggfunc=np.mean)
    #find hourly mean spread
    table_spread = pd.pivot_table(dftest, values='spread', index=['hour'],
                       aggfunc=np.mean)
    #find hourly mean range
    table_range = pd.pivot_table(dftest, values='range', index=['hour'],
                       aggfunc=np.mean)
    summary=pd.DataFrame()
    summary["Range"] = table_range/sum(table_range.values)*100
    summary["Volume"] = table_volume/sum(table_volume.values)*100
    summary["Spread"] = table_spread/sum(table_spread.values)*100
    summary["Quality"] = (((summary.Volume)+(summary.Range))/2-(summary.Spread))
    mqi = summary.Quality*100/summary.Quality.max()
    
    a+=1#counter for plotting
    
    plt.subplot(len(df),4,a)
    plt.plot(mqi)
    plt.yscale('linear')
    plt.title(pair)
    plt.grid(False)
    plt.tight_layout()
In [ ]:
 

Comments

  1. Language sorry i am little dummie and beginner

    ReplyDelete
    Replies
    1. I will be happy to answer if you have a question.

      Delete

Post a Comment

Popular posts from this blog

Two Strategies you can start trading tomorrow - Time of Day effects in FX continued

My latest post at http://quantsjourney.blogspot.co.uk/2017/09/time-of-day-effects-in-fx.html was on time of day effects in FX and I was claiming that you can actually make money with simple strategies depending on time of day.Below you will find 2 very simple strategies you can play with and make some money. Do not forget sending my 20%, I know I can trust you.I will now test these strategies with M15 bars with my quick and dirty backtester on 15 currency pairs including majors. Backtesting period is 01.01.2007 - 05.05.2017. The charts are profit in pips for the pairs where the strategy has positive P&L, these are not equity curves with equally spaced time, the horizontal axis is number of trades. But obviously equity curves will be similar with some gaps due to days with no trades.I almost did not optimize these strategies, there is room for improvement.Strategy one: Short at GMT 09:15 am, do this on Wednesday, Thursday and Friday, close after 5 hours. Check out EURUSD! In [5]: bt.…

Struggling Quant Episode 1: How I lost USD 500.000 while figuring out the link between questions, math, stats, coding and trading

Say that you are 30 years old and you have a good 25 years to work hard. Instead of going down the easy way of working for someone else during the day and killing time in the evenings and weekends, you have chosen the hard path of quantitative trading and started the heavy work. How many profitable trading ideas you can find in 25 years. Lets say you can figure out and test ideas in 10 days, 36 ideas a year and 900 ideas in 25 years right. Since this is my post, I am rounding 900 to 1000. Assuming a hit rate of 5%, 50 profitable ideas in 25 years, 2 per year and lets also say a profitable idea makes 20% per year. Depending on your initial capital, you will make X USD in 25 years. Lets say this X is USD 12.500.000 for me. USD 500.000 per year in average. This is my potential if I start doing things right now, right? So if I do things wrong for a year, I lose USD 500.000, this is what I did last year. I could not figure out how to operationalize all the scientific literature, huge qua…

Trading Decisions of Your Stone Age Grandpa can Make You Money in FOREX

Why Ferrari or Rolex does not price their products at 149.999 or 12.999 but most of the items you see in your supermarket is priced like 4.99? Because they never like to be positioned as a bargain. Did you know that we tend to chose the price with less syllables even if the two prices have the same written lenght? These are some of the pricing strategies used by marketers.This is a very interesting topic and you can even find yourself deep in neuroscience while reading about it. Check this site, it gives 42 pricing methods to influence your brain, crazy, https://www.nickkolenda.com/psychological-pricing-strategies/We also deal with prices when trading and I believe there are some sub-concious forces in play. Knowing some articles on things like the effect of round numbers in trading, I see some more potential here and I find this worth digging more not as standalone trading strategies but more as filters. At the end of the day, no one knows how the price feed effects the primitive you…