public void TestVolSurface()
        {
            IVolatilitySurface volSurface = new VolatilitySurface("BHP", 4500M, DateTime.Today);
            ForwardExpiry      expiry1    = new ForwardExpiry(DateTime.Parse("01-Jan-2010"), 4200);
            ForwardExpiry      expiry2    = new ForwardExpiry(DateTime.Parse("01-Jan-2011"), 4400);
            OptionPosition     call1      = new OptionPosition("1245", 104, PositionType.Call);
            OptionPosition     put1       = new OptionPosition("1246", 1200, PositionType.Put);
            OptionPosition     call2      = new OptionPosition("1645", 180, PositionType.Call);
            OptionPosition     put2       = new OptionPosition("1646", 1300, PositionType.Put);
            Strike             strike1    = new Strike(4200, call1, put1);
            Strike             strike2    = new Strike(4000, call2, put2);
            IVolatilityPoint   point1     = new VolatilityPoint();

            point1.SetVolatility(0.30M, VolatilityState.Default());
            put1.SetVolatility(point1);
            call1.SetVolatility(point1);
            IVolatilityPoint point2 = new VolatilityPoint();

            point2.SetVolatility(0.40M, VolatilityState.Default());
            call2.SetVolatility(point2);
            put2.SetVolatility(point2);
            expiry1.AddStrike(strike1, true);
            expiry2.AddStrike(strike2, false);
            volSurface.AddExpiry(expiry1);
            volSurface.AddExpiry(expiry2);
            List <ForwardExpiry> forwardExpiries = volSurface.NodalExpiries.ToList();
            int n1 = forwardExpiries[0].Strikes.Count(item => item.NodalPoint);
            // int n2 = forwardExpiries[1].Strikes.Count(delegate(Strike item) { return item.NodalPoint == true; });
            int n2 = 0;

            Assert.AreEqual(1, n1 + n2);
        }
Beispiel #2
0
        public static object LocalVolDenominator(object mktObj, object[] dates, double[] strikes, string assetName)
        {
            return(FunctionRunnerUtils.Run("LocalVolSurface", () =>
            {
                Market market = MarketManager.Instance.GetMarket(mktObj);
                AssetMarket assetMarket = market.AssetMarketFromName(assetName);
                VolatilitySurface volSurface = assetMarket.VolSurface();

                var localVariance = volSurface.LocalVariance;
                var moneyness = volSurface.Moneyness;
                var time = volSurface.Time;

                var result = new double[dates.Length, strikes.Length];
                for (int i = 0; i < dates.Length; i++)
                {
                    var date = ObjectConverters.ConvertDate(dates[i], assetMarket.RefDate);
                    double t = time[date];
                    var denomFunc = localVariance.Denominator(t);
                    var denoms = strikes.Map(k =>
                    {
                        var y = moneyness.Moneyness(t, k);
                        return denomFunc.Eval(y);
                    });
                    ArrayUtils.SetRow(ref result, i, denoms);
                }
                return result;
            }));
        }
