Esempio n. 1
0
        public void PutCallParityTest()
        {
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           spy                   = Symbols.SPY;
            var           SPY_C_192_Feb19_2016E = GetOptionSymbol(spy, OptionStyle.European, OptionRight.Call);
            var           SPY_P_192_Feb19_2016E = GetOptionSymbol(spy, OptionStyle.European, OptionRight.Put);

            // setting up underlying
            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            // setting up European style call option
            var contractCall = GetOptionContract(SPY_C_192_Feb19_2016E, spy, evaluationDate);
            var optionCall   = GetOption(SPY_C_192_Feb19_2016E, equity, tz);

            // setting up European style put option
            var contractPut = GetOptionContract(SPY_P_192_Feb19_2016E, spy, evaluationDate);
            var optionPut   = GetOption(SPY_P_192_Feb19_2016E, equity, tz);

            // running evaluation
            var priceModel  = OptionPriceModels.BlackScholes();
            var resultsCall = priceModel.Evaluate(optionCall, null, contractCall);
            var resultsPut  = priceModel.Evaluate(optionPut, null, contractPut);
            var callPrice   = resultsCall.TheoreticalPrice;
            var putPrice    = resultsPut.TheoreticalPrice;

            // Put-call parity equation
            var rightPart = putPrice + underlyingPrice; // no yield
            var leftPart  = callPrice + contractCall.Strike * (decimal)Math.Exp((double)-riskFreeRate);

            Assert.AreEqual((double)leftPart, (double)rightPart, 0.0001);
        }
Esempio n. 2
0
        public void BlackScholesPortfolioTest()
        {
            const decimal price           = 20.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           spy                   = Symbols.SPY;
            var           SPY_C_192_Feb19_2016E = GetOptionSymbol(spy, OptionStyle.European, OptionRight.Call);

            // setting up underlying
            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            // setting up European style call option
            var contract   = GetOptionContract(SPY_C_192_Feb19_2016E, spy, evaluationDate);
            var optionCall = GetOption(SPY_C_192_Feb19_2016E, equity, tz);

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });

            // running evaluation
            var priceModel = OptionPriceModels.BlackScholes();
            var results    = priceModel.Evaluate(optionCall, null, contract);
            var callPrice  = results.TheoreticalPrice;
            var greeks     = results.Greeks;

            // BS equation
            var rightPart = greeks.Theta + riskFreeRate * underlyingPrice * greeks.Delta + 0.5m * underlyingVol * underlyingVol * underlyingPrice * underlyingPrice * greeks.Gamma;
            var leftPart  = riskFreeRate * callPrice;

            Assert.AreEqual((double)leftPart, (double)rightPart, 0.0001);
        }
Esempio n. 3
0
        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);

            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");
            }
        }
Esempio n. 5
0
        public void EvaluationDateWorksInPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            var           tz                    = TimeZones.NewYork;
            var           spy                   = Symbols.SPY;
            var           evaluationDate1       = new DateTime(2015, 2, 19);
            var           evaluationDate2       = new DateTime(2015, 2, 20);
            var           SPY_C_192_Feb19_2016E = GetOptionSymbol(spy, OptionStyle.American, OptionRight.Call);

            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            var contract   = GetOptionContract(SPY_C_192_Feb19_2016E, spy, evaluationDate1);
            var optionCall = GetOption(SPY_C_192_Feb19_2016E, equity, tz);

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice1 = results.TheoreticalPrice;

            contract.Time = evaluationDate2;
            results       = priceModel.Evaluate(optionCall, null, contract);

            var callPrice2 = results.TheoreticalPrice;

            Assert.Greater(callPrice1, callPrice2);
        }
        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, 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, 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");
            }
        }
