Skip to content

Commit

Permalink
Address reviews
Browse files Browse the repository at this point in the history
- Adding python regression algorithm for
  `AddOptionContractFromUniverseRegressionAlgorithm`
  and `AddOptionContractExpiresRegressionAlgorithm`
- Rename QCAlgorithm new api method to `AddChainedOptionUniverse`
  • Loading branch information
Martin-Molinero committed Oct 5, 2020
1 parent 797c52a commit 62cc181
Show file tree
Hide file tree
Showing 9 changed files with 171 additions and 16 deletions.
17 changes: 8 additions & 9 deletions Algorithm.CSharp/AddOptionContractExpiresRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
using QuantConnect.Data;
using QuantConnect.Interfaces;
using System.Collections.Generic;
using QuantConnect.Securities.Option;

namespace QuantConnect.Algorithm.CSharp
{
Expand All @@ -29,7 +28,7 @@ namespace QuantConnect.Algorithm.CSharp
public class AddOptionContractExpiresRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private DateTime _expiration = new DateTime(2014, 06, 21);
private Option _option;
private Symbol _option;
private Symbol _twx;
private bool _traded;

Expand All @@ -54,16 +53,16 @@ public override void OnData(Slice data)
&& optionContract.ID.OptionStyle == OptionStyle.American);
if (option != null)
{
_option = AddOptionContract(option);
_option = AddOptionContract(option).Symbol;
}
}

if (!Portfolio.Invested && _option != null && Securities[_option.Symbol].Price != 0 && !_traded)
if (_option != null && Securities[_option].Price != 0 && !_traded)
{
_traded = true;
Buy(_option.Symbol, 1);
Buy(_option, 1);

foreach (var symbol in new [] { _option.Symbol, _option.Symbol.Underlying })
foreach (var symbol in new [] { _option, _option.Underlying })
{
var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList();

Expand All @@ -80,9 +79,9 @@ public override void OnData(Slice data)

if (Time.Date > _expiration)
{
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option.Symbol).Any())
if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any())
{
throw new Exception($"Unexpected configurations for {_option.Symbol} after it has been delisted");
throw new Exception($"Unexpected configurations for {_option} after it has been delisted");
}

if (Securities[_twx].Invested)
Expand Down Expand Up @@ -113,7 +112,7 @@ public override void OnData(Slice data)
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public override void Initialize()

public override void OnData(Slice data)
{
if (!Portfolio.Invested && _option != null && Securities[_option].Price != 0 && !_traded)
if (_option != null && Securities[_option].Price != 0 && !_traded)
{
_traded = true;
Buy(_option, 1);
Expand Down Expand Up @@ -164,7 +164,7 @@ public override void OnEndOfAlgorithm()
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp };
public Language[] Languages { get; } = { Language.CSharp, Language.Python };

/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public override void Initialize()
var selectionUniverse = AddUniverse(enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl },
enumerable => new[] { Time.Date <= new DateTime(2014, 6, 5) ? _twx : _aapl });