Beispiel #3
0
        private static RealInterval GridSupport(double gridQuantile, VolatilitySurface volSurface, double t)
        {
            var impliedVar            = volSurface.VarianceInterpoler.TimeSlice(t) / t;
            Func <double, double> vol = k => Math.Sqrt(impliedVar.Eval(Math.Log(k)));
            var mInf = Math.Log(SmileLawUtils.ComputeQuantile(1.0, t, vol, gridQuantile));
            var mSup = Math.Log(SmileLawUtils.ComputeQuantile(1.0, t, vol, 1.0 - gridQuantile));

            return(RealInterval.Compact(mInf, mSup));
        }
        /// <summary>
        /// Process a PPD Grid. The result is a Market structure that camn be published.
        /// </summary>
        /// <param name="logger">The logger</param>
        /// <param name="cache">The cache.</param>
        /// <param name="swapCurve">The latest rate curve</param>
        /// <param name="ppdGrid">The raw Points Per Day matrix supplied from the subscriber</param>
        /// <param name="id">The id to use in publishing the curve</param>
        /// <param name="nameSpace">The client namespace</param>
        /// <returns></returns>
        public static Market ProcessSwaption(ILogger logger, ICoreCache cache, Market swapCurve, SwaptionPPDGrid ppdGrid, string id, string nameSpace)
        {
            var mkt   = swapCurve;
            var curve = new SimpleRateCurve(mkt);
            // List the values so we can build our ATM vols
            var atmVols = new Dictionary <SimpleKey, decimal>();
            // Create a calendar to use to modify the date
            // default to be Sydney...
            IBusinessCalendar bc = BusinessCenterHelper.ToBusinessCalendar(cache, new[] { "AUSY" }, nameSpace); //BusinessCalendarHelper("AUSY");
            // Use some logic to get the spot date to use
            // LPM Spot lag is 2 days (modfollowing)
            DateTime spotDate = curve.GetSpotDate();

            // Extract each surface and build an ATM engine therefrom
            // Build a list of all possible engines
            foreach (string e in ExpiryKeys)
            {
                // Assume frequency = 4 months until 3 years tenor is reached
                Period expiration         = PeriodHelper.Parse(e);
                double expiryYearFraction = expiration.ToYearFraction();
                foreach (string t in TenorKeys)
                {
                    // Create a Swaprate for each expiry/tenor pair
                    // Assume frequency = 4 months until 3 years tenor is reached
                    double tenorYearFraction = PeriodHelper.Parse(t).ToYearFraction();
                    int    frequency         = tenorYearFraction < 4 ? 4 : 2;
                    // Calculation date
                    // Discount factors
                    // Offsets (elapsed days)
                    var rates = new SwapRate(logger, cache, nameSpace, "AUSY", curve.BaseDate, "ACT/365.FIXED", curve.GetDiscountFactors(), curve.GetDiscountFactorOffsets(), frequency, BusinessDayConventionEnum.MODFOLLOWING);
                    // Calculate the volatility given PPD and swap curve
                    DateTime expiry = bc.Roll(expiration.Add(spotDate), BusinessDayConventionEnum.FOLLOWING);
                    decimal  vol    = CalculateAtmVolatility(rates, expiry, ppdGrid, expiryYearFraction, tenorYearFraction);
                    atmVols.Add(new SimpleKey(e, t), vol);
                }
            }
            var vols = new object[atmVols.Count + 1, 3];
            var i    = 1;

            vols[0, 0] = "Expiry";
            vols[0, 1] = "Tenor";
            vols[0, 2] = "0";
            foreach (var key in atmVols.Keys)
            {
                vols[i, 0] = key.Expiry;
                vols[i, 1] = key.Tenor;
                vols[i, 2] = atmVols[key];
                i++;
            }
            DateTime buildDateTime = swapCurve.Items1[0].buildDateTime;
            var      volSurface    = new VolatilitySurface(vols, new VolatilitySurfaceIdentifier(id), curve.BaseDate, buildDateTime);

            return(CreateMarketDocument(volSurface.GetFpMLData()));
        }
Beispiel #5
0
        public static object LocalVolSurface(object mktObj, object[] dates, double[] strikes, string assetName)
        {
            return(FunctionRunnerUtils.Run("LocalVolSurface", () =>
            {
                Market market = MarketManager.Instance.GetMarket(mktObj);
                AssetMarket assetMarket = market.AssetMarketFromName(assetName);
                VolatilitySurface volSurface = assetMarket.VolSurface();
                var maturities = ObjectConverters.ConvertDateArray(dates, assetMarket.RefDate);

                return ArrayUtils.CartesianProd(maturities, strikes, volSurface.LocalVol);
            }));
        }
        public override IModel Build(LocalVolModelDescription lv, Market market)
        {
            AssetMarket assetMkt = market.AssetMarketFromName(lv.Asset);

            DiscreteLocalDividend[] localDividends = lv.WithDivs
                ? assetMkt.Dividends.Map(div => div.DivModel())
                : new DiscreteLocalDividend[0];

            VolatilitySurface volSurface = VolatilitySurface.BuildInterpol(lv.VolMatrix, assetMkt.Moneyness);

            return(new LocalVolatilityModel(lv.VolMatrix.Time, assetMkt.Asset, volSurface, assetMkt.Moneyness, localDividends));
        }