Esempio n. 7
0
        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, 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, 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(2016, 01, 28);
            SetEndDate(2016, 02, 29);
            SetCash(1000000);

            // setting futures
            var futureSP500 = AddFuture(TickerSP500, Resolution.Minute);

            // set our expiry filter for this futures chain
            futureSP500.SetFilter(TimeSpan.FromDays(10), TimeSpan.FromDays(182));

            // setting up options
            var equity = AddEquity(UnderlyingTicker);
            var option = AddOption(UnderlyingTicker);

            equity.SetDataNormalizationMode(DataNormalizationMode.Raw);
            option.PriceModel = OptionPriceModels.BinomialCoxRossRubinstein();
            // option.EnableGreekApproximation = true;
            // set our expiry filter for this option chain
            option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));

            // setting up stock
            AddEquity(TickerMSFT);

            // setting up FX
            AddForex(TickerEURUSD);

            // specifying zero benchmark
            SetBenchmark(date => 0m);
        }
Esempio n. 9
0
        public override void Initialize()
        {
            SetStartDate(2016, 01, 28);
            SetEndDate(2016, 02, 29);
            SetCash(1000000);

            // setting up Microsoft Equity
            _equitySymbol = AddEquity("MSFT").Symbol;

            // setting up EUR/USD FX spot pair
            _forexSymbol = AddForex("EURUSD").Symbol;

            // setting up S&P 500 EMini futures
            var futureSP500 = AddFuture(Futures.Indices.SP500EMini);

            _futureSymbol = futureSP500.Symbol;

            // set our expiry filter for this futures chain
            futureSP500.SetFilter(TimeSpan.FromDays(10), TimeSpan.FromDays(182));

            // setting up Dow Jones ETF Options
            var option = AddOption("DIA");

            _optionSymbol = option.Symbol;

            option.PriceModel = OptionPriceModels.BinomialCoxRossRubinstein();
            // option.EnableGreekApproximation = true;
            // set our expiry filter for this option chain
            option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));

            // specifying zero benchmark
            SetBenchmark(date => 0m);
        }
Esempio n. 10
0
        public void BlackScholesPortfolioTest()
        {
            const decimal price           = 20.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           SPY_C_192_Feb19_2016E = Symbol.CreateOption("SPY", Market.USA, OptionStyle.European, OptionRight.Call, 192m, new DateTime(2016, 02, 19));

            // setting up underlying
            var equity = new Equity(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            // setting up European style option
            var contract = new OptionContract(SPY_C_192_Feb19_2016E, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = new Option(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), SPY_C_192_Feb19_2016E, Resolution.Minute, tz, tz, true, false, false),
                new Cash(Currencies.USD, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });
            optionCall.Underlying = equity;

            // running evaluation
            var priceModel = OptionPriceModels.BlackScholes();
            var results    = priceModel.Evaluate(optionCall, null, contract);
            var callPrice  = results.TheoreticalPrice;
            var greeks     = results.Greeks;

            // BS equation
            var rightPart = greeks.Theta + riskFreeRate * underlyingPrice * greeks.Delta + 0.5m * underlyingVol * underlyingVol * underlyingPrice * underlyingPrice * greeks.Gamma;
            var leftPart  = riskFreeRate * callPrice;

            Assert.AreEqual((double)leftPart, (double)rightPart, 0.0001);
        }
Esempio n. 11
0
        public void CreatesOptionPriceModelByName(string priceEngineName)
        {
            IOptionPriceModel priceModel = null;

            Assert.DoesNotThrow(() =>
            {
                priceModel = OptionPriceModels.Create(priceEngineName, 0.01m);
            });

            Assert.NotNull(priceModel);
            Assert.IsInstanceOf <QLOptionPriceModel>(priceModel);
        }
Esempio n. 12
0
        public override void Initialize()
        {
            SetStartDate(2014, 6, 9);
            SetEndDate(2014, 6, 9);

            var option = AddOption("AAPL", Resolution.Minute);

            // BlackSholes model does not support American style options
            option.PriceModel = OptionPriceModels.BlackScholes();

            SetWarmup(2, Resolution.Daily);

            Init(option, optionStyleIsSupported: false);
        }
