double ComputeGamma(OptionInstrument option, double riskFactor) { var diffDate = (option.ExpirationDate - Data.ParamDate).TotalDays / 365.00; var d1 = (Math.Log(riskFactor / option.Strike) + 0.5 * Math.Pow(Data.Volatility, 2) * diffDate) / (Data.Volatility * Math.Sqrt(diffDate)); return(Math.Exp(-Data.Rate * diffDate) * Tools.NormalDensity(d1) / (riskFactor * Data.Volatility * Math.Sqrt(diffDate))); }
static void Main(string[] args) { DateTime expirationDate = DateTime.Parse("01/05/2019"); DateTime riskFactorDate = DateTime.Parse("01/09/2019"); DateTime paramDate = DateTime.Parse("01/04/2019"); var option = new OptionInstrument(60, expirationDate, OptionType.Put, Way.Sell, Underlying.Petrol, riskFactorDate); Data.InitMarketData(0.25, 0.05, paramDate); var pricingcfg = new PricingConfiguration( new List <GreekType> { GreekType.Delta, GreekType.Gamma, GreekType.Vega, GreekType.Rho, GreekType.Tetha }); var pricer = new Pricer(); var results = pricer.Results(option, pricingcfg); Console.WriteLine("Le prix de l'option :" + results.Mtm); foreach (var result in results.Results) { Console.WriteLine("La valeur de " + result.Key.ToString() + " : " + result.Value); } /*// prcing europeene option * var maturity = DateTime.Parse("01/05/2019"); * var paramDate = DateTime.Parse("01/04/2019"); * var riskFctorDate = DateTime.Parse("01/09/2019"); * var diif = (paramDate-maturity).TotalDays; * var option = new OptionInstrument(60, maturity); * var interpolator = new InterpolatorFuturePrice("CL", riskFctorDate); * var riskFator = interpolator.InterpolationBackStepProcess(); * var optionData = new OptionMarketData(riskFator, paramDate, 0.05, 0.25); * * var pricer = new OptionPricer(option, optionData,"call"); * * * var listGreeks = new List<string>() * { * "Delta", * "Vega", * "Theta", * "Rho", * "Gamma" * }; * * PrintResult print = new PrintResult(pricer,true,true,listGreeks); * print.Print(); */ // InitMarketData // Construction of Product + PricingConfiguration // Call the method Price }
public DataTestCase(List <GreekType> greekTypes, double vol, double rate, OptionInstrument option, DateTime evalDate) { GreekTypes = greekTypes; Vol = vol; Rate = rate; Option = option; EvalDate = evalDate; }
public PricingResults Results(OptionInstrument option, PricingConfiguration pricingcfg) { var blackModel = new BlackModelOption(); double riskfacor = Interpolators.InterpolateForward(option.SousJacent, option.RiskFactorDate); double price = blackModel.PriceBlackModel(option, riskfacor); var resultGreeks = blackModel.ComputeGreeks(pricingcfg.GreeksToCompute, riskfacor, option); return(new PricingResults(resultGreeks, price)); }
private void Button_Click(object sender, RoutedEventArgs e) { GetData(out vol, out strikeValue, out interestRate, out valueDate, out maturityDate, out riskfacorDate); way = (Way)System.Enum.Parse(typeof(Way), Way.SelectedItem.ToString()); optionType = (OptionType)System.Enum.Parse(typeof(OptionType), TypeOption.SelectedItem.ToString()); sousJacent = (Underlying)System.Enum.Parse(typeof(Underlying), sousjacent.SelectedItem.ToString()); var x = MyGreeks.SelectedItems; var z = MyGreeks.SelectedItem; listGreeks = MyGreeks.SelectedItems.Cast <GreekType>().ToList(); Data.InitMarketData(vol, interestRate, valueDate); var option = new OptionInstrument(strikeValue, maturityDate, optionType, way, sousJacent, riskfacorDate); var pricingcfg = new PricingConfiguration(listGreeks); var pricer = new Pricer(); Result.Text = pricer.Results(option, pricingcfg).Mtm.ToString(); var resultGreek = pricer.Results(option, pricingcfg).Results; if (resultGreek.Count != 0) { foreach (var result in resultGreek) { switch (result.Key) { case GreekType.Delta: ValueDelta.Text = result.Value.ToString(""); break; case GreekType.Vega: ValueVega.Text = result.Value.ToString(); break; case GreekType.Gamma: ValueGamma.Text = result.Value.ToString(); break; case GreekType.Rho: ValueRho.Text = result.Value.ToString(); break; case GreekType.Tetha: ValueTetha.Text = result.Value.ToString(); break; } } } }
public Dictionary <GreekType, double> ComputeGreeks(List <GreekType> greekTocompute, double riskFactor, OptionInstrument option) { var results = new Dictionary <GreekType, double>(); foreach (var greek in greekTocompute) { switch (greek) { case GreekType.Delta: results.Add(greek, CompuetDelta(option, riskFactor)); if (option.Sens == Way.Sell) { results[greek] = results[greek] * -1; } break; case GreekType.Vega: results.Add(greek, ComputeVega(option, riskFactor)); if (option.Sens == Way.Sell) { results[greek] = results[greek] * -1; } break; case GreekType.Tetha: results.Add(greek, ComputeTheta(option, riskFactor)); if (option.Sens == Way.Sell) { results[greek] = results[greek] * -1; } break; case GreekType.Rho: results.Add(greek, CompuetDelta(option, riskFactor)); if (option.Sens == Way.Sell) { results[greek] = results[greek] * -1; } break; case GreekType.Gamma: results.Add(greek, ComputeGamma(option, riskFactor)); if (option.Sens == Way.Sell) { results[greek] = results[greek] * -1; } break; } } return(results); }
double CompuetDelta(OptionInstrument option, double riskFacor) { var diffDate = (option.ExpirationDate - Data.ParamDate).TotalDays / 365.00; var d1 = (Math.Log(riskFacor / option.Strike) + 0.5 * Math.Pow(Data.Volatility, 2) * diffDate) / (Data.Volatility * Math.Sqrt(diffDate)); if (option.Type == OptionType.Call) { return(Math.Exp(-Data.Rate * diffDate) * Tools.Phi(d1)); } else { return(Math.Exp(-Data.Rate * diffDate) * (Tools.Phi(d1) - 1)); } }
public void PriceOption() { // le mock de la volatilé, Mock <Volatility> volMock = new Mock <Volatility>(); volMock.Setup(x => x.Vol()).Returns(0.25); // utilsation des linq lambda expression. var maturity = DateTime.Parse("01/5/2019"); var paramDate = DateTime.Now; var option = new OptionInstrument(100, maturity); var optionData = new OptionMarketData(120, paramDate, 0.05, volMock.Object.Vol()); var pricer = new OptionPricer(option, optionData); var prix = 0.0; Assert.AreEqual(prix, 0); }
double ComputeRho(OptionInstrument option, double riskFactor) { var maturity = (option.ExpirationDate - Data.ParamDate).TotalDays / 365.00; var d1 = (Math.Log(riskFactor / option.Strike) + 0.5 * Math.Pow(Data.Volatility, 2) * maturity) / (Data.Volatility * Math.Sqrt(maturity)); var d2 = d1 - Math.Sqrt(maturity); if (option.Type == OptionType.Call) { return(option.Strike * maturity * Tools.Phi(d2)); } else { return(-option.Strike * maturity * Tools.Phi(-d2)); } }
double ComputeTheta(OptionInstrument option, double riskFactor) { var maturity = (option.ExpirationDate - Data.ParamDate).TotalDays / 365.00; var d1 = (Math.Log(riskFactor / option.Strike) + 0.5 * Math.Pow(Data.Volatility, 2) * maturity) / (Data.Volatility * Math.Sqrt(maturity)); var d2 = d1 - Math.Sqrt(maturity); if (option.Type == OptionType.Call) { return(-riskFactor *Math.Exp(-Data.Rate *maturity) * Tools.NormalDensity(d1) * Data.Volatility / (2 * Math.Sqrt(maturity)) + Data.Rate * riskFactor * Math.Exp(-Data.Rate * maturity) * Tools.Phi(d1) - Math.Exp(-Data.Rate * maturity) * Data.Rate * option.Strike * Tools.Phi(d2)); } else { return(-riskFactor *Math.Exp(-Data.Rate *maturity) * Tools.NormalDensity(d1) * Data.Volatility / (2 * Math.Sqrt(maturity)) - Data.Rate * riskFactor * Math.Exp(-Data.Rate * maturity) * Tools.Phi(-d1) + Data.Rate * option.Strike * Math.Exp(-Data.Rate * maturity) * Tools.Phi(-d2)); } }
public double PriceBlackModel(OptionInstrument option, double riskFactor) { var maturity = (option.ExpirationDate - Data.ParamDate).TotalDays / 365.00; var d1 = (Math.Log(riskFactor / option.Strike) + 0.5 * Math.Pow(Data.Volatility, 2) * maturity) / (Data.Volatility * Math.Sqrt(maturity)); var d2 = d1 - Math.Sqrt(maturity); if (option.Type == OptionType.Call) { var x = Math.Exp(-Data.Rate * maturity) * (riskFactor * Tools.Phi(d1) - option.Strike * Tools.Phi(d2)); return(Math.Exp(-Data.Rate * (maturity)) * (riskFactor * Tools.Phi(d1) - option.Strike * Tools.Phi(d2))); } else { return(Math.Exp(-Data.Rate * maturity) * (-riskFactor * Tools.Phi(-d1) + option.Strike * Tools.Phi(-d2))); } }
public static async Task PlaceOrder(string[] args) { Debug.Print(System.Reflection.MethodBase.GetCurrentMethod().Name); var rh = new RobinhoodClient(_token); //Account account = rh.DownloadAllAccounts().Result.First(); //JToken instrumentData = null; //while (instrumentData == null) //{ // try // { // Console.Write("Symbol: "); // rh.DownloadOptionStrikeInstrument(args).Wait(); // instrumentData = rh.results; // MessageBox.Show(instrument.Name); // } // catch (Exception ex) // { // Utils.MessageBoxModal("Problem with initial order.\n\nWill try again 1 second after you hit OK.\n\nIf expiry date is today or wrong, no order will be places, /n/nsince no option instrument can be found "); // System.Threading.Thread.Sleep(1000); // } //} int qty = Convert.ToInt32(args[4]); decimal price = Convert.ToDecimal(args[5]); TimeInForce tif = TimeInForce.GoodTillCancel; //OptionInstrument instrument = new OptionInstrument() //{ // InstrumentUrl = "https://api.robinhood.com/options/instruments/5ac9f2ac-6d01-4d2d-94de-e18ae7602a81/", //new Url<OptionInstrument>(instrumentData.SelectToken("url").ToString()), // Symbol = "c277b118-58d9-4060-8dc5-a3b5898955cb" // // //instrumentData.SelectToken("chain_symbol").ToString() //}; OptionInstrument instrument = new OptionInstrument() { InstrumentUrl = new Url <OptionInstrument>("https://api.robinhood.com/options/instruments/5ac9f2ac-6d01-4d2d-94de-e18ae7602a81/"), //new Url<OptionInstrument>(instrumentData.SelectToken("url").ToString()), Symbol = "c277b118-58d9-4060-8dc5-a3b5898955cb" // //instrumentData.SelectToken("chain_symbol").ToString() }; var newOptionOrderSingle = new NewOptionOrderSingle(instrument); newOptionOrderSingle.AccountUrl = // account.AccountUrl; new Url <Account>("https://api.robinhood.com/accounts/475573473/"); // newOptionOrderSingle.Quantity = Math.Abs(qty); newOptionOrderSingle.Side = qty > 0 ? Side.Buy : Side.Sell; newOptionOrderSingle.TimeInForce = tif; if (price == 0) { newOptionOrderSingle.OrderType = OrderType.Market; } else { newOptionOrderSingle.OrderType = OrderType.Limit; newOptionOrderSingle.Price = price; } _order = rh.PlaceOptionOrder(newOptionOrderSingle).Result; Debug.Print("2:" + DateTime.Now); _resultsLabel = RobinhoodClient._ErrorMessage; // _resultsLabel = rh._ /// update lastMatch.buyAtPrice /// /// await the order response /// /// /// get reversals after /// //bool isPending = order.State != null && order.State == "unconfirmed"; /// does this say pending or is there a better way // /// if the order is pending or the order is partial //if (isPending) //{ // /// cancel the order // rh.CancelOrder(order.CancelUrl).Wait(); // /// get the order status // /// // /// replace the order //} /// if new reversal /// if not partial /// remove order from lstMatch // so a resumption will create a new turn up (this means our reversal stats are not complete) /// set lastMatch to null /// exit stage left /// /// /// else /// if partial /// record the partial order /// reset contracts /// re-order /// else // order was filled /// log the order //using (TradeLogTableAdapter ta = new TradeLogTableAdapter()) //{ // ta.Insert(args[6], Convert.ToDateTime(args[7]), order.jsonText); //} /// /// Analyse the current status /// Is the ask > buyAtPrice /// Is it more than a penny? /// Is the ask now lower than buyAtPrice i.e. the price is falling /// Has there been a reversal? /// Is BuyPrice >= Bid and <= Ask? //if (!String.IsNullOrEmpty(order.ErrorMessage)) // MessageBox.Show(order.ErrorMessage); //else //{ // MessageBox.Show(string.Format("{0}\t{1}\t{2} x {3}\t{4}", // order.Side, // instrument.Symbol, // order.Quantity, // order.Price.HasValue ? order.Price.ToString() : "mkt", // order.State)); //} //if (!String.IsNullOrEmpty(order.RejectReason)) //{ // MessageBox.Show(order.RejectReason); //} //object state = SynchronizationContext.Current; //var context = (SynchronizationContext)state; //state = new object(); //context.Post(RHCockpit.frmBot.WorkerDone, state); }
/// <summary> /// /// </summary> /// <param name="args"> /// args = new string[] { "QQQ", "2019-04-29", "call", "293", "1", "0.01" }; /// </param> private async Task <OrderSnapshot> PlaceOptionOrderAsync(string[] args) { Debug.Print(System.Reflection.MethodBase.GetCurrentMethod().Name); var rh = new RobinhoodClient(_token); Account account = rh.DownloadAllAccounts().Result.First(); JToken instrumentData = null; while (instrumentData == null) { try { // Console.Write("Symbol: "); rh.DownloadOptionStrikeInstrument(args).Wait(); instrumentData = rh.results; //Console.WriteLine(instrument.Name); } catch (Exception ex) { //MessageBox.Show(ex.Message + "\n\nInstrument problem. Try again."); System.Threading.Thread.Sleep(1000); } } int qty = Convert.ToInt32(args[4]); decimal price = Convert.ToDecimal(args[5]); TimeInForce tif = TimeInForce.GoodTillCancel; OptionInstrument instrument = new OptionInstrument() { InstrumentUrl = new Url <OptionInstrument>(instrumentData.SelectToken("url").ToString()), Symbol = instrumentData.SelectToken("chain_symbol").ToString() }; var newOptionOrderSingle = new NewOptionOrderSingle(instrument); newOptionOrderSingle.AccountUrl = account.AccountUrl; newOptionOrderSingle.Quantity = Math.Abs(qty); newOptionOrderSingle.Side = qty > 0 ? Side.Buy : Side.Sell; newOptionOrderSingle.TimeInForce = tif; newOptionOrderSingle.OrderType = OrderType.Limit; newOptionOrderSingle.Price = price; var order = await rh.PlaceOptionOrder(newOptionOrderSingle); //if (!String.IsNullOrEmpty(order.ErrorMessage)) // //MessageBox.Show(order.ErrorMessage); //else // //MessageBox.Show(string.Format("{0}\t{1}\t{2} x {3}\t{4}", // //order.Side, // //instrument.Symbol, // //order.Quantity, // //order.Price.HasValue ? order.Price.ToString() : "mkt", // //order.State)); //if (!String.IsNullOrEmpty(order.RejectReason)) //{ // //MessageBox.Show(order.RejectReason); //} return(order); }