Beispiel #7
0
        private static Func <double, double> StepLocalVol(DateTime startDate, DateTime endDate, LocalVolatilityModel model)
        {
            var    time  = model.Time;
            double start = time[startDate];
            double end   = time[endDate];

            VolatilitySurface volSurface        = model.VolSurface;
            RrFunction        stepLocalVariance = volSurface.LocalVariance.TimeAveragedSlice(start, end);
            var moneyness = model.Moneyness.Moneyness(start);
            Func <double, double> localVol = logSpot => Math.Sqrt(stepLocalVariance.Eval(moneyness(Math.Exp(logSpot))));

            var gridLocalVol = LocalVolDiscretization(localVol, volSurface, 0.5 * (start + end));

            return(gridLocalVol.Eval);
        }
        /// <summary>
        /// Returns a reference to the minimum proximity contract to lead expiry
        /// (contract expiries are not perfectly aligned) provided the date difference
        /// is within some specified number of days.
        /// </summary>
        /// <param name="fwdExpiry">The FWD expiry.</param>
        /// <param name="volSurface">The vol surface.</param>
        /// <param name="proximityDays">The proximity days.</param>
        /// <returns></returns>
        public static ForwardExpiry FindExpiryClosestTo(ForwardExpiry fwdExpiry, VolatilitySurface volSurface, int proximityDays)
        {
            int           lastProx           = proximityDays;
            ForwardExpiry closestChildExpiry = null;

            foreach (ForwardExpiry childExpiry in volSurface.Expiries)
            {
                int prox = Math.Abs(childExpiry.ExpiryDate.Subtract(fwdExpiry.ExpiryDate).Days);

                if (prox <= proximityDays)
                {
                    lastProx           = prox;
                    closestChildExpiry = childExpiry;
                }
            }
            return(lastProx <= proximityDays ? closestChildExpiry : null);
        }
Beispiel #9
0
        public static Stock CreateStock(EquityVolCalcTestData.Stock stock)
        {
            DateTime today    = XmlGetDate(stock.Date);
            decimal  spot     = Convert.ToDecimal(stock.Spot);
            DateTime baseDate = XmlGetDate(stock.RateCurve.BaseDate);

            DateTime[] rateDates = XmlGetDateArray(stock.RateCurve.DateArray);
            //Load rate curve
            String tp = stock.RateCurve.RateType;
            var    rc = new RateCurve(stock.RateCurve.Ccy, tp, baseDate, rateDates, stock.RateCurve.RateArray);
            // Load dividends
            var divs = (from div in stock.Dividends let exDate = XmlGetDate(div.ExDate) select new Dividend(exDate, Convert.ToDecimal(div.Amount))).ToList();
            //Load stock object
            var stock0 = new Stock(today, spot, stock.AssetId, stock.Name, rc, divs);
            var vol0   = new VolatilitySurface(stock.AssetId, spot, today);

            //Load vols
            stock0.VolatilitySurface = vol0;
            foreach (StockVolatilitySurfaceForwardExpiry exp in stock.VolatilitySurface.Expiries)
            {
                DateTime expDate = XmlGetDate(exp.ExpiryDate);
                Decimal  fwd     = Convert.ToDecimal(exp.FwdPrice);
                var      exp0    = new ForwardExpiry(expDate, fwd);
                // exp0.NodalPoint = System.Convert.ToBoolean(exp.NodalPoint);
                vol0.AddExpiry(exp0);

                foreach (StockVolatilitySurfaceForwardExpiryStrike str in exp.Strikes)
                {
                    var    call         = new OptionPosition();
                    var    put          = new OptionPosition();
                    double strikeprice0 = Convert.ToDouble(str.StrikePrice);
                    var    str0         = new Strike(strikeprice0, call, put, Units.Cents)
                    {
                        Moneyness = Convert.ToDouble(str.Moneyness)
                    };
                    exp0.AddStrike(str0, true);
                    var     vp  = new VolatilityPoint();
                    decimal vol = Convert.ToDecimal(str.Volatility.Value);
                    vp.SetVolatility(vol, VolatilityState.Default());
                    str0.SetVolatility(vp);
                }
            }
            return(stock0);
        }