Esempio n. 13
0
        public override void Initialize()
        {
            SetStartDate(2014, 6, 9);
            SetEndDate(2014, 6, 9);

            var option = AddOption("AAPL", Resolution.Minute);

            // BaroneAdesiWhaley model supports American style options
            option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();

            SetWarmup(2, Resolution.Daily);

            Init(option, optionStyleIsSupported: true);
        }
        public override void Initialize()
        {
            SetStartDate(2021, 1, 14);
            SetEndDate(2021, 1, 14);

            var option = AddIndexOption("SPX", Resolution.Hour);

            // BaroneAdesiWhaley model does not support European style options
            option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();

            SetWarmup(7, Resolution.Daily);

            Init(option, optionStyleIsSupported: false);
        }
        public override void Initialize()
        {
            // this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
            SetStartDate(2015, 12, 24);
            SetEndDate(2015, 12, 24);
            SetCash(1000000);

            var option = AddOption("GOOG");

            option.PriceModel = OptionPriceModels.CrankNicolsonFD();
            option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));

            SetBenchmark("GOOG");
        }
Esempio n. 16
0
        public override void Initialize()
        {
            SetStartDate(2021, 1, 14);
            SetEndDate(2021, 1, 14);

            var option = AddIndexOption("SPX", Resolution.Hour);

            // BlackScholes model supports European style options
            option.PriceModel = OptionPriceModels.BlackScholes();

            SetWarmup(7, Resolution.Daily);

            Init(option, optionStyleIsSupported: true);
        }
