22caf9ef2a
Build & Test Lean / build (push) Has been cancelled
* FOPs margin as a curve - Adjust FOPs margin requirement so that it behaves like an 'S' curve for the contract strike, around the underlying price and it's margin requirement. Based on IB behavior. Adding unit tests for different future contracts - Improve a couple of unit test cleanup * Add ES Short Call unit test
226 lines
9.3 KiB
C#
226 lines
9.3 KiB
C#
/*
|
|
* 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.
|
|
*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using QuantConnect.Data;
|
|
using QuantConnect.Interfaces;
|
|
using QuantConnect.Orders;
|
|
using QuantConnect.Securities;
|
|
|
|
namespace QuantConnect.Algorithm.CSharp
|
|
{
|
|
/// <summary>
|
|
/// This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
|
|
/// We expect 2 orders from the algorithm, which are:
|
|
///
|
|
/// * Initial entry, buy ES Call Option (expiring OTM)
|
|
/// - contract expires worthless, not exercised, so never opened a position in the underlying
|
|
///
|
|
/// * Liquidation of worthless ES call option (expiring OTM)
|
|
///
|
|
/// Additionally, we test delistings for future options and assert that our
|
|
/// portfolio holdings reflect the orders the algorithm has submitted.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
|
|
/// See related issue: https://github.com/QuantConnect/Lean/issues/4854
|
|
/// </remarks>
|
|
public class FutureOptionCallOTMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
|
{
|
|
private Symbol _es19m20;
|
|
private Symbol _esOption;
|
|
private Symbol _expectedContract;
|
|
|
|
public override void Initialize()
|
|
{
|
|
SetStartDate(2020, 1, 5);
|
|
SetEndDate(2020, 6, 30);
|
|
|
|
_es19m20 = AddFutureContract(
|
|
QuantConnect.Symbol.CreateFuture(
|
|
Futures.Indices.SP500EMini,
|
|
Market.CME,
|
|
new DateTime(2020, 6, 19)),
|
|
Resolution.Minute).Symbol;
|
|
|
|
// Select a future option call expiring OTM, and adds it to the algorithm.
|
|
_esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time)
|
|
.Where(x => x.ID.StrikePrice >= 3300m && x.ID.OptionRight == OptionRight.Call)
|
|
.OrderBy(x => x.ID.StrikePrice)
|
|
.Take(1)
|
|
.Single(), Resolution.Minute).Symbol;
|
|
|
|
_expectedContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3300m, new DateTime(2020, 6, 19));
|
|
if (_esOption != _expectedContract)
|
|
{
|
|
throw new Exception($"Contract {_expectedContract} was not found in the chain");
|
|
}
|
|
|
|
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () =>
|
|
{
|
|
MarketOrder(_esOption, 1);
|
|
});
|
|
}
|
|
|
|
public override void OnData(Slice data)
|
|
{
|
|
// Assert delistings, so that we can make sure that we receive the delisting warnings at
|
|
// the expected time. These assertions detect bug #4872
|
|
foreach (var delisting in data.Delistings.Values)
|
|
{
|
|
if (delisting.Type == DelistingType.Warning)
|
|
{
|
|
if (delisting.Time != new DateTime(2020, 6, 19))
|
|
{
|
|
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
|
|
}
|
|
}
|
|
if (delisting.Type == DelistingType.Delisted)
|
|
{
|
|
if (delisting.Time != new DateTime(2020, 6, 20))
|
|
{
|
|
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public override void OnOrderEvent(OrderEvent orderEvent)
|
|
{
|
|
if (orderEvent.Status != OrderStatus.Filled)
|
|
{
|
|
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
|
|
return;
|
|
}
|
|
|
|
if (!Securities.ContainsKey(orderEvent.Symbol))
|
|
{
|
|
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
|
|
}
|
|
|
|
var security = Securities[orderEvent.Symbol];
|
|
if (security.Symbol == _es19m20)
|
|
{
|
|
throw new Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM");
|
|
}
|
|
if (security.Symbol == _expectedContract)
|
|
{
|
|
AssertFutureOptionContractOrder(orderEvent, security);
|
|
}
|
|
else
|
|
{
|
|
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
|
|
}
|
|
|
|
Log($"{orderEvent}");
|
|
}
|
|
|
|
private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option)
|
|
{
|
|
if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1)
|
|
{
|
|
throw new Exception($"No holdings were created for option contract {option.Symbol}");
|
|
}
|
|
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0)
|
|
{
|
|
throw new Exception("Holdings were found after a filled option exercise");
|
|
}
|
|
if (orderEvent.Direction == OrderDirection.Sell && !orderEvent.Message.Contains("OTM"))
|
|
{
|
|
throw new Exception("Contract did not expire OTM");
|
|
}
|
|
if (orderEvent.Message.Contains("Exercise"))
|
|
{
|
|
throw new Exception("Exercised option, even though it expires OTM");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
|
|
/// </summary>
|
|
/// <exception cref="Exception">The algorithm has holdings</exception>
|
|
public override void OnEndOfAlgorithm()
|
|
{
|
|
if (Portfolio.Invested)
|
|
{
|
|
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
|
/// </summary>
|
|
public bool CanRunLocally { get; } = true;
|
|
|
|
/// <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, Language.Python };
|
|
|
|
/// <summary>
|
|
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
|
/// </summary>
|
|
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
|
{
|
|
{"Total Trades", "2"},
|
|
{"Average Win", "0%"},
|
|
{"Average Loss", "-4.03%"},
|
|
{"Compounding Annual Return", "-8.103%"},
|
|
{"Drawdown", "4.000%"},
|
|
{"Expectancy", "-1"},
|
|
{"Net Profit", "-4.029%"},
|
|
{"Sharpe Ratio", "-1.266"},
|
|
{"Probabilistic Sharpe Ratio", "0.015%"},
|
|
{"Loss Rate", "100%"},
|
|
{"Win Rate", "0%"},
|
|
{"Profit-Loss Ratio", "0"},
|
|
{"Alpha", "-0.065"},
|
|
{"Beta", "0.002"},
|
|
{"Annual Standard Deviation", "0.051"},
|
|
{"Annual Variance", "0.003"},
|
|
{"Information Ratio", "-0.222"},
|
|
{"Tracking Error", "0.408"},
|
|
{"Treynor Ratio", "-27.32"},
|
|
{"Total Fees", "$3.70"},
|
|
{"Estimated Strategy Capacity", "$200000000.00"},
|
|
{"Lowest Capacity Asset", "ES XFH59UPHGV9G|ES XFH59UK0MYO1"},
|
|
{"Fitness Score", "0"},
|
|
{"Kelly Criterion Estimate", "0"},
|
|
{"Kelly Criterion Probability Value", "0"},
|
|
{"Sortino Ratio", "-0.184"},
|
|
{"Return Over Maximum Drawdown", "-2.013"},
|
|
{"Portfolio Turnover", "0"},
|
|
{"Total Insights Generated", "0"},
|
|
{"Total Insights Closed", "0"},
|
|
{"Total Insights Analysis Completed", "0"},
|
|
{"Long Insight Count", "0"},
|
|
{"Short Insight Count", "0"},
|
|
{"Long/Short Ratio", "100%"},
|
|
{"Estimated Monthly Alpha Value", "$0"},
|
|
{"Total Accumulated Estimated Alpha Value", "$0"},
|
|
{"Mean Population Estimated Insight Value", "$0"},
|
|
{"Mean Population Direction", "0%"},
|
|
{"Mean Population Magnitude", "0%"},
|
|
{"Rolling Averaged Population Direction", "0%"},
|
|
{"Rolling Averaged Population Magnitude", "0%"},
|
|
{"OrderListHash", "5dc2591837f882d173d2d4852b3b0626"}
|
|
};
|
|
}
|
|
}
|
|
|