Beispiel #10
0
        private static VolatilitySurface CreateSurface(Stock stock)
        {
            VolatilitySurface surface = new VolatilitySurface(stock.AssetId, stock.Spot, stock.Date);
            List <DateTime>   dates   = new List <DateTime>
            {
                new DateTime(2009, 9, 16),
                new DateTime(2009, 10, 05),
                new DateTime(2009, 10, 10),
                new DateTime(2009, 11, 9),
                new DateTime(2009, 11, 26),
                new DateTime(2009, 12, 9),
                new DateTime(2010, 3, 10),
                new DateTime(2010, 6, 9),
                new DateTime(2010, 9, 8),
                new DateTime(2011, 3, 12),
                new DateTime(2011, 9, 7),
                new DateTime(2012, 9, 9),
                new DateTime(2013, 9, 9),
                new DateTime(2014, 9, 9),
            };
            IList <double> moneynesses = new List <double> {
                0.5, 0.9, 1, 1.1, 1.5
            };

            foreach (DateTime date in dates)
            {
                var expiry = new ForwardExpiry
                {
                    FwdPrice   = (decimal)stock.GetForward(stock.Date, date),
                    ExpiryDate = date
                };
                foreach (double moneyness in moneynesses)
                {
                    Strike           str = new Strike(Math.Round(Convert.ToDouble(expiry.FwdPrice) * moneyness, 2), null, null, Units.Cents);
                    IVolatilityPoint vp  = new VolatilityPoint();
                    vp.SetVolatility(Convert.ToDecimal(Math.Exp(moneyness) / 3 * 0.32), VolatilityState.Default());
                    str.SetVolatility(vp);
                    expiry.AddStrike(str, true);
                }
                surface.AddExpiry(expiry);
            }
            return(surface);
        }
        private static VolatilitySurface CreateSurface(Stock stock)
        {
            VolatilitySurface surface = new VolatilitySurface(stock.AssetId, stock.Spot, stock.Date);
            List <DateTime>   dates   = new List <DateTime>
            {
                new DateTime(2014, 9, 9),
                new DateTime(2016, 9, 9)
            };
            IList <double> strikes = new List <double> {
                2261,
                2638,
                2827,
                3015,
                3204,
                3298,
                3392,
                3467,
                3543,
                3581,
                3618,
                3694,
                3769,
                3844,
                3920,
                3957,
                3995,
                4071,
                4146,
                4240,
                4334,
                4523,
                4711,
                4900,
                5277,
                5465,
                5654,
                5842,
                6030,
                6219,
                6407,
                6596,
                6784,
                6973,
                7161,
                7350,
                7538
            };

            IList <double> vols1 = new List <double> {
                0.4162,
                0.4094,
                0.4062,
                0.4031,
                0.4,
                0.3985,
                0.3972,
                0.3961,
                0.3949,
                0.3944,
                0.3938,
                0.3925,
                0.3912,
                0.3899,
                0.3886,
                0.388,
                0.3874,
                0.3862,
                0.385,
                0.3835,
                0.382,
                0.3792,
                0.3764,
                0.3738,
                0.3688,
                0.3665,
                0.3643,
                0.3622,
                0.3602,
                0.3584,
                0.3566,
                0.3549,
                0.3533,
                0.3518,
                0.3503,
                0.3489,
                0.3476
            };

            IList <double> vols2 = new List <double> {
                0.4085,
                0.4021,
                0.399,
                0.3961,
                0.3932,
                0.3918,
                0.3906,
                0.3897,
                0.3888,
                0.3883,
                0.3878,
                0.3866,
                0.3853,
                0.384,
                0.3828,
                0.3822,
                0.3816,
                0.3803,
                0.3792,
                0.3777,
                0.3763,
                0.3734,
                0.3707,
                0.3681,
                0.3631,
                0.3608,
                0.3585,
                0.3564,
                0.3544,
                0.3525,
                0.3506,
                0.3489,
                0.3472,
                0.3456,
                0.344,
                0.3425,
                0.3411
            };


            var expiry1 = new ForwardExpiry
            {
                FwdPrice   = (decimal)stock.GetForward(stock.Date, dates[0]),
                ExpiryDate = dates[0]
            };
            var expiry2 = new ForwardExpiry
            {
                FwdPrice   = (decimal)stock.GetForward(stock.Date, dates[1]),
                ExpiryDate = dates[1]
            };

            for (int idx = 0; idx < strikes.Count; idx++)
            {
                Strike           str = new Strike(strikes[idx], null, null, Units.Cents);
                IVolatilityPoint vp  = new VolatilityPoint();
                vp.SetVolatility(Convert.ToDecimal(vols1[idx]), VolatilityState.Default());
                str.SetVolatility(vp);
                expiry1.AddStrike(str, true);
            }
            surface.AddExpiry(expiry1);
            for (int idx = 0; idx < strikes.Count; idx++)
            {
                Strike           str = new Strike(strikes[idx], null, null, Units.Cents);
                IVolatilityPoint vp  = new VolatilityPoint();
                vp.SetVolatility(Convert.ToDecimal(vols2[idx]), VolatilityState.Default());
                str.SetVolatility(vp);
                expiry2.AddStrike(str, true);
            }
            surface.AddExpiry(expiry2);
            return(surface);
        }
Beispiel #12
0
 public static void AssertSensibleValue(VolatilitySurface surface)
 {
     Assert.NotNull(surface);
     AssertSensibleValue(surface.Sigma);
 }
