Hi all,
I am re-implementing my code @ Quantopian on QC platform. Below is a simple code snippet, where I am calculating future spread and ratio for NGH19/NGJ19. Could anyone direct me on how to implement this using QC APIs? while I am comfortable with Quantopian libs/APIs, I am still trying to understand how to work with futures on QC.
front_contract = "NGH19"
back_contract = "NGJ19"
contracts = symbols([front_contract, back_contract])
prices = get_pricing(contracts,
start_date='2018-01-01',
end_date='2019-02-07',
fields='price')
prices.columns = map(lambda x: x.symbol, prices.columns)
prices = prices.dropna()
spread = prices[front_contract] - prices[back_contract]
ratio = prices[front_contract] / prices[back_contract]
Thanks in advance!
Douglas Stridsberg
Heya,
Here's a basic test to show you how to do what you want to do. It goes a bit further, too, by identifying the front-month contract (and assumes it's basically spot) and making further calculations. It's in C# but the general process is the same in Python. You can use the relevant docs to figure out the differences. Hope it helps!
CloudTrader
Hi Douglas,
Thank you!! Your C# code is not really what I was asking for :) Sorry if I was not clear on this.
My Quantopian Python code above calculates spread and ratio for NGH19/NGJ19 (in few lines of code). This is precisely about NG (natural gas) widow maker. This is always about March/April spread every year between NGH19 (front month) and NGJ19 (back month). I know how to get future chain, access unadjusted contracts and do basic things in QC. However, what I was looking for is similar and compact way like in Quantopian to directly access NGH19 and NGJ19 contracts.
The goal is to find out historical NGH19/NGJ19 extreme spreads and ratios to decide on whether NGH19/NGJ19 a candidate calendar spread trade or not.
I would also further need continous contracts for my analysis. However, this capability is not yet available in QC.
Halldor Andersen
Hi all.
To retrieve specific futures contracts, set in the method Initialize:
self.frontContract = "NG26H19" self.backContract = "NG27J19"
and in the method OnData():
contracts = filter(lambda x: x.Symbol.Value in [self.frontContract,self.backContract], chain.Value)
I've attached a backtest where I retrieve the price for the two future contracts, and I calculate the spread and the ratio between the contracts at the end of each day. Good luck!
CloudTrader
Hi Halldor,
Awesome! Many thanks for this reference implementation. Two questions please:
1) Since all contract months settle to the volume-weighted average price (VWAP) of outright trades between 15:59:00 and 16:00:00 London time, you are capturing NG26H19 and NG27J19 futures contract prices at 15:59. self.Time.hour and self.Time.minute is stored in historical data as London time and not UTC time?
2) I have always coded my analysis first in Quantopian Rsearch Notebooks (fast and reliable) and then implemented the trades in Algorithms.
How would you code this reference implementation in QC Research Jupyter Notebook?
# This code is not working in Research
# ng = qb.AddFuture("NG26H19")
# ng = qb.AddFuture("NG27J19")
# This simple call has been running endlessly and still no results
ng = qb.AddFuture("NG")
df = qb.GetFutureHistory(ng.Symbol, datetime(2018, 1, 1), datetime.now()).GetAllData()
df
CloudTrader
Hi Halldor,
UTC is the same as London time :) Sorry, forget my first question.
Halldor Andersen
Hi CloudTrader.
Glad I could help! You can retrieve the values by adding the following:
subset=df.index.get_level_values(1).isin(["NG26H19","NG27J19"]) df[subset]
I've attached a notebook for your reference.
CloudTrader
Hi Halldor,
Great, this filtering is working for me. Many thanks!
CloudTrader
Hi Halldor,
Second index level is missing now. Are there changes in futures index levels?
subset=df.index.get_level_values(1).isin(["NG26H19","NG27J19"]) df[subset] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-15-3b9c2e904b83> in <module> ----> 1 subset=df.index.get_level_values(1).isin(["NG26H19","NG27J19"]) 2 df[subset] /opt/miniconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in _get_level_values(self, level) 3169 """ 3170 -> 3171 self._validate_index_level(level) 3172 return self 3173 /opt/miniconda3/lib/python3.6/site-packages/pandas/core/indexes/base.py in _validate_index_level(self, level) 1953 raise IndexError("Too many levels:" 1954 " Index has only 1 level, not %d" % -> 1955 (level + 1)) 1956 elif level != self.name: 1957 raise KeyError('Level %s must be same as name (%s)' % IndexError: Too many levels: Index has only 1 level, not 2
Jack Simonson
Hi,
We just did an overhaul of our futures data and will have the Research Environment updated soon, which should fix this. If you continue to experience this error next week, please let us know and we'll do our best to find a solution.
CloudTrader
Thanks Jack. I will check this later then.
CloudTrader
Hi Jack,
I tested again today and unfortunately same problem as before:
IndexError: Too many levels: Index has only 1 level, not 2
CloudTrader
Hi Jack,
I am still having that issue. When can I expect that future data fix in Research to be done?
Thanks
Link Liang
Hi CloudTrader,
I apology for late response. We had an upgrade for all future data and they are ready to use in backtesting environment. Meanwhile, we are working hard to update our research environment for the new implementation of future data and it will be online soon. Thanks for your support.
CloudTrader
Ok, sounds good. I will use only meanwhile then the backtesting environment. Many thanks Link for update.
CloudTrader
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 QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect 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. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!