Esempio n. 17
0
        public void PutCallParityTest()
        {
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           SPY_C_192_Feb19_2016E = Symbol.CreateOption("SPY", Market.USA, OptionStyle.European, OptionRight.Call, 192m, new DateTime(2016, 02, 19));
            var           SPY_P_192_Feb19_2016E = Symbol.CreateOption("SPY", Market.USA, OptionStyle.European, OptionRight.Put, 192m, new DateTime(2016, 02, 19));

            // setting up underlying
            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            // setting up European style call option
            var contractCall = new OptionContract(SPY_C_192_Feb19_2016E, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = new Option(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), SPY_C_192_Feb19_2016E, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            optionCall.Underlying = equity;

            // setting up European style put option
            var contractPut = new OptionContract(SPY_P_192_Feb19_2016E, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionPut = new Option(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), SPY_P_192_Feb19_2016E, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            optionPut.Underlying = equity;

            // running evaluation
            var priceModel  = OptionPriceModels.BlackScholes();
            var resultsCall = priceModel.Evaluate(optionCall, null, contractCall);
            var resultsPut  = priceModel.Evaluate(optionPut, null, contractPut);
            var callPrice   = resultsCall.TheoreticalPrice;
            var putPrice    = resultsPut.TheoreticalPrice;

            // Put-call parity equation
            var rightPart = putPrice + underlyingPrice; // no yield
            var leftPart  = callPrice + contractCall.Strike * (decimal)Math.Exp((double)-riskFreeRate);

            Assert.AreEqual((double)leftPart, (double)rightPart, 0.0001);
        }
        public override void Initialize()
        {
            SetStartDate(2014, 06, 9);
            SetEndDate(2014, 06, 15);

            var option = AddOption("AAPL", Resolution.Minute);

            option.SetFilter((universeFilter) =>
            {
                return(universeFilter.IncludeWeeklys().Strikes(-1, 1).Expiration(0, 10));
            });
            option.PriceModel = OptionPriceModels.BaroneAdesiWhaley();
            _optionSymbol     = option.Symbol;

            SetWarmUp(TimeSpan.FromDays(3));
        }
Esempio n. 19
0
        public override void Initialize()
        {
            // this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
            SetStartDate(2015, 12, 24);
            SetEndDate(2015, 12, 24);
            SetCash(1000000);

            var equity = AddEquity(UnderlyingTicker);
            var option = AddOption(UnderlyingTicker);

            equity.SetDataNormalizationMode(DataNormalizationMode.Raw);
            option.PriceModel = OptionPriceModels.CrankNicolsonFD();
            option.SetFilter(-2, +2, TimeSpan.FromDays(00), TimeSpan.FromDays(180));

            SetBenchmark(equity.Symbol);
        }
Esempio n. 20
0
        public void GreekApproximationTest()
        {
            const decimal price           = 20.00m;
            const decimal underlyingPrice = 190m;
            const decimal underlyingVol   = 0.15m;
            var           tz             = TimeZones.NewYork;
            var           evaluationDate = new DateTime(2016, 1, 19);

            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_P_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionPut = new Option(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY_P_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            optionPut.SetMarketPrice(new Tick {
                Value = price
            });
            optionPut.Underlying = equity;

            var priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();

            priceModel.EnableGreekApproximation = false;

            var results = priceModel.Evaluate(optionPut, null, contract);
            var greeks  = results.Greeks;

            Assert.AreEqual(greeks.Theta, 0);
            Assert.AreEqual(greeks.Rho, 0);
            Assert.AreEqual(greeks.Vega, 0);

            priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();
            priceModel.EnableGreekApproximation = true;

            results = priceModel.Evaluate(optionPut, null, contract);
            greeks  = results.Greeks;

            Assert.LessOrEqual(greeks.Theta, 0);
            Assert.AreNotEqual(greeks.Rho, 0);
            Assert.Greater(greeks.Vega, 0);
        }
Esempio n. 21
0
        public void BaroneAdesiWhaleyPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            const decimal riskFreeRate    = 0.01m;
            var           tz             = TimeZones.NewYork;
            var           evaluationDate = new DateTime(2015, 2, 19);

            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_C_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = new Option(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY_C_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });
            optionCall.Underlying = equity;

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice         = results.TheoreticalPrice;
            var impliedVolatility = results.ImpliedVolatility;
            var greeks            = results.Greeks;

            Assert.Greater(price, callPrice);
            Assert.Greater(impliedVolatility, underlyingVol);

            // BS equation (inequality)
            var rightPart = greeks.Theta + riskFreeRate * underlyingPrice * greeks.Delta + 0.5m * underlyingVol * underlyingVol * underlyingPrice * underlyingPrice * greeks.Gamma;
            var leftPart  = riskFreeRate * callPrice;

            Assert.GreaterOrEqual(Math.Round(leftPart, 4), Math.Round(rightPart, 4));
        }
Esempio n. 22
0
        public override void Initialize()
        {
            // this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
            SetStartDate(2015, 12, 24);
            SetEndDate(2015, 12, 24);
            SetCash(1000000);

            var option = AddOption("GOOG");

            // add the initial contract filter
            option.SetFilter(-2, +2, TimeSpan.Zero, TimeSpan.FromDays(180));

            // set the pricing model for Greeks and volatility
            // find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html
            option.PriceModel = OptionPriceModels.CrankNicolsonFD();
            // set the warm-up period for the pricing model
            SetWarmup(TimeSpan.FromDays(4));
            // set the benchmark to be the initial cash
            SetBenchmark(d => 1000000);
        }
Esempio n. 23
0
        public void GreekApproximationTest()
        {
            const decimal price           = 20.00m;
            const decimal underlyingPrice = 190m;
            const decimal underlyingVol   = 0.15m;
            var           tz             = TimeZones.NewYork;
            var           evaluationDate = new DateTime(2016, 1, 19);
            var           spy            = Symbols.SPY;

            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            var contract = GetOptionContract(Symbols.SPY_P_192_Feb19_2016, spy, evaluationDate);

            var optionPut = GetOption(Symbols.SPY_P_192_Feb19_2016, equity, tz);

            optionPut.SetMarketPrice(new Tick {
                Value = price
            });

            var priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();

            priceModel.EnableGreekApproximation = false;

            var results = priceModel.Evaluate(optionPut, null, contract);
            var greeks  = results.Greeks;

            Assert.AreEqual(greeks.Theta, 0);
            Assert.AreEqual(greeks.Rho, 0);
            Assert.AreEqual(greeks.Vega, 0);

            priceModel = (QLOptionPriceModel)OptionPriceModels.CrankNicolsonFD();
            priceModel.EnableGreekApproximation = true;

            results = priceModel.Evaluate(optionPut, null, contract);
            greeks  = results.Greeks;

            Assert.LessOrEqual(greeks.Theta, 0);
            Assert.AreNotEqual(greeks.Rho, 0);
            Assert.Greater(greeks.Vega, 0);
        }
Esempio n. 24
0
        public void EvaluationDateWorksInPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            const decimal riskFreeRate    = 0.01m;
            var           tz = TimeZones.NewYork;
            var           evaluationDate1 = new DateTime(2015, 2, 19);
            var           evaluationDate2 = new DateTime(2015, 2, 20);

            var equity = new Equity(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            equity.SetMarketPrice(new Tick {
                Value = underlyingPrice
            });
            equity.VolatilityModel = new DummyVolatilityModel(underlyingVol);

            var contract = new OptionContract(Symbols.SPY_C_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate1
            };
            var optionCall = new Option(SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY_C_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false), new Cash(CashBook.AccountCurrency, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(CashBook.AccountCurrency)));

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });
            optionCall.Underlying = equity;

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice1 = results.TheoreticalPrice;

            contract.Time = evaluationDate2;
            results       = priceModel.Evaluate(optionCall, null, contract);

            var callPrice2 = results.TheoreticalPrice;

            Assert.Greater(callPrice1, callPrice2);
        }