Beispiel #13
0
        static void Main(string[] args)
        {
            //LstSquCubicRegr ls = new LstSquCubicRegr();
            //ls.AddPoints(0.145, -0.1444050245);

            //double a = ls.aTerm;
            //double b = ls.bTerm;
            //double c = ls.cTerm;
            //double d = ls.dTerm;

            //int i = 0;

            string sInput = "";

            if (args.Length == 0)
            {
                Console.WriteLine("Basic:");
                Console.WriteLine("'1' Run the optimal set (data-new).");
                Console.WriteLine("'2' Run the optimal set (data-old).");
                Console.WriteLine("'3' Loop through all systems with standard size.");
                Console.WriteLine("'4' Run a specific system.");
                Console.WriteLine("With genetic optimization:");
                Console.WriteLine("'f' Calculate all PDFs and scenarios only.");
                Console.WriteLine("'a' Get the latest genetically optimal portfolio only.");
                Console.WriteLine("'c' Assess (default) portfolio impact under scenarios.");
                Console.WriteLine("'d' Assess (bestportRM1) portfolio impact under scenarios.");
                Console.WriteLine("'e' Assess (bestportRM2) portfolio impact under scenarios.");
                Console.Write("Choice: ");
                sInput = Console.ReadLine();
            }
            else
            {
                sInput = args[0];
                if (sInput[0] != '1' && sInput[0] != '2' &&
                    sInput[0] != '3' && sInput[0] != '4' &&
                    sInput[0] != 'a' &&
                    sInput[0] != 'c' && sInput[0] != 'd' &&
                    sInput[0] != 'e' && sInput[0] != 'f')
                {
                    Console.WriteLine("Invalid choice.");
                    return;
                }
            }

            if (sInput[0] == '1' || sInput[0] == '2')
            {
                IParam.LoadOptimal();

                RuleBasedDayTradeSys rbdts = new RuleBasedDayTradeSys(IParam.SYSNAME.OPTIMAL,
                                                                      IParam.DetailFilePath, "OM/pnl-OPTIMAL.txt", "OM/mr-OPTIMAL.txt", IParam.HSCIEXHSIFilePath, true);

                RunOptionMedley(rbdts,
                                sInput[0] == '1' ? IParam.DataNewFilePath : IParam.DataOldFilePath);
            }
            else if (sInput[0] == '3')
            {
                foreach (IParam.SYSNAME sn in Enum.GetValues(typeof(IParam.SYSNAME)))
                {
                    IParam.ResetPosSize();
                    IParam.PosSize[(int)sn] = 10000000;

                    RuleBasedDayTradeSys rbdts = new RuleBasedDayTradeSys(sn,
                                                                          IParam.DetailFilePath, "OM/pnl-" + sn.ToString() + ".txt", "OM/mr-" + sn.ToString() + ".txt",
                                                                          IParam.HSCIEXHSIFilePath, false);

                    RunOptionMedley(rbdts, IParam.DataOldFilePath);
                }
            }
            else if (sInput[0] == '4')
            {
                IParam.ResetPosSize();
                IParam.PosSize[17] = 10000000;

                RuleBasedDayTradeSys rbdts = new RuleBasedDayTradeSys(IParam.SYSNAME.OPTIMAL,
                                                                      IParam.DetailFilePath, "OM/pnl-OPTIMAL.txt", "OM/mr-OPTIMAL.txt", IParam.HSCIEXHSIFilePath, true);

                RunOptionMedley(rbdts, IParam.DataOldFilePath);
            }
            else if (sInput[0] == 'f')
            {
                IParam.LoadParamSetA();

                //run basic systems to get delta
                IParam.LoadOptimal();
                RuleBasedDayTradeSys rbdts = new RuleBasedDayTradeSys(IParam.SYSNAME.OPTIMAL,
                                                                      IParam.DetailFilePath, "OM/pnl-OPTIMAL.txt", "OM/mr-OPTIMAL.txt", IParam.HSCIEXHSIFilePath, true);
                RunOptionMedley(rbdts, IParam.DataNewFilePath);

                //generate PDFs
                VolatilitySurface.GenVolSmile_ImplPDF(rbdts);
                rbdts.vs.ReadVolatilitySmileFromFile(true);
                ScenarioProvider sp = new ScenarioProvider();
                sp.GenerateScenarioFile_ScVolSmile(rbdts);
            }
            else if (sInput[0] == 'a')
            {
                IParam.LoadParamSetA();

                bool bLoadBestPortFrmFile = true;
                IParam.RUNMODE = 1;
                string sInput6 = "";
                string sInput7 = "";
                if (args.Length >= 2)
                {
                    sInput6 = args[1];
                    sInput7 = args[2];
                }
                else
                {
                    Console.Write("Load best portfolio");
                    Console.Write(" [Y]/N: ");
                    sInput6 = Console.ReadLine();
                    Console.Write("Genetic Optimization Run Mode [1 = Full Scale / 2 = Adjust MyPort / 3 = Quick Full Scale]");
                    Console.Write(" [1]/2/3: ");
                    sInput7 = Console.ReadLine();
                }
                if (sInput6 != null && sInput6.Length != 0 && sInput6[0] == 'N')
                {
                    bLoadBestPortFrmFile = false;
                }
                if (sInput7 != null && sInput7.Length != 0 && sInput7[0] == '2')
                {
                    IParam.RUNMODE = 2;
                }
                if (sInput7 != null && sInput7.Length != 0 && sInput7[0] == '3')
                {
                    IParam.RUNMODE = 3;
                }
                IParam.GeneticOptimizationRunMode();

                //apply genetic optimization on that result
                ScenarioProvider sp = new ScenarioProvider();
                sp.ReadScenarioFile();
                Genetic            g        = new Genetic();
                PositionController pcMyPort = new PositionController(true);
                pcMyPort.LoadPortfolioFrmFile(IParam.MyPortFilePath);
                g.RunGeneticOptimizationGalaxy(sp, bLoadBestPortFrmFile, pcMyPort);
            }
            else if (sInput[0] == 'c' || sInput[0] == 'd' || sInput[0] == 'e')
            {
                StatHelper sh = new StatHelper(IParam.SCENARIOMAX);
                SortedList sl = new SortedList();

                PositionController pcMyPort = new PositionController(true);
                pcMyPort.LoadPortfolioFrmFile(IParam.MyPortFilePath);

                ScenarioProvider sp = new ScenarioProvider();
                sp.ReadScenarioFile();

                PositionController pc = new PositionController(true);
                pc.SetPathsAndResetFile(IParam.AssessFilePath, IParam.AssessFilePath,
                                        IParam.AssessFilePath, IParam.AssessFilePath, true);

                RandomEngine re = new RandomEngine();

                //load our default portfolio
                IParam.RUNMODE = 1;
                if (sInput[0] == 'd')
                {
                    IParam.RUNMODE = 1;
                }
                else if (sInput[0] == 'e')
                {
                    IParam.RUNMODE = 2;
                }
                IParam.GeneticOptimizationRunMode();

                if (sInput[0] == 'c')
                {
                    pc.LoadPortfolioFrmFile(IParam.DefaultPortFilePath);
                }
                else if (sInput[0] == 'd' || sInput[0] == 'e')
                {
                    pc.LoadPortfolioFrmFile(IParam.BestPortFilePath);
                }


                //we output internal figures to make sure things are calculated right
                pc.vs.VHSILatest = sp.StartingVolatility;
                pc.MarkToMarket(sp.StartingPrice1, sp.StartingPrice2, sp.StartingDate, 0);
                //pc.OutputDetails(sp.StartingDate.ToString());
                //pc.OutputPositionInfoClose(sp.StartingDate, sp.StartingPrice1, sp.StartingPrice2, 3);
                //pc.OutputDetails("---------------------------------------------------------------");
                pc.OutputDetails("KYIERJ7");

                string sBufferredScenarioDetailes = "";

                for (int iSc = 0; iSc < sp.GetNoOfScenario(); iSc++)
                {
                    //reset to starting condition
                    pc.vs.VHSILatest = sp.StartingVolatility;
                    pc.MarkToMarket(sp.StartingPrice1, sp.StartingPrice2, sp.StartingDate, 0);
                    pc.ResetCPnL();
                    pc.PenalizeCPnLPctgFrict(sp.StartingPrice1, sp.StartingPrice2, sp.StartingDate, 1);

                    //load scenario
                    double   dScenarioProbability = 0;
                    DateTime dtScenarioEndingDate = sp.StartingDate; //just set it to sth
                    double   dScenarioPrice1      = 0;
                    double   dScenarioPrice2      = 0;
                    double   dScenarioVolatility  = 0;
                    sp.GetProbEndingDatePriceVolatility(iSc, ref dScenarioProbability, ref dtScenarioEndingDate, ref dScenarioPrice1, ref dScenarioPrice2, ref dScenarioVolatility);

                    //load scenario into PositionController
                    pc.vs.VHSILatest = dScenarioVolatility;
                    pc.MarkToMarket(dScenarioPrice1, dScenarioPrice2, dtScenarioEndingDate, 0);
                    pc.OutputPositionInfoClose(dtScenarioEndingDate, dScenarioPrice1, dScenarioPrice2, 3);
                    pc.PenalizeCPnLPctgFrict(dScenarioPrice1, dScenarioPrice2, dtScenarioEndingDate, 1);


                    //store it for calculation
                    sh.Add(pc.CPnL, (int)(dScenarioProbability * 1000));
                    if (!sl.ContainsKey(pc.CPnL))
                    {
                        sl.Add(pc.CPnL, dScenarioProbability);
                    }
                    else
                    {
                        sl[pc.CPnL] = (double)sl[pc.CPnL] + dScenarioProbability;
                    }

                    //buffer up intermediate results
                    sBufferredScenarioDetailes += "Scenario: " + iSc.ToString() + "\tCPnL: " +
                                                  Math.Round(pc.CPnL, 3).ToString() + "\t" +
                                                  (pc.CPnL == 0 ? "\t" : "") +
                                                  dtScenarioEndingDate.Year.ToString() + "-" +
                                                  dtScenarioEndingDate.Month.ToString() + "-" +
                                                  dtScenarioEndingDate.Day.ToString() + "\t" +
                                                  Math.Round(dScenarioProbability * 100, 1).ToString() + "%\t" +
                                                  Math.Round(dScenarioPrice1, 0).ToString() + "\t" +
                                                  Math.Round(dScenarioPrice2, 0).ToString() + "\t" +
                                                  Math.Round(dScenarioVolatility, 2).ToString() + "\n";
                }

                //output results
                pc.OutputDetails(sBufferredScenarioDetailes);

                pc.OutputDetails("------------------------------------------");
                pc.OutputDetails("Expected Return: " + Math.Round(sh.AMean, 2).ToString());
                string sTmp     = "";
                double dUtility =
                    Math.Round(Genetic.CalcUtilityScore(sh.AMean, sh.SemiVar, sh.SemiVar0,
                                                        //(double)sl.GetKey(0), (double)sl.GetByIndex(0),
                                                        (int)Math.Min(pc.AggCallPos, pc.AggPutPos),
                                                        pc.CompareOptCtrtDiff(pcMyPort),
                                                        true), 5);
                sTmp += "Utility : " + dUtility.ToString();
                sTmp += "\t";
                double dScore =
                    Math.Round(Genetic.CalcUtilityScore(sh.AMean, sh.SemiVar, sh.SemiVar0,
                                                        //(double)sl.GetKey(0), (double)sl.GetByIndex(0),
                                                        (int)Math.Min(pc.AggCallPos, pc.AggPutPos),
                                                        pc.CompareOptCtrtDiff(pcMyPort),
                                                        false), 5);
                sTmp += "Score : " + dScore.ToString();
                pc.OutputDetails(sTmp);

                double dAlpha = Math.Round(Genetic.GetPositionSizeAlpha(sh.X, sh.V), 2);
                pc.OutputDetails("Kelly = " + Math.Round(IParam.HOWMUCHKELLY, 2) +
                                 " , Alpha = " + dAlpha);


                //reset to starting condition and print once
                pc.vs.VHSILatest = sp.StartingVolatility;
                pc.MarkToMarket(sp.StartingPrice1, sp.StartingPrice2, sp.StartingDate, 0);

                pc.OutputDetails("-------------------------------------------------------");
                pc.OutputDetails("Position size (Satellite futures):");
                pc.OutputPositionInfoClose(sp.StartingDate, sp.StartingPrice1, sp.StartingPrice2, 3);
                pc.OutputDetails("Portfolio Delta: " + (Math.Round(pc.GetPortDelta(sp.StartingDate, sp.StartingPrice1, sp.StartingPrice2), 2)).ToString());


                //ok, now we calculate mess up the PositionController to calculate the equivalent regular contract size
                //reset to starting condition
                pc.MultiplyFutPsnSz(sp.StartingPrice1, sp.StartingDate, dAlpha, "ASS");
                pc.MultiplyOptPsnSz(sp.StartingPrice1, sp.StartingDate, dAlpha / 5d, "ASS");
                pc.OutputDetails("-------------------------------------------------------");
                pc.OutputDetails("Position size after multiplying alpha:");
                pc.OutputPositionInfoClose(sp.StartingDate, sp.StartingPrice1, sp.StartingPrice2, 4);


                ExtensionMethods.PrintFileToConsole(IParam.AssessFilePath);
            }
        }