AddChainedEquityOptionUniverseSelectionModel(selectionUniverse, universe =>
AddChainedOptionUniverse(selectionUniverse, universe =>
{
if (universe.Underlying == null)
{
Expand Down
67 changes: 67 additions & 0 deletions Algorithm.Python/AddOptionContractExpiresRegressionAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from datetime import *

### <summary>
### We add an option contract using 'QCAlgorithm.AddOptionContract' and place a trade, the underlying
### gets deselected from the universe selection but should still be present since we manually added the option contract.
### Later we call 'QCAlgorithm.RemoveOptionContract' and expect both option and underlying to be removed.
### </summary>
class AddOptionContractExpiresRegressionAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.SetStartDate(2014, 6, 5)
self.SetEndDate(2014, 6, 30)

self._expiration = datetime(2014, 6, 21)
self._option = None
self._traded = False

self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)

self.AddUniverse("my-daily-universe-name", self.Selector)

def Selector(self, time):
return [ "AAPL" ]

def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if self._option == None:
options = self.OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, self.Time)
options = sorted(options, key=lambda x: x.ID.Symbol)

option = next((option for option in options if option.ID.Date == self._expiration and option.ID.OptionRight == OptionRight.Call and option.ID.OptionStyle == OptionStyle.American), None)
if option != None:
self._option = self.AddOptionContract(option).Symbol;

if self._option != None and self.Securities[self._option].Price != 0 and not self._traded:
self._traded = True;
self.Buy(self._option, 1);

if self.Time > self._expiration and self.Securities[self._twx].Invested:
# we liquidate the option exercised position
self.Liquidate(self._twx);
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from clr import AddReference
AddReference("System")
AddReference("QuantConnect.Algorithm")
AddReference("QuantConnect.Common")

from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from datetime import *

### <summary>
### We add an option contract using 'QCAlgorithm.AddOptionContract' and place a trade, the underlying
### gets deselected from the universe selection but should still be present since we manually added the option contract.
### Later we call 'QCAlgorithm.RemoveOptionContract' and expect both option and underlying to be removed.
### </summary>
class AddOptionContractFromUniverseRegressionAlgorithm(QCAlgorithm):
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.SetStartDate(2014, 6, 5)
self.SetEndDate(2014, 6, 9)

self._expiration = datetime(2014, 6, 21)
self._securityChanges = None
self._option = None
self._traded = False

self._twx = Symbol.Create("TWX", SecurityType.Equity, Market.USA)
self._aapl = Symbol.Create("AAPL", SecurityType.Equity, Market.USA)
self.UniverseSettings.Resolution = Resolution.Minute
self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw

self.AddUniverse(self.Selector, self.Selector)

def Selector(self, fundamental):
if self.Time <= datetime(2014, 6, 5):
return [ self._twx ]
return [ self._aapl ]

def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if self._option != None and self.Securities[self._option].Price != 0 and not self._traded:
self._traded = True;
self.Buy(self._option, 1);

if self.Time == datetime(2014, 6, 6, 14, 0, 0):
# liquidate & remove the option
self.RemoveOptionContract(self._option)

def OnSecuritiesChanged(self, changes):
# keep track of all removed and added securities
if self._securityChanges == None:
self._securityChanges = changes
else:
self._securityChanges.op_Addition(self._securityChanges, changes)

if any(security.Symbol.SecurityType == SecurityType.Option for security in changes.AddedSecurities):
return

for addedSecurity in changes.AddedSecurities:
options = self.OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, self.Time)
options = sorted(options, key=lambda x: x.ID.Symbol)

option = next((option for option in options if option.ID.Date == self._expiration and option.ID.OptionRight == OptionRight.Call and option.ID.OptionStyle == OptionStyle.American), None)

self.AddOptionContract(option)

# just keep the first we got
if self._option == None:
self._option = option
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def Initialize(self):

universe = self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)

self.AddChainedEquityOptionUniverseSelectionModel(universe, self.OptionFilterFunction)
self.AddChainedOptionUniverse(universe, self.OptionFilterFunction)

def OptionFilterFunction(self, universe):
universe.IncludeWeeklys().FrontMonth()
Expand Down
2 changes: 2 additions & 0 deletions Algorithm.Python/QuantConnect.Algorithm.Python.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
<ItemGroup>
<Content Include="AccumulativeInsightPortfolioRegressionAlgorithm.py" />
<Content Include="AddAlphaModelAlgorithm.py" />
<Content Include="AddOptionContractExpiresRegressionAlgorithm.py" />
<Content Include="AddOptionContractFromUniverseRegressionAlgorithm.py" />
<Content Include="AddRiskManagementAlgorithm.py" />
<Content Include="AddUniverseSelectionModelAlgorithm.py" />
<Content Include="Alphas\ContingentClaimsAnalysisDefaultPredictionAlpha.py" />
Expand Down
4 changes: 2 additions & 2 deletions Algorithm/QCAlgorithm.Python.cs
Original file line number Diff line number Diff line change
Expand Up @@ -448,14 +448,14 @@ public Universe AddUniverse(Type dataType, SecurityType securityType, string nam
/// </summary>
/// <param name="universe">The universe we want to chain an option universe selection model too</param>
/// <param name="optionFilter">The option filter universe to use</param>
public void AddChainedEquityOptionUniverseSelectionModel(PyObject universe, PyObject optionFilter)
public void AddChainedOptionUniverse(PyObject universe, PyObject optionFilter)
{
Func<OptionFilterUniverse, OptionFilterUniverse> convertedOptionChain;
Universe universeToChain;

if (universe.TryConvert(out universeToChain) && optionFilter.TryConvertToDelegate(out convertedOptionChain))
{
AddChainedEquityOptionUniverseSelectionModel(universeToChain, convertedOptionChain);
AddChainedOptionUniverse(universeToChain, convertedOptionChain);
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion Algorithm/QCAlgorithm.Universe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ public Universe AddUniverse(SecurityType securityType, string name, Resolution r
/// </summary>
/// <param name="universe">The universe we want to chain an option universe selection model too</param>
/// <param name="optionFilter">The option filter universe to use</param>
public void AddChainedEquityOptionUniverseSelectionModel(Universe universe, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter)
public void AddChainedOptionUniverse(Universe universe, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter)
{
AddUniverseSelection(new OptionChainedUniverseSelectionModel(universe, optionFilter));
}
Expand Down

0 comments on commit 62cc181

Please sign in to comment.