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); // We must set the volatility model on the underlying, since the defaults are // too strict to calculate greeks with when we only have data for a single day _es19m20.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel( 60, Resolution.Minute, TimeSpan.FromMinutes(1)); // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20.Symbol, new DateTime(2020, 1, 5)) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute); _esOption.PriceModel = OptionPriceModels.BjerksundStensland(); _expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20.Symbol, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19)); if (_esOption.Symbol != _expectedOptionContract) { throw new Exception($"Contract {_expectedOptionContract} was not found in the chain"); } }
public override void Initialize() { SetStartDate(2021, 1, 4); SetEndDate(2021, 1, 31); _spx = AddIndex("SPX", Resolution.Minute).Symbol; // Select a index option expiring ITM, and adds it to the algorithm. _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 3200m, new DateTime(2021, 1, 15)); if (_spxOption != _expectedContract) { throw new Exception($"Contract {_expectedContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () => { MarketOrder(_spxOption, 1); }); }
public override void Initialize() { SetStartDate(2012, 1, 3); SetEndDate(2012, 1, 4); // Add our underlying future contract var dc = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Dairy.ClassIIIMilk, Market.CME, new DateTime(2012, 4, 1)), Resolution).Symbol; // Attempt to fetch a specific future option contract DcOption = OptionChainProvider.GetOptionContractList(dc, Time) .Where(x => x.ID.StrikePrice == 17m && x.ID.OptionRight == OptionRight.Call) .Select(x => AddFutureOptionContract(x, Resolution).Symbol) .FirstOrDefault(); // Validate it is the expected contract var expectedContract = QuantConnect.Symbol.CreateOption(dc, Market.CME, OptionStyle.American, OptionRight.Call, 17m, new DateTime(2012, 4, 01)); if (DcOption != expectedContract) { throw new Exception($"Contract {DcOption} was not the expected contract {expectedContract}"); } ScheduleBuySell(); }
public override void OnData(Slice data) { if (!Portfolio.Invested) { var contracts = OptionChainProvider.GetOptionContractList(_equitySymbol, data.Time); var underlyingPrice = Securities[_equitySymbol].Price; // filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on var otmCalls = (from symbol in contracts where symbol.ID.OptionRight == OptionRight.Call where symbol.ID.StrikePrice - underlyingPrice > 0 where ((symbol.ID.Date - data.Time).TotalDays < 30 && (symbol.ID.Date - data.Time).TotalDays > 10) select symbol); if (otmCalls.Count() != 0) { var contract = otmCalls.OrderBy(x => x.ID.Date) .ThenBy(x => (x.ID.StrikePrice - underlyingPrice)) .FirstOrDefault(); // Before placing the order, use AddOptionContract() to subscribe the requested contract symbol AddOptionContract(contract, Resolution.Minute); MarketOrder(contract, -1); MarketOrder(_equitySymbol, 100); } } }
/// <summary> /// Gets <see cref="OptionHistory"/> object for a given symbol, date and resolution /// </summary> /// <param name="symbol">The symbol to retrieve historical option data for</param> /// <param name="date">Date of the data</param> /// <param name="resolution">The resolution to request</param> /// <returns>A <see cref="OptionHistory"/> object that contains historical option data.</returns> public OptionHistory GetOptionHistory(Symbol symbol, DateTime start, DateTime?end = null, Resolution?resolution = null) { if (!end.HasValue || end.Value.Date == start.Date) { end = start.AddDays(1); } var option = Securities[symbol] as Option; var resolutionToUseForUnderlying = resolution ?? SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol) .GetHighestResolution(); var underlying = AddEquity(symbol.Underlying.Value, resolutionToUseForUnderlying); var allSymbols = new List <Symbol>(); for (var date = start; date < end; date = date.AddDays(1)) { if (option.Exchange.DateIsOpen(date)) { allSymbols.AddRange(OptionChainProvider.GetOptionContractList(symbol.Underlying, date)); } } var symbols = base.History(symbol.Underlying, start, end.Value, resolution) .SelectMany(x => option.ContractFilter.Filter(new OptionFilterUniverse(allSymbols.Distinct(), x))) .Distinct().Concat(new[] { symbol.Underlying }); return(new OptionHistory(History(symbols, start, end.Value, resolution))); }
public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872 // which causes delisting events to never be processed, thus leading to options that might never // be exercised until the next data point arrives. AddEquity("AAPL", Resolution.Daily); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice >= 3400m && 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, 3400m, 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 Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 1, 6); _es20h20 = AddFutureContract( QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)), Resolution.Minute).Symbol; _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; var optionChains = OptionChainProvider.GetOptionContractList(_es20h20, Time) .Concat(OptionChainProvider.GetOptionContractList(_es19m20, Time)); foreach (var optionContract in optionChains) { _expectedSymbolsReceived.Add(AddFutureOptionContract(optionContract, Resolution.Minute).Symbol); } if (_expectedSymbolsReceived.Count == 0) { throw new InvalidOperationException("Expected Symbols receive count is 0, expected >0"); } }
public override void Initialize() { SetStartDate(2021, 1, 4); SetEndDate(2021, 1, 31); var spx = AddIndex("SPX", Resolution.Minute); spx.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(60, Resolution.Minute, TimeSpan.FromMinutes(1)); _spx = spx.Symbol; // Select an index option expiring ITM, and adds it to the algorithm. _spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute); _spxOption.PriceModel = OptionPriceModels.BlackScholes(); _expectedOptionContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Call, 3200m, new DateTime(2021, 1, 15)); if (_spxOption.Symbol != _expectedOptionContract) { throw new Exception($"Contract {_expectedOptionContract} was not found in the chain"); } }
public void Scan() { foreach (var underlying in _underlyings) { var contracts = OptionChainProvider.GetOptionContractList(underlying, Time); var underlyingPrice = Portfolio[underlying].Price; var specificContracts = (from contract in contracts where contract.ID.OptionStyle == OptionStyle.American && contract.ID.OptionRight == OptionRight.Call && contract.ID.StrikePrice > underlyingPrice && contract.ID.Date > Time.AddDays(15) && contract.ID.Date < Time.AddDays(60) && contract.ID.Date == new DateTime(2017, 10, 20) select contract).OrderBy(c => c.ID.StrikePrice).FirstOrDefault(); if (specificContracts != null) { var optionContract = AddOptionContract(specificContracts, Resolution.Minute); Manager[underlying] = new Position() { Ticker = underlying, Security = optionContract, OptionPrice = optionContract.Close, Symbol = optionContract.Symbol, UnderlyingPrice = underlyingPrice }; } } }
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 expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19)); if (_esOption != _expectedOptionContract) { throw new Exception($"Contract {_expectedOptionContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); }
/// <summary> /// Gets <see cref="OptionHistory"/> object for a given symbol, date and resolution /// </summary> /// <param name="symbol">The symbol to retrieve historical option data for</param> /// <param name="start">The history request start time</param> /// <param name="end">The history request end time. Defaults to 1 day if null</param> /// <param name="resolution">The resolution to request</param> /// <returns>A <see cref="OptionHistory"/> object that contains historical option data.</returns> public OptionHistory GetOptionHistory(Symbol symbol, DateTime start, DateTime?end = null, Resolution?resolution = null) { if (!end.HasValue || end.Value == start) { end = start.AddDays(1); } // Load a canonical option Symbol if the user provides us with an underlying Symbol if (symbol.SecurityType != SecurityType.Option && symbol.SecurityType != SecurityType.FutureOption) { symbol = AddOption(symbol, resolution, symbol.ID.Market).Symbol; } IEnumerable <Symbol> symbols; if (symbol.IsCanonical()) { // canonical symbol, lets find the contracts var option = Securities[symbol] as Option; var resolutionToUseForUnderlying = resolution ?? SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol) .GetHighestResolution(); if (!Securities.ContainsKey(symbol.Underlying)) { // only add underlying if not present AddEquity(symbol.Underlying.Value, resolutionToUseForUnderlying); } var allSymbols = new List <Symbol>(); for (var date = start; date < end; date = date.AddDays(1)) { if (option.Exchange.DateIsOpen(date)) { allSymbols.AddRange(OptionChainProvider.GetOptionContractList(symbol.Underlying, date)); } } var optionFilterUniverse = new OptionFilterUniverse(); var distinctSymbols = allSymbols.Distinct(); symbols = base.History(symbol.Underlying, start, end.Value, resolution) .SelectMany(x => { // the option chain symbols wont change so we can set 'exchangeDateChange' to false always optionFilterUniverse.Refresh(distinctSymbols, x, exchangeDateChange: false); return(option.ContractFilter.Filter(optionFilterUniverse)); }) .Distinct().Concat(new[] { symbol.Underlying }); } else { // the symbol is a contract symbols = new List <Symbol> { symbol }; } return(new OptionHistory(History(symbols, start, end.Value, resolution))); }
public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); // We add AAPL as a temporary workaround for https://github.com/QuantConnect/Lean/issues/4872 // which causes delisting events to never be processed, thus leading to options that might never // be exercised until the next data point arrives. AddEquity("AAPL", Resolution.Daily); var es20h20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)), Resolution.Minute).Symbol; var es20m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time) .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time)) .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call) .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol) .ToList(); var expectedContracts = new[] { QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 3, 20)), QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19)) }; foreach (var esOption in esOptions) { if (!expectedContracts.Contains(esOption)) { throw new Exception($"Contract {esOption} was not found in the chain"); } } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () => { MarketOrder(esOptions[0], 1); MarketOrder(esOptions[1], -1); }); Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () => { Liquidate(); }); }
public override void OnData(Slice slice) { if (!slice.ContainsKey(_spx)) { return; } if (_addOption) { var contracts = OptionChainProvider.GetOptionContractList(_spx, Time); contracts = contracts.Where(x => x.ID.OptionRight == OptionRight.Put && x.ID.Date.Date == new DateTime(2021, 1, 15)); var option = AddIndexOptionContract(contracts.First(), Resolution.Minute); _optionExpiry = option.Expiry; _optionSymbol = option.Symbol; _addOption = false; } if (slice.ContainsKey(_optionSymbol)) { if (!Portfolio.Invested) { SetHoldings(_optionSymbol, 0.25); } // Verify the order of delisting; warning then delisting Delisting delisting; if (slice.Delistings.TryGetValue(_optionSymbol, out delisting)) { switch (delisting.Type) { case DelistingType.Warning: _receivedWarning = true; break; case DelistingType.Delisted: if (!_receivedWarning) { throw new Exception("Did not receive warning before delisting"); } break; } } // Verify we aren't receiving expired option data. if (_optionExpiry < Time.Date) { throw new Exception($"Received expired contract {_optionSymbol} expired: {_optionExpiry} current time: {Time}"); } } }
public override void Initialize() { SetStartDate(2021, 1, 4); SetEndDate(2021, 1, 31); var spx = AddIndex("SPX", Resolution.Minute).Symbol; // Select a index option expiring ITM, and adds it to the algorithm. var spxOptions = OptionChainProvider.GetOptionContractList(spx, Time) .Where(x => (x.ID.StrikePrice == 3700m || x.ID.StrikePrice == 3800m) && x.ID.OptionRight == OptionRight.Call && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1) .Select(x => AddIndexOptionContract(x, Resolution.Minute).Symbol) .OrderBy(x => x.ID.StrikePrice) .ToList(); var expectedContract3700 = QuantConnect.Symbol.CreateOption( spx, Market.USA, OptionStyle.European, OptionRight.Call, 3700m, new DateTime(2021, 1, 15)); var expectedContract3800 = QuantConnect.Symbol.CreateOption( spx, Market.USA, OptionStyle.European, OptionRight.Call, 3800m, new DateTime(2021, 1, 15)); if (spxOptions.Count != 2) { throw new Exception($"Expected 2 index options symbols from chain provider, found {spxOptions.Count}"); } if (spxOptions[0] != expectedContract3700) { throw new Exception($"Contract {expectedContract3700} was not found in the chain, found instead: {spxOptions[0]}"); } if (spxOptions[1] != expectedContract3800) { throw new Exception($"Contract {expectedContract3800} was not found in the chain, found instead: {spxOptions[1]}"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(spx, 1), () => { MarketOrder(spxOptions[0], 1); MarketOrder(spxOptions[1], -1); }); Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () => { Liquidate(); }); }
public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); var es20h20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 3, 20)), Resolution.Minute).Symbol; var es20m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. var esOptions = OptionChainProvider.GetOptionContractList(es20m20, Time) .Concat(OptionChainProvider.GetOptionContractList(es20h20, Time)) .Where(x => x.ID.StrikePrice == 3200m && x.ID.OptionRight == OptionRight.Call) .Select(x => AddFutureOptionContract(x, Resolution.Minute).Symbol) .ToList(); var expectedContracts = new[] { QuantConnect.Symbol.CreateOption(es20h20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 3, 20)), QuantConnect.Symbol.CreateOption(es20m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19)) }; foreach (var esOption in esOptions) { if (!expectedContracts.Contains(esOption)) { throw new Exception($"Contract {esOption} was not found in the chain"); } } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(es20m20, 1), () => { MarketOrder(esOptions[0], 1); MarketOrder(esOptions[1], -1); }); Schedule.On(DateRules.Tomorrow, TimeRules.Noon, () => { Liquidate(); }); }
public override void Initialize() { SetStartDate(2014, 06, 06); SetEndDate(2014, 06, 09); UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw; UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; var aapl = AddEquity("AAPL").Symbol; _contract = OptionChainProvider.GetOptionContractList(aapl, Time) .OrderBy(symbol => symbol.ID.Symbol) .FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American); }
public override void OnSecuritiesChanged(SecurityChanges changes) { if (_securityChanges.RemovedSecurities.Intersect(changes.RemovedSecurities).Any()) { throw new Exception($"SecurityChanges.RemovedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!"); } if (_securityChanges.AddedSecurities.Intersect(changes.AddedSecurities).Any()) { throw new Exception($"SecurityChanges.AddedSecurities intersect {changes.RemovedSecurities}. We expect no duplicate!"); } // keep track of all removed and added securities _securityChanges += changes; if (changes.AddedSecurities.Any(security => security.Symbol.SecurityType == SecurityType.Option)) { return; } foreach (var addedSecurity in changes.AddedSecurities) { var option = OptionChainProvider.GetOptionContractList(addedSecurity.Symbol, Time) .OrderBy(symbol => symbol.ID.Symbol) .First(optionContract => optionContract.ID.Date == _expiration && optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American); AddOptionContract(option); foreach (var symbol in new[] { option, option.Underlying }) { var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList(); if (!config.Any()) { throw new Exception($"Was expecting configurations for {symbol}"); } if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw)) { throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}"); } } // just keep the first we got if (_option == null) { _option = option; } } }
public override void Initialize() { SetStartDate(2014, 06, 05); SetEndDate(2014, 06, 09); var equitySymbol = AddEquity("TWX").Symbol; var contracts = OptionChainProvider.GetOptionContractList(equitySymbol, UtcTime).ToList(); var callOptionSymbol = contracts .Where(c => c.ID.OptionRight == OptionRight.Call) .OrderBy(c => c.ID.Date) .First(); _optionContract = AddOptionContract(callOptionSymbol).Symbol; _canonicalOptionContract = _optionContract.Canonical; }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2014, 06, 05); SetEndDate(2014, 06, 23); AddEquity("AAPL", Resolution.Daily); _equitySymbol = AddEquity("TWX", Resolution.Minute).Symbol; var contracts = OptionChainProvider.GetOptionContractList(_equitySymbol, UtcTime).ToList(); var callOptionSymbol = contracts .Where(c => c.ID.OptionRight == OptionRight.Call) .OrderBy(c => c.ID.Date) .First(); _optionContract = AddOptionContract(callOptionSymbol).Symbol; }
public void Scan() { foreach (var underlying in _underlyings) { var contracts = OptionChainProvider.GetOptionContractList(underlying, Time); var underlyingPrice = Portfolio[underlying].Price; var specificContract = (from contract in contracts where contract.ID.OptionStyle == OptionStyle.American && contract.ID.OptionRight == OptionRight.Call && contract.ID.StrikePrice > underlyingPrice && contract.ID.Date > Time.AddDays(15) && contract.ID.Date < Time.AddDays(60) && contract.ID.Date == new DateTime(2017, 10, 20) select contract).OrderBy(c => c.ID.StrikePrice).FirstOrDefault(); if (specificContract != null) { Option optionContract = null; if ((Securities.ContainsKey(specificContract) && (Securities[specificContract].Invested))) { optionContract = (Option)Securities[specificContract]; } else { optionContract = AddOptionContract(specificContract, Resolution.Minute); } Manager[underlying] = new CoveredCallPosition() { Ticker = underlying, OptionSecurity = optionContract, OptionPrice = optionContract.Close, UnderlyingSymbol = optionContract.Symbol, UnderlyingPrice = underlyingPrice }; // Do Stuff if (!optionContract.Invested) { RemoveSecurity(optionContract.Symbol); } } } }
/// <summary> /// Gets <see cref="OptionHistory"/> object for a given symbol, date and resolution /// </summary> /// <param name="symbol">The symbol to retrieve historical option data for</param> /// <param name="start">The history request start time</param> /// <param name="end">The history request end time. Defaults to 1 day if null</param> /// <param name="resolution">The resolution to request</param> /// <returns>A <see cref="OptionHistory"/> object that contains historical option data.</returns> public OptionHistory GetOptionHistory(Symbol symbol, DateTime start, DateTime?end = null, Resolution?resolution = null) { if (!end.HasValue || end.Value == start) { end = start.AddDays(1); } IEnumerable <Symbol> symbols; if (symbol.IsCanonical()) { // canonical symbol, lets find the contracts var option = Securities[symbol] as Option; var resolutionToUseForUnderlying = resolution ?? SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol) .GetHighestResolution(); if (!Securities.ContainsKey(symbol.Underlying)) { // only add underlying if not present AddEquity(symbol.Underlying.Value, resolutionToUseForUnderlying); } var allSymbols = new List <Symbol>(); for (var date = start; date < end; date = date.AddDays(1)) { if (option.Exchange.DateIsOpen(date)) { allSymbols.AddRange(OptionChainProvider.GetOptionContractList(symbol.Underlying, date)); } } symbols = base.History(symbol.Underlying, start, end.Value, resolution) .SelectMany(x => option.ContractFilter.Filter(new OptionFilterUniverse(allSymbols.Distinct(), x))) .Distinct().Concat(new[] { symbol.Underlying }); } else { // the symbol is a contract symbols = new List <Symbol> { symbol }; } return(new OptionHistory(History(symbols, start, end.Value, resolution))); }
public override void Initialize() { SetStartDate(2014, 06, 06); SetEndDate(2014, 06, 09); UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw; UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; UniverseSettings.FillForward = false; AddEquity("SPY", Resolution.Daily); var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA); _contract = OptionChainProvider.GetOptionContractList(aapl, Time) .OrderBy(symbol => symbol.ID.Symbol) .FirstOrDefault(optionContract => optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American); AddOptionContract(_contract); }
public override void OnData(Slice data) { if (!Portfolio[_equitySymbol].Invested) { MarketOrder(_equitySymbol, 100); } if (!(Securities.ContainsKey(_optionContract) && Portfolio[_optionContract].Invested)) { var contracts = OptionChainProvider.GetOptionContractList(_equitySymbol, data.Time); var underlyingPrice = Securities[_equitySymbol].Price; // filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on var otmCalls = (from symbol in contracts where symbol.ID.OptionRight == OptionRight.Call where symbol.ID.StrikePrice - underlyingPrice > 0 where ((symbol.ID.Date - data.Time).TotalDays < 30 && (symbol.ID.Date - data.Time).TotalDays > 10) select symbol); if (otmCalls.Count() != 0) { _optionContract = otmCalls.OrderBy(x => x.ID.Date) .ThenBy(x => (x.ID.StrikePrice - underlyingPrice)) .FirstOrDefault(); if (_contractsAdded.Add(_optionContract)) { // use AddOptionContract() to subscribe the data for specified contract AddOptionContract(_optionContract, Resolution.Minute); } } else { _optionContract = string.Empty; } } if (Securities.ContainsKey(_optionContract) && !Portfolio[_optionContract].Invested) { MarketOrder(_optionContract, -1); } }
public override void Initialize() { SetStartDate(2014, 06, 06); SetEndDate(2014, 06, 06); UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw; UniverseSettings.MinimumTimeInUniverse = TimeSpan.Zero; var aapl = QuantConnect.Symbol.Create("AAPL", SecurityType.Equity, Market.USA); var contracts = OptionChainProvider.GetOptionContractList(aapl, Time) .OrderBy(symbol => symbol.ID.Symbol) .Where(optionContract => optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American) .Take(2) .ToList(); _contract1 = contracts[0]; _contract2 = contracts[1]; AddOptionContract(_contract1); AddOptionContract(_contract2); }
public override void Initialize() { SetStartDate(2015, 12, 23); SetEndDate(2015, 12, 24); SetCash(100000); Stock = AddEquity("GOOG", Resolution.Minute); var contracts = OptionChainProvider.GetOptionContractList(Stock.Symbol, UtcTime).ToList(); PutOptionSymbol = contracts .Where(c => c.ID.OptionRight == OptionRight.Put) .OrderBy(c => c.ID.Date) .First(c => c.ID.StrikePrice == 800m); CallOptionSymbol = contracts .Where(c => c.ID.OptionRight == OptionRight.Call) .OrderBy(c => c.ID.Date) .First(c => c.ID.StrikePrice == 600m); PutOption = AddOptionContract(PutOptionSymbol); CallOption = AddOptionContract(CallOptionSymbol); }
public override void OnData(Slice data) { // Compare our previous slice time to this slice // Because of issues with Delisting data we have to let Auxiliary data pass through GH #5207 if (Time.Ticks - _lastSliceTime.Ticks < 1000 && data.Values.Any(x => x.DataType != MarketDataType.Auxiliary)) { throw new Exception($"Emitted two slices within 1000 ticks of each other."); } // Store our slice time _lastSliceTime = Time; var underlyingPrice = Securities[_symbol].Price; var contractSymbol = OptionChainProvider.GetOptionContractList(_symbol, Time) .Where(x => x.ID.StrikePrice - underlyingPrice > 0) .OrderBy(x => x.ID.Date) .FirstOrDefault(); if (contractSymbol != null) { _optionSymbol = AddOptionContract(contractSymbol).Symbol; } }
public void OnData(TradeBars data) { if (IsMarketOpen(iSymbol) == false) { return; } if (IsNewBar(TimeSpan.FromHours(1)) == false) { return; } var price = Securities[iSymbol].Price; // If options were exercised and we were assigned to buy shares, sell them immediately if (Portfolio[iSymbol].Invested) { MarketOrder(iSymbol, -100); } if (Portfolio.Invested == false) { var contracts = OptionChainProvider.GetOptionContractList(iSymbol, Time); // Choose all contracts within a month and strike price $1 to $5 from current underlying price var atmPuts = from c in contracts where c.ID.OptionRight == OptionRight.Put where price - c.ID.StrikePrice < 3 && price - c.ID.StrikePrice > 1 where (c.ID.Date - Time).TotalDays < 45 && (c.ID.Date - Time).TotalDays > 0 select c; // Choose all contracts within a month and strike price $1 to $5 from current underlying price var otmPuts = from c in contracts where c.ID.OptionRight == OptionRight.Put where price - c.ID.StrikePrice < 7 && price - c.ID.StrikePrice > 5 where (c.ID.Date - Time).TotalDays < 45 && (c.ID.Date - Time).TotalDays > 0 select c; // Take ATM options with the MIN expiration date and MAX distance from underlying price var contractAtmPut = atmPuts .OrderBy(o => o.ID.Date) .ThenBy(o => price - o.ID.StrikePrice) .FirstOrDefault(); // Take OTM options with the MIN expiration date and MAX distance from underlying price var contractOtmPut = otmPuts .OrderBy(o => o.ID.Date) .ThenBy(o => price - o.ID.StrikePrice) .FirstOrDefault(); // If we found such options - open trade if (contractAtmPut != null && contractOtmPut != null) { AddOptionContract(contractAtmPut, Resolution.Minute); AddOptionContract(contractOtmPut, Resolution.Minute); MarketOrder(contractAtmPut, -1); MarketOrder(contractOtmPut, 1); } } }
public override void OnData(Slice data) { if (_option == null) { var option = OptionChainProvider.GetOptionContractList(_twx, Time) .OrderBy(symbol => symbol.ID.Symbol) .FirstOrDefault(optionContract => optionContract.ID.Date == _expiration && optionContract.ID.OptionRight == OptionRight.Call && optionContract.ID.OptionStyle == OptionStyle.American); if (option != null) { _option = AddOptionContract(option).Symbol; } } if (_option != null && Securities[_option].Price != 0 && !_traded) { _traded = true; Buy(_option, 1); foreach (var symbol in new [] { _option, _option.Underlying }) { var config = SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(symbol).ToList(); if (!config.Any()) { throw new Exception($"Was expecting configurations for {symbol}"); } if (config.Any(dataConfig => dataConfig.DataNormalizationMode != DataNormalizationMode.Raw)) { throw new Exception($"Was expecting DataNormalizationMode.Raw configurations for {symbol}"); } } } if (Time.Date > _expiration) { if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_option).Any()) { throw new Exception($"Unexpected configurations for {_option} after it has been delisted"); } if (Securities[_twx].Invested) { if (!SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any()) { throw new Exception($"Was expecting configurations for {_twx}"); } // first we liquidate the option exercised position Liquidate(_twx); } } else if (Time.Date > _expiration && !Securities[_twx].Invested) { if (SubscriptionManager.SubscriptionDataConfigService.GetSubscriptionDataConfigs(_twx).Any()) { throw new Exception($"Unexpected configurations for {_twx} after it has been liquidated"); } } }
/// <summary> /// Gets <see cref="OptionHistory"/> object for a given symbol, date and resolution /// </summary> /// <param name="symbol">The symbol to retrieve historical option data for</param> /// <param name="start">The history request start time</param> /// <param name="end">The history request end time. Defaults to 1 day if null</param> /// <param name="resolution">The resolution to request</param> /// <returns>A <see cref="OptionHistory"/> object that contains historical option data.</returns> public OptionHistory GetOptionHistory(Symbol symbol, DateTime start, DateTime?end = null, Resolution?resolution = null) { if (!end.HasValue || end.Value == start) { end = start.AddDays(1); } // Load a canonical option Symbol if the user provides us with an underlying Symbol if (!symbol.SecurityType.IsOption()) { var option = AddOption(symbol, resolution, symbol.ID.Market); // Allow 20 strikes from the money for futures. No expiry filter is applied // so that any future contract provided will have data returned. if (symbol.SecurityType == SecurityType.Future && symbol.IsCanonical()) { throw new ArgumentException("The Future Symbol provided is a canonical Symbol (i.e. a Symbol representing all Futures), which is not supported at this time. " + "If you are using the Symbol accessible from `AddFuture(...)`, use the Symbol from `AddFutureContract(...)` instead. " + "You can use `qb.FutureOptionChainProvider(canonicalFuture, datetime)` to get a list of futures contracts for a given date, and add them to your algorithm with `AddFutureContract(symbol, Resolution)`."); } if (symbol.SecurityType == SecurityType.Future && !symbol.IsCanonical()) { option.SetFilter(universe => universe.Strikes(-10, +10)); } symbol = option.Symbol; } IEnumerable <Symbol> symbols; if (symbol.IsCanonical()) { // canonical symbol, lets find the contracts var option = Securities[symbol] as Option; var resolutionToUseForUnderlying = resolution ?? SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(symbol) .GetHighestResolution(); if (!Securities.ContainsKey(symbol.Underlying)) { if (symbol.Underlying.SecurityType == SecurityType.Equity) { // only add underlying if not present AddEquity(symbol.Underlying.Value, resolutionToUseForUnderlying); } if (symbol.Underlying.SecurityType == SecurityType.Future && symbol.Underlying.IsCanonical()) { AddFuture(symbol.Underlying.ID.Symbol, resolutionToUseForUnderlying); } else if (symbol.Underlying.SecurityType == SecurityType.Future) { AddFutureContract(symbol.Underlying, resolutionToUseForUnderlying); } } var allSymbols = new List <Symbol>(); for (var date = start; date < end; date = date.AddDays(1)) { if (option.Exchange.DateIsOpen(date)) { allSymbols.AddRange(OptionChainProvider.GetOptionContractList(symbol.Underlying, date)); } } var optionFilterUniverse = new OptionFilterUniverse(); var distinctSymbols = allSymbols.Distinct(); symbols = base.History(symbol.Underlying, start, end.Value, resolution) .SelectMany(x => { // the option chain symbols wont change so we can set 'exchangeDateChange' to false always optionFilterUniverse.Refresh(distinctSymbols, x, exchangeDateChange: false); return(option.ContractFilter.Filter(optionFilterUniverse)); }) .Distinct().Concat(new[] { symbol.Underlying }); } else { // the symbol is a contract symbols = new List <Symbol> { symbol }; } return(new OptionHistory(History(symbols, start, end.Value, resolution))); }