Beispiel #14
0
        private static RegularGridAffineInterpol LocalVolDiscretization(Func <double, double> localVol, VolatilitySurface volSurface, double t)
        {
            const double gridQuantile = 1.0e-6;
            const int    gridSize     = 250;
            RealInterval gridSupport  = GridSupport(gridQuantile, volSurface, t);

            double[] localVolGridValues = GridUtils.RegularGrid(gridSupport, gridSize).Map(localVol);
            var      gridLocalVol       = new RegularGridAffineInterpol(gridSupport, gridSize, localVolGridValues);

            return(gridLocalVol);
        }
 public LocalVolatilityModel(ITimeMeasure time, AssetId asset, VolatilitySurface volSurface, MoneynessProvider moneyness, DiscreteLocalDividend[] dividends)
     : base(asset, dividends, time)
 {
     VolSurface = volSurface;
     Moneyness  = moneyness;
 }
        /// <summary>
        /// Process a CapFloor ATM parvVols structure.
        /// The process Bootstraps the parVols using the supplied ratecurve
        /// </summary>
        /// <param name="logger">The logger</param>
        /// <param name="cache">The cache.</param>
        /// <param name="nameSpace"></param>
        /// <param name="rateCurve"></param>
        /// <param name="capFloor"></param>
        /// <returns></returns>
        private static Market ProcessCapFloorATM(ILogger logger, ICoreCache cache, string nameSpace, Market rateCurve, CapFloorATMMatrix capFloor)
        {
            var id     = capFloor.id;
            var expiry = capFloor.GetExpiries();
            var vols   = capFloor.GetVolatilities();
            var mkt    = rateCurve;
            var curve  = new SimpleRateCurve(mkt);
            var discountFactorDates = curve.GetDiscountFactorDates();
            var discountFactors     = curve.GetDiscountFactors();
            var volType             = capFloor.GetVolatilityTypes();
            var atmVols             = new Dictionary <string, decimal>();
            var settings            = CreateCapFloorProperties(capFloor.GetVolatilitySettings());
            // Create an internal matrix object from the raw data
            var matrix = new CapFloorVolatilityMatrix(id, expiry, volType, vols, null,
                                                      discountFactorDates, ArrayUtilities.ArrayToDecimal(discountFactors));
            // Create an ATM engine from the matrix
            var engines = CreateEngines(logger, cache, nameSpace, id, matrix, settings);
            // Add the default interpolation to use
            const ExpiryInterpolationType volatilityInterpolation = ExpiryInterpolationType.Linear;

            if (engines != null)
            {
                var vol = new CapletExpiryInterpolatedVolatility(engines[0], volatilityInterpolation);
                // List the values so we can build our ATM vols
                var keys = ExpiryKeys.Split(',');
                // Create a calendar to use to modify the date
                var businessCalendar = settings.GetValue("BusinessCalendar", "AUSY");
                var bc = BusinessCenterHelper.ToBusinessCalendar(cache, new[] { businessCalendar }, nameSpace);
                // Use some logic to get the spot date to use
                // LPM Spot lag is 2 days (modfollowing)
                var spotDate       = curve.GetSpotDate();
                var rollConvention = settings.GetValue("RollConvention", BusinessDayConventionEnum.FOLLOWING);
                spotDate = spotDate == curve.GetBaseDate() ? bc.Roll(spotDate.Add(new TimeSpan(2, 0, 0, 0)), rollConvention) : spotDate;
                //// Extract each surface and build an ATM engine therefrom
                //// Build a list of all possible engines
                foreach (var key in keys)
                {
                    // Calculate the volatility for each target key
                    var tv     = PeriodHelper.Parse(key);
                    var target = tv.period == PeriodEnum.D ? bc.Roll(spotDate.AddDays(Convert.ToInt32(tv.periodMultiplier)), rollConvention) :
                                 bc.Roll(spotDate.AddMonths(Convert.ToInt32(tv.periodMultiplier)), rollConvention);
                    atmVols.Add(key, vol.ComputeCapletVolatility(target));
                }
            }
            var outputVols = new object[atmVols.Count + 1, 2];
            var i          = 1;

            //Expiry	0
            outputVols[0, 0] = "Expiry";
            outputVols[0, 1] = "0";
            foreach (var key in atmVols.Keys)
            {
                outputVols[i, 0] = key;
                outputVols[i, 1] = atmVols[key];
                i++;
            }
            DateTime buildDateTime = rateCurve.Items1[0].buildDateTime;
            var      volSurface    = new VolatilitySurface(outputVols, new VolatilitySurfaceIdentifier(id), curve.BaseDate, buildDateTime);

            return(CreateMarketDocument(volSurface.GetFpMLData()));
        }