Esempio n. 25
0
        public void BaroneAdesiWhaleyPortfolioTest()
        {
            const decimal price           = 30.00m;
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.25m;
            const decimal riskFreeRate    = 0.01m;
            var           tz                    = TimeZones.NewYork;
            var           spy                   = Symbols.SPY;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           SPY_C_192_Feb19_2016E = GetOptionSymbol(spy, OptionStyle.American, OptionRight.Call);

            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            var contract = new OptionContract(Symbols.SPY_C_192_Feb19_2016, Symbols.SPY)
            {
                Time = evaluationDate
            };
            var optionCall = GetOption(SPY_C_192_Feb19_2016E, equity, tz);

            optionCall.SetMarketPrice(new Tick {
                Value = price
            });

            var priceModel = OptionPriceModels.BaroneAdesiWhaley();
            var results    = priceModel.Evaluate(optionCall, null, contract);

            var callPrice         = results.TheoreticalPrice;
            var impliedVolatility = results.ImpliedVolatility;
            var greeks            = results.Greeks;

            Assert.Greater(price, callPrice);
            Assert.Greater(impliedVolatility, underlyingVol);

            // BS equation (inequality)
            var rightPart = greeks.Theta + riskFreeRate * underlyingPrice * greeks.Delta + 0.5m * underlyingVol * underlyingVol * underlyingPrice * underlyingPrice * greeks.Gamma;
            var leftPart  = riskFreeRate * callPrice;

            Assert.GreaterOrEqual(Math.Round(leftPart, 4), Math.Round(rightPart, 4));
        }
Esempio n. 26
0
        /// <summary>
        /// Initialize your algorithm and add desired assets.
        /// </summary>
        public override void Initialize()
        {
            //SetStartDate(2013, 11, 1);
            //SetEndDate(2018, 9, 30);

            SetStartDate(2015, 5, 1);
            SetEndDate(2015, 7, 30);
            SetCash(1000000000);

            foreach (string symbol in S_AND_P_500_SYMOLS)
            {
                var option = AddOption(symbol, Resolution.Daily, null, false);
                option.PriceModel = OptionPriceModels.BlackScholes();

                // set our strike/expiry filter for this option chain
                //option.SetFilter((universe) => universe.WeeklysOnly().Expiration(TimeSpan.FromDays(0), TimeSpan.FromDays(7)));
                //option.SetFilter(TimeSpan.FromDays(0), TimeSpan.FromDays(7));

                if (!this.registerForEOD)
                {
                    this.registerForEOD = true;

                    // Schedule an event to fire every trading day for a security
                    // The time rule here tells it to fire 10 minutes before market close
                    Schedule.On(DateRules.EveryDay(option.Symbol), TimeRules.BeforeMarketClose(option.Symbol, 15), () =>
                    {
                        Log("EveryDay 15 min before markets close: Fired at: " + Time);
                        this.LiquidateExpiredOptions();
                    });
                }
            }

            // set the warm-up period for the pricing model
            SetWarmup(TimeSpan.FromDays(15));

            // set the benchmark to be the initial cash
            SetBenchmark((d) => 1000000000);
        }
Esempio n. 27
0
        public static void RandomDataGenerator(
            string startDateString,
            string endDateString,
            string symbolCountString,
            string market,
            string securityTypeString,
            string resolutionString,
            string dataDensityString,
            string includeCoarseString,
            string quoteTradeRatioString,
            string randomSeed,
            string hasIpoPercentageString,
            string hasRenamePercentageString,
            string hasSplitsPercentageString,
            string hasDividendsPercentageString,
            string dividendEveryQuarterPercentageString,
            string optionPriceEngineName,
            string volatilityModelResolutionString,
            string chainSymbolCountString,
            List <string> tickers
            )
        {
            var settings = RandomDataGeneratorSettings.FromCommandLineArguments(
                startDateString,
                endDateString,
                symbolCountString,
                market,
                securityTypeString,
                resolutionString,
                dataDensityString,
                includeCoarseString,
                quoteTradeRatioString,
                randomSeed,
                hasIpoPercentageString,
                hasRenamePercentageString,
                hasSplitsPercentageString,
                hasDividendsPercentageString,
                dividendEveryQuarterPercentageString,
                optionPriceEngineName,
                volatilityModelResolutionString,
                chainSymbolCountString,
                tickers
                );

            if (settings.Start.Year < 1998)
            {
                Log.Error($"RandomDataGeneratorProgram(): Required parameter --start must be at least 19980101");
                Environment.Exit(1);
            }

            var securityManager = new SecurityManager(new TimeKeeper(settings.Start, new[] { TimeZones.Utc }));
            var securityService = new SecurityService(
                new CashBook(),
                MarketHoursDatabase.FromDataFolder(),
                SymbolPropertiesDatabase.FromDataFolder(),
                new SecurityInitializerProvider(new FuncSecurityInitializer(security =>
            {
                // init price
                security.SetMarketPrice(new Tick(settings.Start, security.Symbol, 100, 100));
                security.SetMarketPrice(new OpenInterest(settings.Start, security.Symbol, 10000));

                // from settings
                security.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(settings.VolatilityModelResolution);

                // from settings
                if (security is Option option)
                {
                    option.PriceModel = OptionPriceModels.Create(settings.OptionPriceEngineName, Statistics.PortfolioStatistics.GetRiskFreeRate());
                }
            })),
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCacheProvider(
                    new SecurityPortfolioManager(securityManager, new SecurityTransactionManager(null, securityManager))),
                new MapFilePrimaryExchangeProvider(Composer.Instance.GetExportedValueByTypeName <IMapFileProvider>(Config.Get("map-file-provider", "LocalDiskMapFileProvider")))
                );

            securityManager.SetSecurityService(securityService);

            var generator = new RandomDataGenerator();

            generator.Init(settings, securityManager);
            generator.Run();

            if (settings.IncludeCoarse && settings.SecurityType == SecurityType.Equity)
            {
                Log.Trace("RandomDataGeneratorProgram(): Launching coarse data generator...");

                CoarseUniverseGeneratorProgram.CoarseUniverseGenerator();
            }

            if (!Console.IsInputRedirected)
            {
                Log.Trace("RandomDataGeneratorProgram(): Press any key to exit...");
                Console.ReadKey();
            }
        }