Esempio n. 1
0
    void Start()
    {
        if(TouchScreenKeyboard.isSupported)
            TouchScreenKeyboard.Open("");

        clothesSettings = Data.Instance.clothesSettings;
        savedSettings = Data.Instance.savedSettings;
        characterManager.SetCloth(clothesSettings.faces, savedSettings.myPlayerSettings.face);
        characterManager.SetCloth(clothesSettings.hairs, savedSettings.myPlayerSettings.hair);
        characterManager.SetCloth(clothesSettings.legs, savedSettings.myPlayerSettings.bottom);
        characterManager.SetCloth(clothesSettings.shoes, savedSettings.myPlayerSettings.shoes);
        characterManager.SetCloth(clothesSettings.tops, savedSettings.myPlayerSettings.body);
        characterManager.SetCloth(clothesSettings.glasses, savedSettings.myPlayerSettings.glasses);
        characterManager.SetColor(savedSettings.myPlayerSettings.color);
    }
Esempio n. 2
0
    void Start()
    {
        Events.OnCustomizerButtonPrevClicked += OnCustomizerButtonPrevClicked;
        Events.OnCustomizerButtonNextClicked += OnCustomizerButtonNextClicked;

        clothesSettings = Data.Instance.clothesSettings;
        savedSettings = Data.Instance.savedSettings;

        savedSettings.CreateRandomPlayer();

        characterManager.SetCloth(clothesSettings.faces, savedSettings.myPlayerSettings.face);
        characterManager.SetCloth(clothesSettings.hairs, savedSettings.myPlayerSettings.hair);
        characterManager.SetCloth(clothesSettings.legs, savedSettings.myPlayerSettings.bottom);
        characterManager.SetCloth(clothesSettings.shoes, savedSettings.myPlayerSettings.shoes);
        characterManager.SetCloth(clothesSettings.tops, savedSettings.myPlayerSettings.body);
        characterManager.SetCloth(clothesSettings.glasses, savedSettings.myPlayerSettings.glasses);
        characterManager.SetColor(savedSettings.myPlayerSettings.color);
    }
Esempio n. 3
0
    void Awake()
    {
        if (!mInstance)
            mInstance = this;
        //otherwise, if we do, kill this thing
        else
        {
            Destroy(this.gameObject);
            return;
        }

        DontDestroyOnLoad(this);
        missionsManager = GetComponent<MissionsManager>();
        texts = GetComponent<Texts>();
        settings = GetComponent<Settings>();
        userData = GetComponent<UserData>();
        clothesSettings = GetComponent<ClothesSettings>();
        savedSettings = GetComponent<SavedSettings>();
    }
Esempio n. 4
0
    void Awake()
    {
        fade = GetComponentInChildren<Fade>();

        fade.gameObject.SetActive(true);
        if (!mInstance)
            mInstance = this;
        //otherwise, if we do, kill this thing
        else
        {
            Destroy(this.gameObject);
            return;
        }

        DontDestroyOnLoad(this.gameObject);

        settings = GetComponent<Settings>();
        savedSettings = GetComponent<SavedSettings>();
        clothesSettings = GetComponent<ClothesSettings>();
    }
Esempio n. 5
0
        public DrawTubeTool(FScene scene)
        {
            this.scene = scene;

            behaviors = new InputBehaviorSet();

            // TODO is this where we should be doing this??
            behaviors.Add(
                new DrawTubeTool_MouseBehavior(scene.Context)
            {
                Priority = 5
            });
            behaviors.Add(
                new DrawTubeTool_SpatialDeviceBehavior(this, scene.Context)
            {
                Priority = 5
            });

            // restore radius
            if (SavedSettings.Restore("DrawTubeTool_radius") != null)
            {
                radius = (float)SavedSettings.Restore("DrawTubeTool_radius");
            }


            indicators = new ToolIndicatorSet(this, scene);
            BrushCursorSphere brushSphere = new BrushCursorSphere()
            {
                PositionF = () => { return(lastPreviewPos.Origin); },
                Radius    = fDimension.Scene(() => { return(Radius); })
            };

            brushSphereMat       = MaterialUtil.CreateTransparentMaterialF(Colorf.CornflowerBlue, 0.2f);
            brushSphere.material = brushSphereMat;
            indicators.AddIndicator(brushSphere);
        }
Esempio n. 6
0
        public DrawCurveTool(FScene scene)
        {
            this.scene = scene;

            behaviors = new InputBehaviorSet();

            // TODO is this where we should be doing this??
            behaviors.Add(
                new DrawCurveTool_2DBehavior(scene.Context)
            {
                Priority = 5
            });
            behaviors.Add(
                new DrawCurveTool_SpatialDeviceBehavior(scene.Context)
            {
                Priority = 5
            });

            // restore radius
            if (SavedSettings.Restore("DrawCurveTool_width") != null)
            {
                width = (float)SavedSettings.Restore("DrawCurveTool_width");
            }
        }
Esempio n. 7
0
        public void testCachedMarketValue()
        {
            // Testing credit-default swap against cached market values...

            using (SavedSettings backup = new SavedSettings())
            {
                Settings.setEvaluationDate(new Date(9, Month.June, 2006));
                Date     evalDate = Settings.evaluationDate();
                Calendar calendar = new UnitedStates();

                List <Date> discountDates = new List <Date>();
                discountDates.Add(evalDate);
                discountDates.Add(calendar.advance(evalDate, 1, TimeUnit.Weeks, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 1, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 2, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 3, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 6, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 12, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 2, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 3, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 4, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 5, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 6, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 7, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 8, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 9, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 10, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                discountDates.Add(calendar.advance(evalDate, 15, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));

                List <double> dfs = new List <double>();
                dfs.Add(1.0);
                dfs.Add(0.9990151375768731);
                dfs.Add(0.99570502636871183);
                dfs.Add(0.99118260474528685);
                dfs.Add(0.98661167950906203);
                dfs.Add(0.9732592953359388);
                dfs.Add(0.94724424481038083);
                dfs.Add(0.89844996737120875);
                dfs.Add(0.85216647839921411);
                dfs.Add(0.80775477692556874);
                dfs.Add(0.76517289234200347);
                dfs.Add(0.72401019553182933);
                dfs.Add(0.68503909569219212);
                dfs.Add(0.64797499814013748);
                dfs.Add(0.61263171936255534);
                dfs.Add(0.5791942350748791);
                dfs.Add(0.43518868769953606);

                DayCounter curveDayCounter = new Actual360();

                RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new InterpolatedDiscountCurve <LogLinear>(discountDates, dfs, curveDayCounter, null, null, null, new LogLinear()));

                DayCounter  dayCounter = new Thirty360();
                List <Date> dates      = new List <Date>();
                dates.Add(evalDate);
                dates.Add(calendar.advance(evalDate, 6, TimeUnit.Months, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 1, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 2, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 3, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 4, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 5, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 7, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));
                dates.Add(calendar.advance(evalDate, 10, TimeUnit.Years, BusinessDayConvention.ModifiedFollowing));

                List <double> defaultProbabilities = new List <double>();
                defaultProbabilities.Add(0.0000);
                defaultProbabilities.Add(0.0047);
                defaultProbabilities.Add(0.0093);
                defaultProbabilities.Add(0.0286);
                defaultProbabilities.Add(0.0619);
                defaultProbabilities.Add(0.0953);
                defaultProbabilities.Add(0.1508);
                defaultProbabilities.Add(0.2288);
                defaultProbabilities.Add(0.3666);

                List <double> hazardRates = new List <double>();
                hazardRates.Add(0.0);
                for (int i = 1; i < dates.Count; ++i)
                {
                    double t1 = dayCounter.yearFraction(dates[0], dates[i - 1]);
                    double t2 = dayCounter.yearFraction(dates[0], dates[i]);
                    double S1 = 1.0 - defaultProbabilities[i - 1];
                    double S2 = 1.0 - defaultProbabilities[i];
                    hazardRates.Add(Math.Log(S1 / S2) / (t2 - t1));
                }

                RelinkableHandle <DefaultProbabilityTermStructure> piecewiseFlatHazardRate = new RelinkableHandle <DefaultProbabilityTermStructure>();
                piecewiseFlatHazardRate.linkTo(new InterpolatedHazardRateCurve <BackwardFlat>(dates, hazardRates, new Thirty360()));

                // Testing credit default swap

                // Build the schedule
                Date                  issueDate     = new Date(20, Month.March, 2006);
                Date                  maturity      = new Date(20, Month.June, 2013);
                Frequency             cdsFrequency  = Frequency.Semiannual;
                BusinessDayConvention cdsConvention = BusinessDayConvention.ModifiedFollowing;

                Schedule schedule = new Schedule(issueDate, maturity, new Period(cdsFrequency), calendar,
                                                 cdsConvention, cdsConvention,
                                                 DateGeneration.Rule.Forward, false);

                // Build the CDS
                double     recoveryRate = 0.25;
                double     fixedRate    = 0.0224;
                DayCounter dayCount     = new Actual360();
                double     cdsNotional  = 100.0;

                CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, cdsNotional, fixedRate,
                                                              schedule, cdsConvention, dayCount, true, true);
                cds.setPricingEngine(new MidPointCdsEngine(piecewiseFlatHazardRate, recoveryRate, discountCurve));

                double calculatedNpv      = cds.NPV();
                double calculatedFairRate = cds.fairSpread();

                double npv      = -1.364048777; // from Bloomberg we have 98.15598868 - 100.00;
                double fairRate = 0.0248429452; // from Bloomberg we have 0.0258378;

                double tolerance = 1e-9;

                if (Math.Abs(npv - calculatedNpv) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce the npv for the given credit-default swap\n"
                        + "    computed NPV:  " + calculatedNpv + "\n"
                        + "    Given NPV:     " + npv);
                }

                if (Math.Abs(fairRate - calculatedFairRate) > tolerance)
                {
                    Assert.Fail("Failed to reproduce the fair rate for the given credit-default swap\n"
                                + "    computed fair rate:  " + calculatedFairRate + "\n"
                                + "    Given fair rate:     " + fairRate);
                }
            }
        }
Esempio n. 8
0
        public void testVannaVolgaDoubleBarrierValues()
        {
            // Testing double-barrier FX options against Vanna/Volga values
            SavedSettings backup = new SavedSettings();

            DoubleBarrierFxOptionData[] values =
            {
                //                             BarrierType,                    barr.1, barr.2, rebate,         type,    strike,          s,         q,         r,  t, vol25Put,    volAtm,vol25Call,      vol,    result,   tol
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Call, 1.13321, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.11638, 0.14413, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Call, 1.22687, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.10088, 0.07456, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Call, 1.31179, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08925, 0.02710, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Call, 1.38843, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08463, 0.00569, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Call, 1.46047, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08412, 0.00013, 1.0e-4),

                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Put,  1.13321, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.11638, 0.00017, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Put,  1.22687, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.10088, 0.00353, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Put,  1.31179, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08925, 0.02221, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Put,  1.38843, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08463, 0.06049, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.1, 1.5, 0.0, Option.Type.Put,  1.46047, 1.30265, 0.0003541, 0.0033871, 1.0, 0.10087, 0.08925, 0.08463, 0.08412, 0.11103, 1.0e-4),

                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Call, 1.06145, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.12511, 0.19981, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Call, 1.19545, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.10890, 0.10389, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Call, 1.32238, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09444, 0.03555, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Call, 1.44298, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09197, 0.00634, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Call, 1.56345, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09261, 0.00000, 1.0e-4),

                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Put,  1.06145, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.12511, 0.00000, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Put,  1.19545, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.10890, 0.00436, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Put,  1.32238, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09444, 0.03173, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Put,  1.44298, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09197, 0.09346, 1.0e-4),
                new DoubleBarrierFxOptionData(DoubleBarrier.Type.KnockOut, 1.0, 1.6, 0.0, Option.Type.Put,  1.56345, 1.30265, 0.0009418, 0.0039788, 2.0, 0.10891, 0.09525, 0.09197, 0.09261, 0.17704, 1.0e-4),
            };

            DayCounter dc    = new Actual360();
            Date       today = new Date(05, Month.Mar, 2013);

            Settings.setEvaluationDate(today);

            SimpleQuote        spot      = new SimpleQuote(0.0);
            SimpleQuote        qRate     = new SimpleQuote(0.0);
            YieldTermStructure qTS       = Utilities.flatRate(today, qRate, dc);
            SimpleQuote        rRate     = new SimpleQuote(0.0);
            YieldTermStructure rTS       = Utilities.flatRate(today, rRate, dc);
            SimpleQuote        vol25Put  = new SimpleQuote(0.0);
            SimpleQuote        volAtm    = new SimpleQuote(0.0);
            SimpleQuote        vol25Call = new SimpleQuote(0.0);

            for (int i = 0; i < values.Length; i++)
            {
                for (int j = 0; j <= 1; j++)
                {
                    DoubleBarrier.Type barrierType = (DoubleBarrier.Type)j;
                    spot.setValue(values[i].s);
                    qRate.setValue(values[i].q);
                    rRate.setValue(values[i].r);
                    vol25Put.setValue(values[i].vol25Put);
                    volAtm.setValue(values[i].volAtm);
                    vol25Call.setValue(values[i].vol25Call);

                    StrikedTypePayoff payoff = new PlainVanillaPayoff(values[i].type, values[i].strike);

                    Date     exDate   = today + (int)(values[i].t * 365 + 0.5);
                    Exercise exercise = new EuropeanExercise(exDate);

                    Handle <DeltaVolQuote> volAtmQuote = new Handle <DeltaVolQuote>(
                        new DeltaVolQuote(new Handle <Quote>(volAtm), DeltaVolQuote.DeltaType.Fwd, values[i].t,
                                          DeltaVolQuote.AtmType.AtmDeltaNeutral));

                    //always delta neutral atm
                    Handle <DeltaVolQuote> vol25PutQuote = new Handle <DeltaVolQuote>(new DeltaVolQuote(-0.25,
                                                                                                        new Handle <Quote>(vol25Put), values[i].t, DeltaVolQuote.DeltaType.Fwd));

                    Handle <DeltaVolQuote> vol25CallQuote = new Handle <DeltaVolQuote>(new DeltaVolQuote(0.25,
                                                                                                         new Handle <Quote>(vol25Call), values[i].t, DeltaVolQuote.DeltaType.Fwd));

                    DoubleBarrierOption doubleBarrierOption = new DoubleBarrierOption(barrierType,
                                                                                      values[i].barrier1, values[i].barrier2, values[i].rebate, payoff, exercise);

                    double bsVanillaPrice = Utils.blackFormula(values[i].type, values[i].strike,
                                                               spot.value() * qTS.discount(values[i].t) / rTS.discount(values[i].t),
                                                               values[i].v * Math.Sqrt(values[i].t), rTS.discount(values[i].t));

                    IPricingEngine vannaVolgaEngine;

                    vannaVolgaEngine = new VannaVolgaDoubleBarrierEngine(volAtmQuote, vol25PutQuote, vol25CallQuote,
                                                                         new Handle <Quote>(spot),
                                                                         new Handle <YieldTermStructure>(rTS),
                                                                         new Handle <YieldTermStructure>(qTS),
                                                                         (process, series) => new WulinYongDoubleBarrierEngine(process, series),
                                                                         true,
                                                                         bsVanillaPrice);
                    doubleBarrierOption.setPricingEngine(vannaVolgaEngine);

                    double expected = 0;
                    if (barrierType == DoubleBarrier.Type.KnockOut)
                    {
                        expected = values[i].result;
                    }
                    else if (barrierType == DoubleBarrier.Type.KnockIn)
                    {
                        expected = (bsVanillaPrice - values[i].result);
                    }

                    double calculated = doubleBarrierOption.NPV();
                    double error      = Math.Abs(calculated - expected);
                    if (error > values[i].tol)
                    {
                        REPORT_FAILURE_VANNAVOLGA("value", values[i].barrierType,
                                                  values[i].barrier1, values[i].barrier2,
                                                  values[i].rebate, payoff, exercise, values[i].s,
                                                  values[i].q, values[i].r, today, values[i].vol25Put,
                                                  values[i].volAtm, values[i].vol25Call, values[i].v,
                                                  expected, calculated, error, values[i].tol);
                    }

                    vannaVolgaEngine = new VannaVolgaDoubleBarrierEngine(volAtmQuote, vol25PutQuote, vol25CallQuote,
                                                                         new Handle <Quote>(spot),
                                                                         new Handle <YieldTermStructure>(rTS),
                                                                         new Handle <YieldTermStructure>(qTS),
                                                                         (process, series) => new AnalyticDoubleBarrierEngine(process, series),
                                                                         true,
                                                                         bsVanillaPrice);
                    doubleBarrierOption.setPricingEngine(vannaVolgaEngine);

                    calculated = doubleBarrierOption.NPV();
                    error      = Math.Abs(calculated - expected);
                    double maxtol = 5.0e-3; // different engines have somewhat different results
                    if (error > maxtol)
                    {
                        REPORT_FAILURE_VANNAVOLGA("value", values[i].barrierType,
                                                  values[i].barrier1, values[i].barrier2,
                                                  values[i].rebate, payoff, exercise, values[i].s,
                                                  values[i].q, values[i].r, today, values[i].vol25Put,
                                                  values[i].volAtm, values[i].vol25Call, values[i].v,
                                                  expected, calculated, error, values[i].tol);
                    }
                }
            }
        }
Esempio n. 9
0
        public void testCashAtHitOrNothingAmericanGreeks()
        {
            // Testing American cash-(at-hit)-or-nothing digital option greeks

            SavedSettings backup = new SavedSettings();

            SortedDictionary <string, double> calculated = new SortedDictionary <string, double>();
            SortedDictionary <string, double> expected   = new SortedDictionary <string, double>();
            SortedDictionary <string, double> tolerance  = new SortedDictionary <string, double>(); // std::map<std::string,Real> calculated, expected, tolerance;

            tolerance["delta"] = 5.0e-5;
            tolerance["gamma"] = 5.0e-5;
            tolerance["rho"]   = 5.0e-5;

            Option.Type[] types      = { QLNet.Option.Type.Call, QLNet.Option.Type.Put };
            double[]      strikes    = { 50.0, 99.5, 100.5, 150.0 };
            double        cashPayoff = 100.0;

            double[] underlyings = { 100 };
            double[] qRates      = { 0.04, 0.05, 0.06 };
            double[] rRates      = { 0.01, 0.05, 0.15 };
            double[] vols        = { 0.11, 0.5, 1.2 };

            DayCounter dc    = new Actual360();
            Date       today = Date.Today;

            Settings.setEvaluationDate(today);

            SimpleQuote spot  = new SimpleQuote(0.0);
            SimpleQuote qRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> qTS = new Handle <YieldTermStructure>(Utilities.flatRate(qRate, dc));
            SimpleQuote rRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> rTS = new Handle <YieldTermStructure>(Utilities.flatRate(rRate, dc));
            SimpleQuote vol = new SimpleQuote(0.0);
            Handle <BlackVolTermStructure> volTS = new Handle <BlackVolTermStructure>(Utilities.flatVol(vol, dc));

            // there is no cycling on different residual times
            Date     exDate     = today + 360;
            Exercise exercise   = new EuropeanExercise(exDate);
            Exercise amExercise = new AmericanExercise(today, exDate, false);

            Exercise[] exercises = { exercise, amExercise };

            BlackScholesMertonProcess stochProcess = new BlackScholesMertonProcess(new Handle <Quote>(spot), qTS, rTS, volTS);

            IPricingEngine euroEngine = new AnalyticEuropeanEngine(stochProcess);

            IPricingEngine amEngine = new AnalyticDigitalAmericanEngine(stochProcess);

            IPricingEngine[] engines = { euroEngine, amEngine };

            bool knockin = true;

            for (int j = 0; j < engines.Length; j++)
            {
                for (int i1 = 0; i1 < types.Length; i1++)
                {
                    for (int i6 = 0; i6 < strikes.Length; i6++)
                    {
                        StrikedTypePayoff payoff = new CashOrNothingPayoff(types[i1], strikes[i6], cashPayoff);

                        VanillaOption opt = new VanillaOption(payoff, exercises[j]);
                        opt.setPricingEngine(engines[j]);

                        for (int i2 = 0; i2 < underlyings.Length; i2++)
                        {
                            for (int i4 = 0; i4 < qRates.Length; i4++)
                            {
                                for (int i3 = 0; i3 < rRates.Length; i3++)
                                {
                                    for (int i7 = 0; i7 < vols.Length; i7++)
                                    {
                                        // test data
                                        double u = underlyings[i2];
                                        double q = qRates[i4];
                                        double r = rRates[i3];
                                        double v = vols[i7];
                                        spot.setValue(u);
                                        qRate.setValue(q);
                                        rRate.setValue(r);
                                        vol.setValue(v);

                                        // theta, dividend rho and vega are not available for
                                        // digital option with american exercise. Greeks of
                                        // digital options with european payoff are tested
                                        // in the europeanoption.cpp test
                                        double value = opt.NPV();
                                        calculated["delta"] = opt.delta();
                                        calculated["gamma"] = opt.gamma();
                                        calculated["rho"]   = opt.rho();

                                        if (value > 1.0e-6)
                                        {
                                            // perturb spot and get delta and gamma
                                            double du = u * 1.0e-4;
                                            spot.setValue(u + du);
                                            double value_p = opt.NPV(),
                                                   delta_p = opt.delta();
                                            spot.setValue(u - du);
                                            double value_m = opt.NPV(),
                                                   delta_m = opt.delta();
                                            spot.setValue(u);
                                            expected["delta"] = (value_p - value_m) / (2 * du);
                                            expected["gamma"] = (delta_p - delta_m) / (2 * du);

                                            // perturb rates and get rho and dividend rho
                                            double dr = r * 1.0e-4;
                                            rRate.setValue(r + dr);
                                            value_p = opt.NPV();
                                            rRate.setValue(r - dr);
                                            value_m = opt.NPV();
                                            rRate.setValue(r);
                                            expected["rho"] = (value_p - value_m) / (2 * dr);

                                            // check
                                            //std::map<std::string,Real>::iterator it;
                                            foreach (var it in calculated)
                                            {
                                                string greek = it.Key;
                                                double expct = expected  [greek],
                                                       calcl = calculated[greek],
                                                       tol   = tolerance [greek];
                                                double error = Utilities.relativeError(expct, calcl, value);
                                                if (error > tol)
                                                {
                                                    REPORT_FAILURE(greek, payoff, exercise,
                                                                   u, q, r, today, v,
                                                                   expct, calcl, error, tol, knockin);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        public void testAtmCalcs()
        {
            // Testing delta-neutral ATM quotations
            SavedSettings backup = new SavedSettings();

            DeltaData[] values =
            {
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Spot,     1.421,  0.997306,  0.992266,  0.1180654, 1.608080,   0.15),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.PaSpot,   1.421,  0.997306,  0.992266,  0.1180654, 1.600545,   0.15),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Fwd,      1.421,  0.997306,  0.992266,  0.1180654, 1.609029,   0.15),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.PaFwd,    1.421,  0.997306,  0.992266,  0.1180654, 1.601550,   0.15),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Spot,   122.121, 0.9695434, 0.9872347,  0.0887676, 119.8031,   0.67),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.PaSpot, 122.121, 0.9695434, 0.9872347,  0.0887676, 117.7096,   0.67),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Fwd,    122.121, 0.9695434, 0.9872347,  0.0887676, 120.0592,   0.67),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.PaFwd,  122.121, 0.9695434, 0.9872347,  0.0887676, 118.0532,   0.67),
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.Spot,    3.4582,   0.99979, 0.9250616,  0.3199034, 4.964924, -0.821),
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.PaSpot,  3.4582,   0.99979, 0.9250616,  0.3199034, 3.778327, -0.821),
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.Fwd,     3.4582,   0.99979, 0.9250616,  0.3199034,  4.51896, -0.821),
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.PaFwd,   3.4582,   0.99979, 0.9250616,  0.3199034,  3.65728, -0.821),
                // Data taken from Castagnas "FX Options and Smile Risk" (Wiley 2009)
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.Spot,    103.00,   0.99482,   0.98508, 0.07247845,    97.47,  -0.25),
                new DeltaData(Option.Type.Put,  DeltaVolQuote.DeltaType.PaSpot,  103.00,   0.99482,   0.98508, 0.07247845,    97.22,  -0.25),
                // Extreme case: zero vol, ATM Fwd strike
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Fwd,     103.00,   0.99482,   0.98508,        0.0, 101.0013,    0.5),
                new DeltaData(Option.Type.Call, DeltaVolQuote.DeltaType.Spot,    103.00,   0.99482,   0.98508,        0.0, 101.0013, 0.99482 * 0.5)
            };

            DeltaVolQuote.DeltaType currDt;
            double currSpot;
            double currdDf;
            double currfDf;
            double currStdDev;
            double expected;
            double calculated;
            double error;
            double tolerance = 1.0e-2; // not that small, but sufficient for strikes
            double currAtmStrike;
            double currCallDelta;
            double currPutDelta;
            double currFwd;

            for (int i = 0; i < values.Length; i++)
            {
                currDt     = values[i].dt;
                currSpot   = values[i].spot;
                currdDf    = values[i].dDf;
                currfDf    = values[i].fDf;
                currStdDev = values[i].stdDev;
                currFwd    = currSpot * currfDf / currdDf;

                BlackDeltaCalculator myCalc = new BlackDeltaCalculator(Option.Type.Call, currDt, currSpot, currdDf,
                                                                       currfDf, currStdDev);

                currAtmStrike = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmDeltaNeutral);
                currCallDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Put);
                currPutDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Call);

                expected   = 0.0;
                calculated = currCallDelta + currPutDelta;
                error      = Math.Abs(calculated - expected);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Delta neutrality failed for spot delta in Delta Calculator. \n"
                                 + "Iteration: " + i + "\n"
                                 + "Calculated Delta Sum: " + calculated + "\n"
                                 + "Expected Delta Sum:   " + expected + "\n"
                                 + "Error: " + error);
                }

                myCalc.setDeltaType(DeltaVolQuote.DeltaType.Fwd);
                currAtmStrike = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmDeltaNeutral);
                currCallDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Put);
                currPutDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Call);

                expected   = 0.0;
                calculated = currCallDelta + currPutDelta;
                error      = Math.Abs(calculated - expected);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Delta neutrality failed for forward delta in Delta Calculator. \n"
                                 + "Iteration: " + i + "\n"
                                 + "Calculated Delta Sum: " + calculated + "\n"
                                 + "Expected Delta Sum:   " + expected + "\n"
                                 + "Error: " + error);
                }

                myCalc.setDeltaType(DeltaVolQuote.DeltaType.PaSpot);
                currAtmStrike = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmDeltaNeutral);
                currCallDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Put);
                currPutDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Call);

                expected   = 0.0;
                calculated = currCallDelta + currPutDelta;
                error      = Math.Abs(calculated - expected);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Delta neutrality failed for premium-adjusted spot delta in Delta Calculator. \n"
                                 + "Iteration: " + i + "\n"
                                 + "Calculated Delta Sum: " + calculated + "\n"
                                 + "Expected Delta Sum:   " + expected + "\n"
                                 + "Error: " + error);
                }


                myCalc.setDeltaType(DeltaVolQuote.DeltaType.PaFwd);
                currAtmStrike = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmDeltaNeutral);
                currCallDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Put);
                currPutDelta = myCalc.deltaFromStrike(currAtmStrike);
                myCalc.setOptionType(Option.Type.Call);

                expected   = 0.0;
                calculated = currCallDelta + currPutDelta;
                error      = Math.Abs(calculated - expected);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Delta neutrality failed for premium-adjusted forward delta in Delta Calculator. \n"
                                 + "Iteration: " + i + "\n"
                                 + "Calculated Delta Sum: " + calculated + "\n"
                                 + "Expected Delta Sum:   " + expected + "\n"
                                 + "Error: " + error);
                }

                // Test ATM forward Calculations
                calculated = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmFwd);
                expected   = currFwd;
                error      = Math.Abs(expected - calculated);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Atm forward test failed. \n"
                                 + "Calculated Value: " + calculated + "\n"
                                 + "Expected   Value: " + expected + "\n"
                                 + "Error: " + error);
                }

                // Test ATM 0.50 delta calculations
                myCalc.setDeltaType(DeltaVolQuote.DeltaType.Fwd);
                double atmFiftyStrike = myCalc.atmStrike(DeltaVolQuote.AtmType.AtmPutCall50);
                calculated = Math.Abs(myCalc.deltaFromStrike(atmFiftyStrike));
                expected   = 0.50;
                error      = Math.Abs(expected - calculated);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Atm 0.50 delta strike test failed. \n"
                                 + "Iteration:" + i + "\n"
                                 + "Calculated Value: " + calculated + "\n"
                                 + "Expected   Value: " + expected + "\n"
                                 + "Error: " + error);
                }
            }
        }
Esempio n. 11
0
        public void testDeltaPriceConsistency()
        {
            // Testing premium-adjusted delta price consistency

            // This function tests for price consistencies with the standard
            // Black Scholes calculator, since premium adjusted deltas can be calculated
            // from spot deltas by adding/subtracting the premium.

            SavedSettings backup = new SavedSettings();

            // actually, value and tol won't be needed for testing
            EuropeanOptionData[] values =
            {
                //        type, strike,   spot,    rd,    rf,    t,  vol,   value,    tol
                new EuropeanOptionData(Option.Type.Call, 0.9123, 1.2212, 0.0231, 0.0000, 0.25, 0.301, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 0.9234, 1.2212, 0.0231, 0.0000, 0.35, 0.111, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 0.9783, 1.2212, 0.0231, 0.0000, 0.45, 0.071, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.0000, 1.2212, 0.0231, 0.0000, 0.55, 0.082, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.1230, 1.2212, 0.0231, 0.0000, 0.65, 0.012, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.2212, 1.2212, 0.0231, 0.0000, 0.75, 0.129, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.3212, 1.2212, 0.0231, 0.0000, 0.85, 0.034, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.3923, 1.2212, 0.0131, 0.2344, 0.95, 0.001, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Call, 1.3455, 1.2212, 0.0000, 0.0000, 1.00, 0.127, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  0.9123, 1.2212, 0.0231, 0.0000, 0.25, 0.301, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  0.9234, 1.2212, 0.0231, 0.0000, 0.35, 0.111, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  0.9783, 1.2212, 0.0231, 0.0000, 0.45, 0.071, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.0000, 1.2212, 0.0231, 0.0000, 0.55, 0.082, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.1230, 1.2212, 0.0231, 0.0000, 0.65, 0.012, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.2212, 1.2212, 0.0231, 0.0000, 0.75, 0.129, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.3212, 1.2212, 0.0231, 0.0000, 0.85, 0.034, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.3923, 1.2212, 0.0131, 0.2344, 0.95, 0.001, 0.0, 0.0),
                new EuropeanOptionData(Option.Type.Put,  1.3455, 1.2212, 0.0000, 0.0000, 1.00, 0.127, 0.0, 0.0),
                // extreme case: zero vol
                new EuropeanOptionData(Option.Type.Put,  1.3455, 1.2212, 0.0000, 0.0000, 0.50, 0.000, 0.0, 0.0),
                // extreme case: zero strike
                new EuropeanOptionData(Option.Type.Put,  0.0000, 1.2212, 0.0000, 0.0000, 1.50, 0.133, 0.0, 0.0),
                // extreme case: zero strike+zero vol
                new EuropeanOptionData(Option.Type.Put,  0.0000, 1.2212, 0.0000, 0.0000, 1.00, 0.133, 0.0, 0.0),
            };

            DayCounter dc       = new Actual360();
            Calendar   calendar = new TARGET();
            Date       today    = Date.Today;

            // Start setup of market data

            double discFor       = 0.0;
            double discDom       = 0.0;
            double implVol       = 0.0;
            double expectedVal   = 0.0;
            double calculatedVal = 0.0;
            double error         = 0.0;

            SimpleQuote    spotQuote  = new SimpleQuote(0.0);
            Handle <Quote> spotHandle = new Handle <Quote>(spotQuote);

            SimpleQuote        qQuote  = new SimpleQuote(0.0);
            Handle <Quote>     qHandle = new Handle <Quote>(qQuote);
            YieldTermStructure qTS     = new FlatForward(today, qHandle, dc);

            SimpleQuote        rQuote  = new SimpleQuote(0.0);
            Handle <Quote>     rHandle = new Handle <Quote>(qQuote);
            YieldTermStructure rTS     = new FlatForward(today, rHandle, dc);

            SimpleQuote           volQuote  = new SimpleQuote(0.0);
            Handle <Quote>        volHandle = new Handle <Quote>(volQuote);
            BlackVolTermStructure volTS     = new BlackConstantVol(today, calendar, volHandle, dc);

            BlackScholesMertonProcess stochProcess;
            IPricingEngine            engine;
            StrikedTypePayoff         payoff;
            Date     exDate;
            Exercise exercise;
            // Setup of market data finished

            double tolerance = 1.0e-10;

            for (int i = 0; i < values.Length; ++i)
            {
                payoff   = new PlainVanillaPayoff(values[i].type, values[i].strike);
                exDate   = today + timeToDays(values[i].t);
                exercise = new EuropeanExercise(exDate);

                spotQuote.setValue(values[i].s);
                volQuote.setValue(values[i].v);
                rQuote.setValue(values[i].r);
                qQuote.setValue(values[i].q);

                discDom = rTS.discount(exDate);
                discFor = qTS.discount(exDate);
                implVol = Math.Sqrt(volTS.blackVariance(exDate, 0.0));

                BlackDeltaCalculator myCalc = new BlackDeltaCalculator(values[i].type, DeltaVolQuote.DeltaType.PaSpot,
                                                                       spotQuote.value(), discDom, discFor, implVol);

                stochProcess = new BlackScholesMertonProcess(spotHandle,
                                                             new Handle <YieldTermStructure>(qTS),
                                                             new Handle <YieldTermStructure>(rTS),
                                                             new Handle <BlackVolTermStructure>(volTS));

                engine = new AnalyticEuropeanEngine(stochProcess);

                EuropeanOption option = new EuropeanOption(payoff, exercise);
                option.setPricingEngine(engine);

                calculatedVal = myCalc.deltaFromStrike(values[i].strike);
                expectedVal   = option.delta() - option.NPV() / spotQuote.value();
                error         = Math.Abs(expectedVal - calculatedVal);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Premium-adjusted spot delta test failed. \n"
                                 + "Calculated Delta: " + calculatedVal + "\n"
                                 + "Expected Value:   " + expectedVal + "\n"
                                 + "Error: " + error);
                }

                myCalc.setDeltaType(DeltaVolQuote.DeltaType.PaFwd);

                calculatedVal = myCalc.deltaFromStrike(values[i].strike);
                expectedVal   = expectedVal / discFor; // Premium adjusted Fwd Delta is PA spot without discount
                error         = Math.Abs(expectedVal - calculatedVal);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Premium-adjusted forward delta test failed. \n"
                                 + "Calculated Delta: " + calculatedVal + "\n"
                                 + "Expected Value:   " + expectedVal + "\n"
                                 + "Error: " + error);
                }


                // Test consistency with BlackScholes Calculator for Spot Delta
                myCalc.setDeltaType(DeltaVolQuote.DeltaType.Spot);

                calculatedVal = myCalc.deltaFromStrike(values[i].strike);
                expectedVal   = option.delta();
                error         = Math.Abs(calculatedVal - expectedVal);

                if (error > tolerance)
                {
                    QAssert.Fail("\n spot delta in BlackDeltaCalculator differs from delta in BlackScholesCalculator. \n"
                                 + "Calculated Value: " + calculatedVal + "\n"
                                 + "Expected Value:   " + expectedVal + "\n"
                                 + "Error: " + error);
                }
            }
        }
Esempio n. 12
0
 private void saveToolStripMenuItem_Click(object sender, EventArgs e)
 {
     _lines.Selected = null;
     SavedSettings ss = new SavedSettings
     {
         FirstImage = pbStartImage.Image,
         SecondImage = pbEndImage.Image,
         Lines = _lines,
         Settings = _morphSettings
     };
     using (SaveFileDialog sfd = new SaveFileDialog())
     {
         sfd.Filter = "Morph Files (*.morph)|*.morph|All Files (*.*)|*.*";
         if (sfd.ShowDialog(this) == DialogResult.OK)
         {
             var formatter = new BinaryFormatter();
             using (Stream fileStream = sfd.OpenFile())
             {
                 formatter.Serialize(fileStream, ss);
             }
         }
     }
 }
Esempio n. 13
0
        public T_OvernightIndexedSwap()
        {
#endif

            backup = new SavedSettings();
        }
Esempio n. 14
0
    void Start()
    {
        Events.OnCustomizerButtonPrevClicked += OnCustomizerButtonPrevClicked;
        Events.OnCustomizerButtonNextClicked += OnCustomizerButtonNextClicked;

        clothesSettings = Data.Instance.clothesSettings;
        savedSettings = Data.Instance.savedSettings;

        Invoke("Delay", 0.5f);

        SetSexButton();

        usernameField.text = Data.Instance.userData.username;
    }
Esempio n. 15
0
 void Start()
 {
     settings = Data.Instance.settings;
     clothesSettings = Data.Instance.clothesSettings;
     savedSettings = Data.Instance.savedSettings;
     vueltas = 0;
     StartCoroutine("NextSlide");
 }
Esempio n. 16
0
        public void testCachedValue()
        {
            // Testing credit-default swap against cached values...

            using (SavedSettings backup = new SavedSettings())
            {
                // Initialize curves
                Settings.setEvaluationDate(new Date(9, Month.June, 2006));
                Date     today    = Settings.evaluationDate();
                Calendar calendar = new TARGET();

                Handle <Quote> hazardRate = new Handle <Quote>(new SimpleQuote(0.01234));
                RelinkableHandle <DefaultProbabilityTermStructure> probabilityCurve = new RelinkableHandle <DefaultProbabilityTermStructure>();
                probabilityCurve.linkTo(new FlatHazardRate(0, calendar, hazardRate, new Actual360()));

                RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();

                discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

                // Build the schedule
                Date                  issueDate  = calendar.advance(today, -1, TimeUnit.Years);
                Date                  maturity   = calendar.advance(issueDate, 10, TimeUnit.Years);
                Frequency             frequency  = Frequency.Semiannual;
                BusinessDayConvention convention = BusinessDayConvention.ModifiedFollowing;

                Schedule schedule = new Schedule(issueDate, maturity, new Period(frequency), calendar,
                                                 convention, convention, DateGeneration.Rule.Forward, false);

                // Build the CDS
                double     fixedRate    = 0.0120;
                DayCounter dayCount     = new Actual360();
                double     notional     = 10000.0;
                double     recoveryRate = 0.4;

                CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, notional, fixedRate,
                                                              schedule, convention, dayCount, true, true);
                cds.setPricingEngine(new MidPointCdsEngine(probabilityCurve, recoveryRate, discountCurve));

                double npv      = 295.0153398;
                double fairRate = 0.007517539081;

                double calculatedNpv      = cds.NPV();
                double calculatedFairRate = cds.fairSpread();
                double tolerance          = 1.0e-7;

                if (Math.Abs(calculatedNpv - npv) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce NPV with mid-point engine\n"
                        + "    calculated NPV: " + calculatedNpv + "\n"
                        + "    expected NPV:   " + npv);
                }

                if (Math.Abs(calculatedFairRate - fairRate) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce fair rate with mid-point engine\n"
                        + "    calculated fair rate: " + calculatedFairRate + "\n"
                        + "    expected fair rate:   " + fairRate);
                }

                cds.setPricingEngine(new IntegralCdsEngine(new Period(1, TimeUnit.Days), probabilityCurve,
                                                           recoveryRate, discountCurve));

                calculatedNpv      = cds.NPV();
                calculatedFairRate = cds.fairSpread();
                tolerance          = 1.0e-5;

                if (Math.Abs(calculatedNpv - npv) > notional * tolerance * 10)
                {
                    Assert.Fail(
                        "Failed to reproduce NPV with integral engine "
                        + "(step = 1 day)\n"
                        + "    calculated NPV: " + calculatedNpv + "\n"
                        + "    expected NPV:   " + npv);
                }

                if (Math.Abs(calculatedFairRate - fairRate) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce fair rate with integral engine "
                        + "(step = 1 day)\n"
                        + "    calculated fair rate: " + calculatedFairRate + "\n"
                        + "    expected fair rate:   " + fairRate);
                }

                cds.setPricingEngine(new IntegralCdsEngine(new Period(1, TimeUnit.Weeks), probabilityCurve, recoveryRate, discountCurve));

                calculatedNpv      = cds.NPV();
                calculatedFairRate = cds.fairSpread();
                tolerance          = 1.0e-5;

                if (Math.Abs(calculatedNpv - npv) > notional * tolerance * 10)
                {
                    Assert.Fail(
                        "Failed to reproduce NPV with integral engine "
                        + "(step = 1 week)\n"
                        + "    calculated NPV: " + calculatedNpv + "\n"
                        + "    expected NPV:   " + npv);
                }

                if (Math.Abs(calculatedFairRate - fairRate) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce fair rate with integral engine "
                        + "(step = 1 week)\n"
                        + "    calculated fair rate: " + calculatedFairRate + "\n"
                        + "    expected fair rate:   " + fairRate);
                }
            }
        }
Esempio n. 17
0
   public T_InflationCapFlooredCouponTest()
   {
 #endif
       backup = new SavedSettings();
   }
Esempio n. 18
0
    public void SetCloth(List<string> arr, int idNum)
    {
        pathPreFix = @"file://";
        clothSettings = Data.Instance.clothesSettings;
        savedSettings = Data.Instance.savedSettings;

        if (arr == clothSettings.glasses)
        {
            pathTemp = pathPreFix + clothSettings.glasses[idNum] + ".png";
            StartCoroutine("LoadImages", glassesContainer[0]);
        }
        if (arr == clothSettings.shoes)
        {
            pathTemp = pathPreFix + clothSettings.shoes[idNum] + ".png";
            StartCoroutine("LoadImages", shoesContainer[0]);
            StartCoroutine("LoadImages", shoesContainer[1]);
        }
        else if (arr == clothSettings.faces)
        {
            pathTemp = pathPreFix + clothSettings.faces[idNum] + ".png";
            StartCoroutine("LoadImages", HeadContainer[0]);
        }
        else if (arr == clothSettings.tops)
        {
            pathTemp = pathPreFix + clothSettings.tops[idNum] + "_a.png";
            StartCoroutine("LoadImages", BodyContainer[0]);

            pathTemp = pathPreFix + clothSettings.tops[idNum] + "_b.png";
            StartCoroutine("LoadImages", Arm1Container[0]);
            StartCoroutine("LoadImages", Arm1Container[1]);

            pathTemp = pathPreFix + clothSettings.tops[idNum] + "_c.png";
            StartCoroutine("LoadImages", Arm2Container[0]);
            StartCoroutine("LoadImages", Arm2Container[1]);

            pathTemp = pathPreFix + clothSettings.tops[idNum] + "_d.png";
            StartCoroutine("LoadImages", Arm3Container[0]);
            StartCoroutine("LoadImages", Arm3Container[1]);
        }
        else if (arr == clothSettings.legs)
        {
            pathTemp = pathPreFix + clothSettings.legs[idNum] + "_a.png";
            StartCoroutine("LoadImages", HipContainer[0]);

            pathTemp = pathPreFix + clothSettings.legs[idNum] + "_b.png";
            StartCoroutine("LoadImages", LegsContainer[0]);
            StartCoroutine("LoadImages", LegsContainer[1]);
        }
        else if (arr == clothSettings.hairs)
        {
            pathTemp = pathPreFix + clothSettings.hairs[idNum] + "_a.png";
            StartCoroutine("LoadImages", Hair1Container[0]);

            pathTemp = pathPreFix + clothSettings.hairs[idNum] + "_b.png";
            StartCoroutine("LoadImages", Hair2Container[0]);
        }
    }
Esempio n. 19
0
 public T_LiborMarketModel()
 {
     backup = new SavedSettings();
 }
Esempio n. 20
0
 void Start()
 {
     pathPreFix = @"file://";
     clothSettings = Data.Instance.clothesSettings;
     savedSettings = Data.Instance.savedSettings;
       //  GetComponent<Animation>().Play("shoes1");
     if (UnityEngine.Random.Range(0, 100) < 50)
         RandomActionAnim();
     else
         RandomIdleAnim();
 }
Esempio n. 21
0
        private void testOptionGreeks(ForwardVanillaEngine.GetOriginalEngine getEngine)
        {
            SavedSettings backup = new SavedSettings();

            Dictionary <String, double> calculated = new Dictionary <string, double>(),
                                        expected   = new Dictionary <string, double>(),
                                        tolerance  = new Dictionary <string, double>();

            tolerance["delta"]  = 1.0e-5;
            tolerance["gamma"]  = 1.0e-5;
            tolerance["theta"]  = 1.0e-5;
            tolerance["rho"]    = 1.0e-5;
            tolerance["divRho"] = 1.0e-5;
            tolerance["vega"]   = 1.0e-5;

            Option.Type[] types       = { Option.Type.Call, Option.Type.Put };
            double[]      moneyness   = { 0.9, 1.0, 1.1 };
            double[]      underlyings = { 100.0 };
            double[]      qRates      = { 0.04, 0.05, 0.06 };
            double[]      rRates      = { 0.01, 0.05, 0.15 };
            int[]         lengths     = { 1, 2 };
            Frequency[]   frequencies = { Frequency.Semiannual, Frequency.Quarterly, };
            double[]      vols        = { 0.11, 0.50, 1.20 };

            DayCounter dc    = new Actual360();
            Date       today = Date.Today;

            Settings.setEvaluationDate(today);

            SimpleQuote spot  = new SimpleQuote(0.0);
            SimpleQuote qRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> qTS = new Handle <YieldTermStructure>(Utilities.flatRate(qRate, dc));
            SimpleQuote rRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> rTS = new Handle <YieldTermStructure>(Utilities.flatRate(rRate, dc));
            SimpleQuote vol = new SimpleQuote(0.0);
            Handle <BlackVolTermStructure> volTS = new Handle <BlackVolTermStructure>(Utilities.flatVol(vol, dc));

            BlackScholesMertonProcess process = new BlackScholesMertonProcess(new Handle <Quote>(spot), qTS, rTS, volTS);

            for (int i = 0; i < types.Length; i++)
            {
                for (int j = 0; j < moneyness.Length; j++)
                {
                    for (int k = 0; k < lengths.Length; k++)
                    {
                        for (int kk = 0; kk < frequencies.Length; kk++)
                        {
                            EuropeanExercise maturity = new EuropeanExercise(today + new Period(lengths[k], TimeUnit.Years));

                            PercentageStrikePayoff payoff = new PercentageStrikePayoff(types[i], moneyness[j]);

                            List <Date> reset = new List <Date>();
                            for (Date d = today + new Period(frequencies[kk]);
                                 d < maturity.lastDate();
                                 d += new Period(frequencies[kk]))
                            {
                                reset.Add(d);
                            }

                            IPricingEngine engine = getEngine(process);

                            CliquetOption option = new CliquetOption(payoff, maturity, reset);
                            option.setPricingEngine(engine);

                            for (int l = 0; l < underlyings.Length; l++)
                            {
                                for (int m = 0; m < qRates.Length; m++)
                                {
                                    for (int n = 0; n < rRates.Length; n++)
                                    {
                                        for (int p = 0; p < vols.Length; p++)
                                        {
                                            double u = underlyings[l];
                                            double q = qRates[m],
                                                   r = rRates[n];
                                            double v = vols[p];
                                            spot.setValue(u);
                                            qRate.setValue(q);
                                            rRate.setValue(r);
                                            vol.setValue(v);

                                            double value = option.NPV();
                                            calculated["delta"]  = option.delta();
                                            calculated["gamma"]  = option.gamma();
                                            calculated["theta"]  = option.theta();
                                            calculated["rho"]    = option.rho();
                                            calculated["divRho"] = option.dividendRho();
                                            calculated["vega"]   = option.vega();

                                            if (value > spot.value() * 1.0e-5)
                                            {
                                                // perturb spot and get delta and gamma
                                                double du = u * 1.0e-4;
                                                spot.setValue(u + du);
                                                double value_p = option.NPV(),
                                                       delta_p = option.delta();
                                                spot.setValue(u - du);
                                                double value_m = option.NPV(),
                                                       delta_m = option.delta();
                                                spot.setValue(u);
                                                expected["delta"] = (value_p - value_m) / (2 * du);
                                                expected["gamma"] = (delta_p - delta_m) / (2 * du);

                                                // perturb rates and get rho and dividend rho
                                                double dr = r * 1.0e-4;
                                                rRate.setValue(r + dr);
                                                value_p = option.NPV();
                                                rRate.setValue(r - dr);
                                                value_m = option.NPV();
                                                rRate.setValue(r);
                                                expected["rho"] = (value_p - value_m) / (2 * dr);

                                                double dq = q * 1.0e-4;
                                                qRate.setValue(q + dq);
                                                value_p = option.NPV();
                                                qRate.setValue(q - dq);
                                                value_m = option.NPV();
                                                qRate.setValue(q);
                                                expected["divRho"] = (value_p - value_m) / (2 * dq);

                                                // perturb volatility and get vega
                                                double dv = v * 1.0e-4;
                                                vol.setValue(v + dv);
                                                value_p = option.NPV();
                                                vol.setValue(v - dv);
                                                value_m = option.NPV();
                                                vol.setValue(v);
                                                expected["vega"] = (value_p - value_m) / (2 * dv);

                                                // perturb date and get theta
                                                double dT = dc.yearFraction(today - 1, today + 1);
                                                Settings.setEvaluationDate(today - 1);
                                                value_m = option.NPV();
                                                Settings.setEvaluationDate(today + 1);
                                                value_p = option.NPV();
                                                Settings.setEvaluationDate(today);
                                                expected["theta"] = (value_p - value_m) / dT;

                                                // compare
                                                foreach (var it in calculated)
                                                {
                                                    String greek = it.Key;
                                                    double expct = expected  [greek],
                                                           calcl = calculated[greek],
                                                           tol   = tolerance [greek];
                                                    double error = Utilities.relativeError(expct, calcl, u);
                                                    if (error > tol)
                                                    {
                                                        REPORT_FAILURE(greek, payoff, maturity,
                                                                       u, q, r, today, v,
                                                                       expct, calcl, error, tol);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 22
0
        public void testEuropeanGreeks()
        {
            // Testing dividend European option greeks...

            SavedSettings backup = new SavedSettings();

            Dictionary <string, double> calculated = new Dictionary <string, double>(),
                                        expected   = new Dictionary <string, double>(),
                                        tolerance  = new Dictionary <string, double>();

            tolerance["delta"] = 1.0e-5;
            tolerance["gamma"] = 1.0e-5;
            tolerance["theta"] = 1.0e-5;
            tolerance["rho"]   = 1.0e-5;
            tolerance["vega"]  = 1.0e-5;

            Option.Type[] types       = { Option.Type.Call, Option.Type.Put };
            double[]      strikes     = { 50.0, 99.5, 100.0, 100.5, 150.0 };
            double[]      underlyings = { 100.0 };
            double[]      qRates      = { 0.00, 0.10, 0.30 };
            double[]      rRates      = { 0.01, 0.05, 0.15 };
            int[]         lengths     = { 1, 2 };
            double[]      vols        = { 0.05, 0.20, 0.40 };

            DayCounter dc    = new Actual360();
            Date       today = Date.Today;

            Settings.setEvaluationDate(today);

            SimpleQuote spot  = new SimpleQuote(0.0);
            SimpleQuote qRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> qTS = new Handle <YieldTermStructure>(Utilities.flatRate(qRate, dc));
            SimpleQuote rRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> rTS = new Handle <YieldTermStructure>(Utilities.flatRate(rRate, dc));
            SimpleQuote vol = new SimpleQuote(0.0);
            Handle <BlackVolTermStructure> volTS = new Handle <BlackVolTermStructure>(Utilities.flatVol(vol, dc));

            for (int i = 0; i < types.Length; i++)
            {
                for (int j = 0; j < strikes.Length; j++)
                {
                    for (int k = 0; k < lengths.Length; k++)
                    {
                        Date     exDate   = today + new Period(lengths[k], TimeUnit.Years);
                        Exercise exercise = new EuropeanExercise(exDate);

                        List <Date>   dividendDates = new List <Date>();
                        List <double> dividends     = new List <double>();
                        for (Date d = today + new Period(3, TimeUnit.Months);
                             d < exercise.lastDate();
                             d += new Period(6, TimeUnit.Months))
                        {
                            dividendDates.Add(d);
                            dividends.Add(5.0);
                        }

                        StrikedTypePayoff payoff = new PlainVanillaPayoff(types[i], strikes[j]);

                        BlackScholesMertonProcess stochProcess = new BlackScholesMertonProcess(new Handle <Quote>(spot),
                                                                                               qTS, rTS, volTS);

                        IPricingEngine engine = new AnalyticDividendEuropeanEngine(stochProcess);

                        DividendVanillaOption option = new DividendVanillaOption(payoff, exercise, dividendDates,
                                                                                 dividends);
                        option.setPricingEngine(engine);

                        for (int l = 0; l < underlyings.Length; l++)
                        {
                            for (int m = 0; m < qRates.Length; m++)
                            {
                                for (int n = 0; n < rRates.Length; n++)
                                {
                                    for (int p = 0; p < vols.Length; p++)
                                    {
                                        double u = underlyings[l];
                                        double q = qRates[m],
                                               r = rRates[n];
                                        double v = vols[p];
                                        spot.setValue(u);
                                        qRate.setValue(q);
                                        rRate.setValue(r);
                                        vol.setValue(v);

                                        double value = option.NPV();
                                        calculated["delta"] = option.delta();
                                        calculated["gamma"] = option.gamma();
                                        calculated["theta"] = option.theta();
                                        calculated["rho"]   = option.rho();
                                        calculated["vega"]  = option.vega();

                                        if (value > spot.value() * 1.0e-5)
                                        {
                                            // perturb spot and get delta and gamma
                                            double du = u * 1.0e-4;
                                            spot.setValue(u + du);
                                            double value_p = option.NPV(),
                                                   delta_p = option.delta();
                                            spot.setValue(u - du);
                                            double value_m = option.NPV(),
                                                   delta_m = option.delta();
                                            spot.setValue(u);
                                            expected["delta"] = (value_p - value_m) / (2 * du);
                                            expected["gamma"] = (delta_p - delta_m) / (2 * du);

                                            // perturb risk-free rate and get rho
                                            double dr = r * 1.0e-4;
                                            rRate.setValue(r + dr);
                                            value_p = option.NPV();
                                            rRate.setValue(r - dr);
                                            value_m = option.NPV();
                                            rRate.setValue(r);
                                            expected["rho"] = (value_p - value_m) / (2 * dr);

                                            // perturb volatility and get vega
                                            double dv = v * 1.0e-4;
                                            vol.setValue(v + dv);
                                            value_p = option.NPV();
                                            vol.setValue(v - dv);
                                            value_m = option.NPV();
                                            vol.setValue(v);
                                            expected["vega"] = (value_p - value_m) / (2 * dv);

                                            // perturb date and get theta
                                            double dT = dc.yearFraction(today - 1, today + 1);
                                            Settings.setEvaluationDate(today - 1);
                                            value_m = option.NPV();
                                            Settings.setEvaluationDate(today + 1);
                                            value_p = option.NPV();
                                            Settings.setEvaluationDate(today);
                                            expected["theta"] = (value_p - value_m) / dT;

                                            // compare
                                            foreach (KeyValuePair <string, double> it in calculated)
                                            {
                                                string greek = it.Key;
                                                double expct = expected  [greek],
                                                       calcl = calculated[greek],
                                                       tol   = tolerance [greek];
                                                double error = Utilities.relativeError(expct, calcl, u);
                                                if (error > tol)
                                                {
                                                    REPORT_FAILURE(greek, payoff, exercise,
                                                                   u, q, r, today, v,
                                                                   expct, calcl, error, tol);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 23
0
        public void testPutCallParity()
        {
            // Testing put-call parity for deltas

            // Test for put call parity between put and call deltas.

            SavedSettings backup = new SavedSettings();

            /* The data below are from
             * "Option pricing formulas", E.G. Haug, McGraw-Hill 1998
             * pag 11-16
             */

            EuropeanOptionData[] values =
            {
                // pag 2-8
                //        type, strike,   spot,    q,    r,    t,  vol,   value,    tol
                new EuropeanOptionData(Option.Type.Call,  65.00,  60.00, 0.00, 0.08, 0.25, 0.30,  2.1334, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,   95.00, 100.00, 0.05, 0.10, 0.50, 0.20,  2.4648, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,   19.00,  19.00, 0.10, 0.10, 0.75, 0.28,  1.7011, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call,  19.00,  19.00, 0.10, 0.10, 0.75, 0.28,  1.7011, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call,   1.60,   1.56, 0.08, 0.06, 0.50, 0.12,  0.0291, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,   70.00,  75.00, 0.05, 0.10, 0.50, 0.35,  4.0870, 1.0e-4),
                // pag 24
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.10, 0.15,  0.0205, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.10, 0.15,  1.8734, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.10, 0.15,  9.9413, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.10, 0.25,  0.3150, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.10, 0.25,  3.1217, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.10, 0.25, 10.3556, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.10, 0.35,  0.9474, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.10, 0.35,  4.3693, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.10, 0.35, 11.1381, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.50, 0.15,  0.8069, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.50, 0.15,  4.0232, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.50, 0.15, 10.5769, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.50, 0.25,  2.7026, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.50, 0.25,  6.6997, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.50, 0.25, 12.7857, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00,  90.00, 0.10, 0.10, 0.50, 0.35,  4.9329, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 100.00, 0.10, 0.10, 0.50, 0.35,  9.3679, 1.0e-4),
                new EuropeanOptionData(Option.Type.Call, 100.00, 110.00, 0.10, 0.10, 0.50, 0.35, 15.3086, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.10, 0.15,  9.9210, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.10, 0.15,  1.8734, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.10, 0.15,  0.0408, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.10, 0.25, 10.2155, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.10, 0.25,  3.1217, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.10, 0.25,  0.4551, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.10, 0.35, 10.8479, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.10, 0.35,  4.3693, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.10, 0.35,  1.2376, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.50, 0.15, 10.3192, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.50, 0.15,  4.0232, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.50, 0.15,  1.0646, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.50, 0.25, 12.2149, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.50, 0.25,  6.6997, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.50, 0.25,  3.2734, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00,  90.00, 0.10, 0.10, 0.50, 0.35, 14.4452, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 100.00, 0.10, 0.10, 0.50, 0.35,  9.3679, 1.0e-4),
                new EuropeanOptionData(Option.Type.Put,  100.00, 110.00, 0.10, 0.10, 0.50, 0.35,  5.7963, 1.0e-4),
                // pag 27
                new EuropeanOptionData(Option.Type.Call,  40.00,  42.00, 0.08, 0.04, 0.75, 0.35,  5.0975, 1.0e-4)
            };

            DayCounter dc       = new Actual360();
            Calendar   calendar = new TARGET();
            Date       today    = Date.Today;

            double discFor        = 0.0;
            double discDom        = 0.0;
            double implVol        = 0.0;
            double deltaCall      = 0.0;
            double deltaPut       = 0.0;
            double expectedDiff   = 0.0;
            double calculatedDiff = 0.0;
            double error          = 0.0;
            double forward        = 0.0;

            SimpleQuote spotQuote = new SimpleQuote(0.0);

            SimpleQuote        qQuote  = new SimpleQuote(0.0);
            Handle <Quote>     qHandle = new Handle <Quote>(qQuote);
            YieldTermStructure qTS     = new FlatForward(today, qHandle, dc);

            SimpleQuote        rQuote  = new SimpleQuote(0.0);
            Handle <Quote>     rHandle = new Handle <Quote>(qQuote);
            YieldTermStructure rTS     = new FlatForward(today, rHandle, dc);

            SimpleQuote           volQuote  = new SimpleQuote(0.0);
            Handle <Quote>        volHandle = new Handle <Quote>(volQuote);
            BlackVolTermStructure volTS     = new BlackConstantVol(today, calendar, volHandle, dc);

            StrikedTypePayoff payoff;
            Date     exDate;
            Exercise exercise;

            double tolerance = 1.0e-10;

            for (int i = 0; i < values.Length; ++i)
            {
                payoff   = new PlainVanillaPayoff(Option.Type.Call, values[i].strike);
                exDate   = today + timeToDays(values[i].t);
                exercise = new EuropeanExercise(exDate);

                spotQuote.setValue(values[i].s);
                volQuote.setValue(values[i].v);
                rQuote.setValue(values[i].r);
                qQuote.setValue(values[i].q);
                discDom = rTS.discount(exDate);
                discFor = qTS.discount(exDate);
                implVol = Math.Sqrt(volTS.blackVariance(exDate, 0.0));
                forward = spotQuote.value() * discFor / discDom;

                BlackDeltaCalculator myCalc = new BlackDeltaCalculator(Option.Type.Call, DeltaVolQuote.DeltaType.Spot,
                                                                       spotQuote.value(), discDom, discFor, implVol);

                deltaCall = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Put);
                deltaPut = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Call);

                expectedDiff   = discFor;
                calculatedDiff = deltaCall - deltaPut;
                error          = Math.Abs(expectedDiff - calculatedDiff);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Put-call parity failed for spot delta. \n"
                                 + "Calculated Call Delta: " + deltaCall + "\n"
                                 + "Calculated Put Delta:  " + deltaPut + "\n"
                                 + "Expected Difference:   " + expectedDiff + "\n"
                                 + "Calculated Difference: " + calculatedDiff);
                }
                myCalc.setDeltaType(DeltaVolQuote.DeltaType.Fwd);

                deltaCall = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Put);
                deltaPut = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Call);

                expectedDiff   = 1.0;
                calculatedDiff = deltaCall - deltaPut;
                error          = Math.Abs(expectedDiff - calculatedDiff);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Put-call parity failed for forward delta. \n"
                                 + "Calculated Call Delta: " + deltaCall + "\n"
                                 + "Calculated Put Delta:  " + deltaPut + "\n"
                                 + "Expected Difference:   " + expectedDiff + "\n"
                                 + "Calculated Difference: " + calculatedDiff);
                }

                myCalc.setDeltaType(DeltaVolQuote.DeltaType.PaSpot);

                deltaCall = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Put);
                deltaPut = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Call);

                expectedDiff   = discFor * values[i].strike / forward;
                calculatedDiff = deltaCall - deltaPut;
                error          = Math.Abs(expectedDiff - calculatedDiff);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Put-call parity failed for premium-adjusted spot delta. \n"
                                 + "Calculated Call Delta: " + deltaCall + "\n"
                                 + "Calculated Put Delta:  " + deltaPut + "\n"
                                 + "Expected Difference:   " + expectedDiff + "\n"
                                 + "Calculated Difference: " + calculatedDiff);
                }

                myCalc.setDeltaType(DeltaVolQuote.DeltaType.PaFwd);

                deltaCall = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Put);
                deltaPut = myCalc.deltaFromStrike(values[i].strike);
                myCalc.setOptionType(Option.Type.Call);

                expectedDiff   = values[i].strike / forward;
                calculatedDiff = deltaCall - deltaPut;
                error          = Math.Abs(expectedDiff - calculatedDiff);

                if (error > tolerance)
                {
                    QAssert.Fail("\n Put-call parity failed for premium-adjusted forward delta. \n"
                                 + "Calculated Call Delta: " + deltaCall + "\n"
                                 + "Calculated Put Delta:  " + deltaPut + "\n"
                                 + "Expected Difference:   " + expectedDiff + "\n"
                                 + "Calculated Difference: " + calculatedDiff);
                }
            }
        }
Esempio n. 24
0
        public void testFdEuropeanValues()
        {
            // Testing finite-difference dividend European option values...

            SavedSettings backup = new SavedSettings();

            double tolerance  = 1.0e-2;
            int    gridPoints = 300;
            int    timeSteps  = 40;

            Option.Type[] types       = { Option.Type.Call, Option.Type.Put };
            double[]      strikes     = { 50.0, 99.5, 100.0, 100.5, 150.0 };
            double[]      underlyings = { 100.0 };
            // Rate qRates[] = { 0.00, 0.10, 0.30 };
            // Analytic dividend may not be handling q correctly
            double[] qRates  = { 0.00 };
            double[] rRates  = { 0.01, 0.05, 0.15 };
            int[]    lengths = { 1, 2 };
            double[] vols    = { 0.05, 0.20, 0.40 };

            DayCounter dc    = new Actual360();
            Date       today = Date.Today;

            Settings.setEvaluationDate(today);

            SimpleQuote spot  = new SimpleQuote(0.0);
            SimpleQuote qRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> qTS = new Handle <YieldTermStructure>(Utilities.flatRate(qRate, dc));
            SimpleQuote rRate = new SimpleQuote(0.0);
            Handle <YieldTermStructure> rTS = new Handle <YieldTermStructure>(Utilities.flatRate(rRate, dc));
            SimpleQuote vol = new SimpleQuote(0.0);
            Handle <BlackVolTermStructure> volTS = new Handle <BlackVolTermStructure>(Utilities.flatVol(vol, dc));

            for (int i = 0; i < types.Length; i++)
            {
                for (int j = 0; j < strikes.Length; j++)
                {
                    for (int k = 0; k < lengths.Length; k++)
                    {
                        Date     exDate   = today + new Period(lengths[k], TimeUnit.Years);
                        Exercise exercise = new EuropeanExercise(exDate);

                        List <Date>   dividendDates = new List <Date>();
                        List <double> dividends     = new List <double>();
                        for (Date d = today + new Period(3, TimeUnit.Months);
                             d < exercise.lastDate();
                             d += new Period(6, TimeUnit.Months))
                        {
                            dividendDates.Add(d);
                            dividends.Add(5.0);
                        }

                        StrikedTypePayoff payoff = new PlainVanillaPayoff(types[i], strikes[j]);

                        BlackScholesMertonProcess stochProcess = new BlackScholesMertonProcess(new Handle <Quote>(spot),
                                                                                               qTS, rTS, volTS);

                        IPricingEngine engine = new FDDividendEuropeanEngine(stochProcess, timeSteps, gridPoints);

                        IPricingEngine ref_engine = new AnalyticDividendEuropeanEngine(stochProcess);

                        DividendVanillaOption option = new DividendVanillaOption(payoff, exercise, dividendDates, dividends);
                        option.setPricingEngine(engine);

                        DividendVanillaOption ref_option = new DividendVanillaOption(payoff, exercise, dividendDates, dividends);
                        ref_option.setPricingEngine(ref_engine);

                        for (int l = 0; l < underlyings.Length; l++)
                        {
                            for (int m = 0; m < qRates.Length; m++)
                            {
                                for (int n = 0; n < rRates.Length; n++)
                                {
                                    for (int p = 0; p < vols.Length; p++)
                                    {
                                        double u = underlyings[l];
                                        double q = qRates[m],
                                               r = rRates[n];
                                        double v = vols[p];
                                        spot.setValue(u);
                                        qRate.setValue(q);
                                        rRate.setValue(r);
                                        vol.setValue(v);
                                        // FLOATING_POINT_EXCEPTION
                                        double calculated = option.NPV();
                                        if (calculated > spot.value() * 1.0e-5)
                                        {
                                            double expected = ref_option.NPV();
                                            double error    = Math.Abs(calculated - expected);
                                            if (error > tolerance)
                                            {
                                                REPORT_FAILURE("value", payoff, exercise,
                                                               u, q, r, today, v,
                                                               expected, calculated,
                                                               error, tolerance);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 25
0
        public T_Bermudanswaption()
        {
#endif
            backup = new SavedSettings();
        }
Esempio n. 26
0
  public T_CapFloor()
  {
 #endif
      backup = new SavedSettings();
  }
Esempio n. 27
0
        public T_Swaps()
        {
#endif
            backup = new SavedSettings();
        }
Esempio n. 28
0
        public void testSettings()
        {
            // Testing cash-flow settings...
            using (SavedSettings backup = new SavedSettings())
            {
                Date today = Date.Today;
                Settings.Instance.setEvaluationDate(today);

                // cash flows at T+0, T+1, T+2
                List <CashFlow> leg = new List <CashFlow>();

                for (int i = 0; i < 3; ++i)
                {
                    leg.Add(new SimpleCashFlow(1.0, today + i));
                }

                // case 1: don't include reference-date payments, no override at
                //         today's date

                Settings.Instance.includeReferenceDateEvents = false;
                Settings.Instance.includeTodaysCashFlows     = null;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, false, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, false, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 2: same, but with explicit setting at today's date

                Settings.Instance.includeReferenceDateEvents = false;
                Settings.Instance.includeTodaysCashFlows     = false;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, false, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, false, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 3: do include reference-date payments, no override at
                //         today's date

                Settings.Instance.includeReferenceDateEvents = true;
                Settings.Instance.includeTodaysCashFlows     = null;

                CHECK_INCLUSION(0, 0, true, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 4: do include reference-date payments, explicit (and same)
                //         setting at today's date

                Settings.Instance.includeReferenceDateEvents = true;
                Settings.Instance.includeTodaysCashFlows     = true;

                CHECK_INCLUSION(0, 0, true, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // case 5: do include reference-date payments, override at
                //         today's date

                Settings.Instance.includeReferenceDateEvents = true;
                Settings.Instance.includeTodaysCashFlows     = false;

                CHECK_INCLUSION(0, 0, false, leg, today);
                CHECK_INCLUSION(0, 1, false, leg, today);

                CHECK_INCLUSION(1, 0, true, leg, today);
                CHECK_INCLUSION(1, 1, true, leg, today);
                CHECK_INCLUSION(1, 2, false, leg, today);

                CHECK_INCLUSION(2, 1, true, leg, today);
                CHECK_INCLUSION(2, 2, true, leg, today);
                CHECK_INCLUSION(2, 3, false, leg, today);

                // no discount to make calculations easier
                InterestRate no_discount = new InterestRate(0.0, new Actual365Fixed(), Compounding.Continuous, Frequency.Annual);

                // no override
                Settings.Instance.includeTodaysCashFlows = null;

                CHECK_NPV(false, 2.0, no_discount, leg, today);
                CHECK_NPV(true, 3.0, no_discount, leg, today);

                // override
                Settings.Instance.includeTodaysCashFlows = false;

                CHECK_NPV(false, 2.0, no_discount, leg, today);
                CHECK_NPV(true, 2.0, no_discount, leg, today);
            }
        }
Esempio n. 29
0
        public void testCrankNicolsonWithDamping()
        {
            SavedSettings backup = new SavedSettings();

            DayCounter dc    = new Actual360();
            Date       today = Date.Today;

            SimpleQuote           spot  = new SimpleQuote(100.0);
            YieldTermStructure    qTS   = Utilities.flatRate(today, 0.06, dc);
            YieldTermStructure    rTS   = Utilities.flatRate(today, 0.06, dc);
            BlackVolTermStructure volTS = Utilities.flatVol(today, 0.35, dc);

            StrikedTypePayoff payoff =
                new CashOrNothingPayoff(Option.Type.Put, 100, 10.0);

            double   maturity = 0.75;
            Date     exDate   = today + Convert.ToInt32(maturity * 360 + 0.5);
            Exercise exercise = new EuropeanExercise(exDate);

            BlackScholesMertonProcess process = new
                                                BlackScholesMertonProcess(new Handle <Quote>(spot),
                                                                          new Handle <YieldTermStructure>(qTS),
                                                                          new Handle <YieldTermStructure>(rTS),
                                                                          new Handle <BlackVolTermStructure>(volTS));
            IPricingEngine engine =
                new AnalyticEuropeanEngine(process);

            VanillaOption opt = new VanillaOption(payoff, exercise);

            opt.setPricingEngine(engine);
            double expectedPV    = opt.NPV();
            double expectedGamma = opt.gamma();

            // fd pricing using implicit damping steps and Crank Nicolson
            int        csSteps = 25, dampingSteps = 3, xGrid = 400;
            List <int> dim = new InitializedList <int>(1, xGrid);

            FdmLinearOpLayout layout       = new FdmLinearOpLayout(dim);
            Fdm1dMesher       equityMesher =
                new FdmBlackScholesMesher(
                    dim[0], process, maturity, payoff.strike(),
                    null, null, 0.0001, 1.5,
                    new Pair <double?, double?>(payoff.strike(), 0.01));

            FdmMesher mesher =
                new FdmMesherComposite(equityMesher);

            FdmBlackScholesOp map =
                new FdmBlackScholesOp(mesher, process, payoff.strike());

            FdmInnerValueCalculator calculator =
                new FdmLogInnerValue(payoff, mesher, 0);

            object rhs = new Vector(layout.size());
            Vector x   = new Vector(layout.size());
            FdmLinearOpIterator endIter = layout.end();

            for (FdmLinearOpIterator iter = layout.begin(); iter != endIter;
                 ++iter)
            {
                (rhs as Vector)[iter.index()] = calculator.avgInnerValue(iter, maturity);
                x[iter.index()] = mesher.location(iter, 0);
            }

            FdmBackwardSolver solver = new FdmBackwardSolver(map, new FdmBoundaryConditionSet(),
                                                             new FdmStepConditionComposite(),
                                                             new FdmSchemeDesc().Douglas());

            solver.rollback(ref rhs, maturity, 0.0, csSteps, dampingSteps);

            MonotonicCubicNaturalSpline spline = new MonotonicCubicNaturalSpline(x, x.Count, rhs as Vector);

            double s               = spot.value();
            double calculatedPV    = spline.value(Math.Log(s));
            double calculatedGamma = (spline.secondDerivative(Math.Log(s))
                                      - spline.derivative(Math.Log(s))) / (s * s);

            double relTol = 2e-3;

            if (Math.Abs(calculatedPV - expectedPV) > relTol * expectedPV)
            {
                QAssert.Fail("Error calculating the PV of the digital option" +
                             "\n rel. tolerance:  " + relTol +
                             "\n expected:        " + expectedPV +
                             "\n calculated:      " + calculatedPV);
            }
            if (Math.Abs(calculatedGamma - expectedGamma) > relTol * expectedGamma)
            {
                QAssert.Fail("Error calculating the Gamma of the digital option" +
                             "\n rel. tolerance:  " + relTol +
                             "\n expected:        " + expectedGamma +
                             "\n calculated:      " + calculatedGamma);
            }
        }
Esempio n. 30
0
 public T_PiecewiseyieldCurve()
 {
 #endif
     backup  = new SavedSettings();
     cleaner = new IndexHistoryCleaner();
 }
Esempio n. 31
0
        public void testImpliedHazardRate()
        {
            // Testing implied hazard-rate for credit-default swaps...

            using (SavedSettings backup = new SavedSettings())
            {
                // Initialize curves
                Calendar calendar = new TARGET();
                Date     today    = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);

                double     h1 = 0.30, h2 = 0.40;
                DayCounter dayCounter = new Actual365Fixed();

                List <Date>   dates       = new List <Date>(3);
                List <double> hazardRates = new List <double>(3);
                dates.Add(today);
                hazardRates.Add(h1);

                dates.Add(today + new Period(5, TimeUnit.Years));
                hazardRates.Add(h1);

                dates.Add(today + new Period(10, TimeUnit.Years));
                hazardRates.Add(h2);

                RelinkableHandle <DefaultProbabilityTermStructure> probabilityCurve =
                    new RelinkableHandle <DefaultProbabilityTermStructure>();
                probabilityCurve.linkTo(new InterpolatedHazardRateCurve <BackwardFlat>(dates,
                                                                                       hazardRates,
                                                                                       dayCounter));

                RelinkableHandle <YieldTermStructure> discountCurve = new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new FlatForward(today, 0.03, new Actual360()));

                Frequency             frequency  = Frequency.Semiannual;
                BusinessDayConvention convention = BusinessDayConvention.ModifiedFollowing;

                Date       issueDate    = calendar.advance(today, -6, TimeUnit.Months);
                double     fixedRate    = 0.0120;
                DayCounter cdsDayCount  = new Actual360();
                double     notional     = 10000.0;
                double     recoveryRate = 0.4;

                double?latestRate = null;
                for (int n = 6; n <= 10; ++n)
                {
                    Date     maturity = calendar.advance(issueDate, n, TimeUnit.Years);
                    Schedule schedule = new Schedule(issueDate, maturity, new Period(frequency), calendar,
                                                     convention, convention,
                                                     DateGeneration.Rule.Forward, false);

                    CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, notional, fixedRate,
                                                                  schedule, convention, cdsDayCount, true, true);
                    cds.setPricingEngine(new MidPointCdsEngine(probabilityCurve, recoveryRate, discountCurve));

                    double NPV      = cds.NPV();
                    double flatRate = cds.impliedHazardRate(NPV, discountCurve,
                                                            dayCounter,
                                                            recoveryRate);

                    if (flatRate < h1 || flatRate > h2)
                    {
                        Assert.Fail("implied hazard rate outside expected range\n"
                                    + "    maturity: " + n + " years\n"
                                    + "    expected minimum: " + h1 + "\n"
                                    + "    expected maximum: " + h2 + "\n"
                                    + "    implied rate:     " + flatRate);
                    }

                    if (n > 6 && flatRate < latestRate)
                    {
                        Assert.Fail("implied hazard rate decreasing with swap maturity\n"
                                    + "    maturity: " + n + " years\n"
                                    + "    previous rate: " + latestRate + "\n"
                                    + "    implied rate:  " + flatRate);
                    }

                    latestRate = flatRate;

                    RelinkableHandle <DefaultProbabilityTermStructure> probability = new RelinkableHandle <DefaultProbabilityTermStructure>();
                    probability.linkTo(new FlatHazardRate(today, new Handle <Quote>(new SimpleQuote(flatRate)), dayCounter));

                    CreditDefaultSwap cds2 = new CreditDefaultSwap(Protection.Side.Seller, notional, fixedRate,
                                                                   schedule, convention, cdsDayCount, true, true);
                    cds2.setPricingEngine(new MidPointCdsEngine(probability, recoveryRate, discountCurve));

                    double NPV2      = cds2.NPV();
                    double tolerance = 1.0;
                    if (Math.Abs(NPV - NPV2) > tolerance)
                    {
                        Assert.Fail("failed to reproduce NPV with implied rate\n"
                                    + "    expected:   " + NPV + "\n"
                                    + "    calculated: " + NPV2);
                    }
                }
            }
        }
Esempio n. 32
0
 public T_OptionletStripper()
 {
     backup = new SavedSettings();
 }
Esempio n. 33
0
        public void testFairUpfront()
        {
            // Testing fair-upfront calculation for credit-default swaps...

            using (SavedSettings backup = new SavedSettings())
            {
                // Initialize curves
                Calendar calendar = new TARGET();
                Date     today    = calendar.adjust(Date.Today);
                Settings.setEvaluationDate(today);

                Handle <Quote> hazardRate = new Handle <Quote>(new SimpleQuote(0.01234));
                RelinkableHandle <DefaultProbabilityTermStructure> probabilityCurve =
                    new RelinkableHandle <DefaultProbabilityTermStructure>();
                probabilityCurve.linkTo(new FlatHazardRate(0, calendar, hazardRate, new Actual360()));

                RelinkableHandle <YieldTermStructure> discountCurve =
                    new RelinkableHandle <YieldTermStructure>();
                discountCurve.linkTo(new FlatForward(today, 0.06, new Actual360()));

                // Build the schedule
                Date issueDate = today;
                Date maturity  = calendar.advance(issueDate, 10, TimeUnit.Years);
                BusinessDayConvention convention = BusinessDayConvention.Following;

                Schedule schedule =
                    new MakeSchedule().from(issueDate)
                    .to(maturity)
                    .withFrequency(Frequency.Quarterly)
                    .withCalendar(calendar)
                    .withTerminationDateConvention(convention)
                    .withRule(DateGeneration.Rule.TwentiethIMM).value();

                // Build the CDS
                double     fixedRate    = 0.05;
                double     upfront      = 0.001;
                DayCounter dayCount     = new Actual360();
                double     notional     = 10000.0;
                double     recoveryRate = 0.4;

                IPricingEngine engine = new MidPointCdsEngine(probabilityCurve, recoveryRate, discountCurve, true);

                CreditDefaultSwap cds = new CreditDefaultSwap(Protection.Side.Seller, notional, upfront, fixedRate,
                                                              schedule, convention, dayCount, true, true);
                cds.setPricingEngine(engine);

                double fairUpfront = cds.fairUpfront();

                CreditDefaultSwap fairCds = new CreditDefaultSwap(Protection.Side.Seller, notional,
                                                                  fairUpfront, fixedRate, schedule, convention, dayCount, true, true);
                fairCds.setPricingEngine(engine);

                double fairNPV   = fairCds.NPV();
                double tolerance = 1e-10;

                if (Math.Abs(fairNPV) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce null NPV with calculated fair upfront\n"
                        + "    calculated upfront: " + fairUpfront + "\n"
                        + "    calculated NPV:     " + fairNPV);
                }

                // same with null upfront to begin with
                upfront = 0.0;
                CreditDefaultSwap cds2 = new CreditDefaultSwap(Protection.Side.Seller, notional, upfront, fixedRate,
                                                               schedule, convention, dayCount, true, true);
                cds2.setPricingEngine(engine);

                fairUpfront = cds2.fairUpfront();

                CreditDefaultSwap fairCds2 = new CreditDefaultSwap(Protection.Side.Seller, notional,
                                                                   fairUpfront, fixedRate, schedule, convention, dayCount, true, true);
                fairCds2.setPricingEngine(engine);

                fairNPV = fairCds2.NPV();

                if (Math.Abs(fairNPV) > tolerance)
                {
                    Assert.Fail(
                        "Failed to reproduce null NPV with calculated fair upfront\n"
                        + "    calculated upfront: " + fairUpfront + "\n"
                        + "    calculated NPV:     " + fairNPV);
                }
            }
        }
Esempio n. 34
0
        public void ConsoleApplicationModuleWithXrmConnectionGenerateBatAndExecuteTest()
        {
            //this is done in the load.edit saved request form
            //a button is added the the saved request grid whiuch generates the .bat

            //so we need to save a request
            //then navigate to the save requests and trigger the generate bat button

            var testApplication = CreateThisApp();

            //set to no previously saved ones
            var savedRequests   = new SavedSettings();
            var settingsManager = testApplication.Controller.ResolveType <ISettingsManager>();

            settingsManager.SaveSettingsObject(savedRequests, typeof(TestSavedRequestWithXrmConnectionDialogRequest));

            //navigate to the request and populate the string field
            var entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>();
            var request   = new TestSavedRequestWithXrmConnectionDialogRequest()
            {
                SomeArbitraryString = nameof(TestSavedRequestWithXrmConnectionDialogRequest.SomeArbitraryString)
            };

            testApplication.EnterObject(request, entryForm);

            //trigger save request
            var saveRequestButton = entryForm.GetButton("SAVEREQUEST");

            saveRequestButton.Invoke();

            //enter and save details including autoload
            var saveRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);
            var detailsEntered  = new SaveAndLoadFields()
            {
                Name = "TestName"
            };

            testApplication.EnterAndSaveObject(detailsEntered, saveRequestForm);
            Assert.IsFalse(entryForm.ChildForms.Any());
            Assert.IsFalse(entryForm.LoadingViewModel.IsLoading);

            //reopen app/dialog
            testApplication = CreateThisApp();
            entryForm       = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>();

            //invoke load request dialog
            var loadRequestButton = entryForm.GetButton("LOADREQUEST");

            loadRequestButton.Invoke();
            var loadRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm);

            //verify there is a saved request and trigger the generate bat button
            var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests));

            Assert.IsTrue(subGrid.GridRecords.Count() == 1);
            subGrid.GridRecords.First().IsSelected = true;

            var generateBatButton = subGrid.DynamicGridViewModel.GetButton("GENERATEBAT");

            generateBatButton.Invoke();

            var testFiles = FileUtility.GetFiles(TestingFolder);

            Assert.AreEqual(1, testFiles.Count());
            Assert.IsTrue(testFiles.First().EndsWith(".bat"));

            var batContent = File.ReadAllText(testFiles.First());

            var args = ConsoleTestUtility.CommandLineToArgs(batContent)
                       .Skip(1)
                       .ToArray();

            var arguments       = ConsoleApplication.ParseCommandLineArguments(args);
            var applicationName = arguments.ContainsKey("SettingsFolderName") ? arguments["SettingsFolderName"] : "Unknown Console Context";

            //okay need to create app
            var dependencyResolver = new DependencyContainer();
            var controller         = new ConsoleApplicationController(applicationName, dependencyResolver);

            settingsManager = new DesktopSettingsManager(controller);
            var applicationOptions = new ApplicationOptionsViewModel(controller);
            var app = new ConsoleApplication(controller, applicationOptions, settingsManager);

            //load modules in folder path
            app.LoadModulesInExecutionFolder();

            //for this we will register saved connections in the console
            //in reality they would have been created on disk by the app and loaded by the module\

            //this was just debugging an invalid connection
            //var c1 = GetXrmRecordConfiguration();
            //var c2 = GetSavedXrmRecordConfiguration();
            //c1.Password = new Password("Nope", false, true);
            //c2.Password = new Password("Nope", false, true);
            //XrmConnectionModule.RefreshXrmServices(c1, app.Controller);
            //app.Controller.RegisterInstance<ISavedXrmConnections>(new SavedXrmConnections
            //{
            //    Connections = new[] { c2 }
            //});

            XrmConnectionModule.RefreshXrmServices(GetXrmRecordConfiguration(), app.Controller);
            app.Controller.RegisterInstance <ISavedXrmConnections>(new SavedXrmConnections
            {
                Connections = new[] { GetSavedXrmRecordConfiguration() }
            });

            //run app
            app.Run(args);
        }
Esempio n. 35
0
            // setup
            public CommonVars()
            {
                backup    = new SavedSettings();
                nominalUK = new RelinkableHandle <YieldTermStructure>();
                cpiUK     = new RelinkableHandle <ZeroInflationTermStructure>();
                hcpi      = new RelinkableHandle <ZeroInflationTermStructure>();
                zciisD    = new List <Date>();
                zciisR    = new List <double>();
                hii       = new RelinkableHandle <ZeroInflationIndex>();

                nominals = new InitializedList <double>(1, 1000000);
                // option variables
                frequency = Frequency.Annual;
                // usual setup
                volatility = 0.01;
                length     = 7;
                calendar   = new UnitedKingdom();
                convention = BusinessDayConvention.ModifiedFollowing;
                Date today = new Date(1, Month.June, 2010);

                evaluationDate = calendar.adjust(today);
                Settings.setEvaluationDate(evaluationDate);
                settlementDays = 0;
                fixingDays     = 0;
                settlement     = calendar.advance(today, settlementDays, TimeUnit.Days);
                startDate      = settlement;
                dcZCIIS        = new ActualActual();
                dcNominal      = new ActualActual();

                // uk rpi index
                //      fixing data
                Date     from        = new Date(1, Month.July, 2007);
                Date     to          = new Date(1, Month.June, 2010);
                Schedule rpiSchedule = new MakeSchedule().from(from).to(to)
                                       .withTenor(new Period(1, TimeUnit.Months))
                                       .withCalendar(new UnitedKingdom())
                                       .withConvention(BusinessDayConvention.ModifiedFollowing).value();

                double[] fixData =
                {
                    206.1, 207.3, 208.0, 208.9, 209.7, 210.9,
                    209.8, 211.4, 212.1, 214.0, 215.1, 216.8, //  2008
                    216.5, 217.2, 218.4, 217.7, 216.0, 212.9,
                    210.1, 211.4, 211.3, 211.5, 212.8, 213.4, //  2009
                    213.4, 214.4, 215.3, 216.0, 216.6, 218.0,
                    217.9, 219.2, 220.7, 222.8,  -999,  -999, //  2010
                    -999
                };

                // link from cpi index to cpi TS
                bool interp = false;// this MUST be false because the observation lag is only 2 months

                // for ZCIIS; but not for contract if the contract uses a bigger lag.
                ii = new UKRPI(interp, hcpi);
                for (int i = 0; i < rpiSchedule.Count; i++)
                {
                    ii.addFixing(rpiSchedule[i], fixData[i], true);// force overwrite in case multiple use
                }

                Datum[] nominalData =
                {
                    new Datum(new Date(2,  Month.June,      2010), 0.499997),
                    new Datum(new Date(3,  Month.June,      2010), 0.524992),
                    new Datum(new Date(8,  Month.June,      2010), 0.524974),
                    new Datum(new Date(15, Month.June,      2010), 0.549942),
                    new Datum(new Date(22, Month.June,      2010), 0.549913),
                    new Datum(new Date(1,  Month.July,      2010), 0.574864),
                    new Datum(new Date(2,  Month.August,    2010), 0.624668),
                    new Datum(new Date(1,  Month.September, 2010), 0.724338),
                    new Datum(new Date(16, Month.September, 2010), 0.769461),
                    new Datum(new Date(1,  Month.December,  2010), 0.997501),
                    //{ Date( 16, December, 2010), 0.838164 ),
                    new Datum(new Date(17, Month.March,     2011), 0.916996),
                    new Datum(new Date(16, Month.June,      2011), 0.984339),
                    new Datum(new Date(22, Month.September, 2011),  1.06085),
                    new Datum(new Date(22, Month.December,  2011), 1.141788),
                    new Datum(new Date(1,  Month.June,      2012), 1.504426),
                    new Datum(new Date(3,  Month.June,      2013),  1.92064),
                    new Datum(new Date(2,  Month.June,      2014), 2.290824),
                    new Datum(new Date(1,  Month.June,      2015), 2.614394),
                    new Datum(new Date(1,  Month.June,      2016), 2.887445),
                    new Datum(new Date(1,  Month.June,      2017), 3.122128),
                    new Datum(new Date(1,  Month.June,      2018), 3.322511),
                    new Datum(new Date(3,  Month.June,      2019), 3.483997),
                    new Datum(new Date(1,  Month.June,      2020), 3.616896),
                    new Datum(new Date(1,  Month.June,      2022),   3.8281),
                    new Datum(new Date(2,  Month.June,      2025),   4.0341),
                    new Datum(new Date(3,  Month.June,      2030), 4.070854),
                    new Datum(new Date(1,  Month.June,      2035), 4.023202),
                    new Datum(new Date(1,  Month.June,      2040), 3.954748),
                    new Datum(new Date(1,  Month.June,      2050), 3.870953),
                    new Datum(new Date(1,  Month.June,      2060),  3.85298),
                    new Datum(new Date(2,  Month.June,      2070), 3.757542),
                    new Datum(new Date(3,  Month.June,      2080), 3.651379)
                };
                int nominalDataLength = 33 - 1;

                List <Date>   nomD = new List <Date>();
                List <double> nomR = new List <double>();

                for (int i = 0; i < nominalDataLength; i++)
                {
                    nomD.Add(nominalData[i].date);
                    nomR.Add(nominalData[i].rate / 100.0);
                }
                YieldTermStructure nominalTS = new InterpolatedZeroCurve <Linear>(nomD, nomR, dcNominal);

                nominalUK.linkTo(nominalTS);

                // now build the zero inflation curve
                observationLag                   = new Period(2, TimeUnit.Months);
                contractObservationLag           = new Period(3, TimeUnit.Months);
                contractObservationInterpolation = InterpolationType.Flat;

                Datum[] zciisData =
                {
                    new Datum(new Date(1, Month.June, 2011), 3.087),
                    new Datum(new Date(1, Month.June, 2012),  3.12),
                    new Datum(new Date(1, Month.June, 2013), 3.059),
                    new Datum(new Date(1, Month.June, 2014),  3.11),
                    new Datum(new Date(1, Month.June, 2015),  3.15),
                    new Datum(new Date(1, Month.June, 2016), 3.207),
                    new Datum(new Date(1, Month.June, 2017), 3.253),
                    new Datum(new Date(1, Month.June, 2018), 3.288),
                    new Datum(new Date(1, Month.June, 2019), 3.314),
                    new Datum(new Date(1, Month.June, 2020), 3.401),
                    new Datum(new Date(1, Month.June, 2022), 3.458),
                    new Datum(new Date(1, Month.June, 2025),  3.52),
                    new Datum(new Date(1, Month.June, 2030), 3.655),
                    new Datum(new Date(1, Month.June, 2035), 3.668),
                    new Datum(new Date(1, Month.June, 2040), 3.695),
                    new Datum(new Date(1, Month.June, 2050), 3.634),
                    new Datum(new Date(1, Month.June, 2060), 3.629),
                };
                zciisDataLength = 17;
                for (int i = 0; i < zciisDataLength; i++)
                {
                    zciisD.Add(zciisData[i].date);
                    zciisR.Add(zciisData[i].rate);
                }

                // now build the helpers ...
                List <BootstrapHelper <ZeroInflationTermStructure> > helpers = makeHelpers(zciisData, zciisDataLength, ii,
                                                                                           observationLag, calendar, convention, dcZCIIS);

                // we can use historical or first ZCIIS for this
                // we know historical is WAY off market-implied, so use market implied flat.
                baseZeroRate = zciisData[0].rate / 100.0;
                PiecewiseZeroInflationCurve <Linear> pCPIts = new PiecewiseZeroInflationCurve <Linear>(
                    evaluationDate, calendar, dcZCIIS, observationLag, ii.frequency(), ii.interpolated(), baseZeroRate,
                    new Handle <YieldTermStructure>(nominalTS), helpers);

                pCPIts.recalculate();
                cpiUK.linkTo(pCPIts);
                hii.linkTo(ii);

                // make sure that the index has the latest zero inflation term structure
                hcpi.linkTo(pCPIts);

                // cpi CF price surf data
                Period[] cfMat = { new Period(3,  TimeUnit.Years),
                                   new Period(5,  TimeUnit.Years),
                                   new Period(7,  TimeUnit.Years),
                                   new Period(10, TimeUnit.Years),
                                   new Period(15, TimeUnit.Years),
                                   new Period(20, TimeUnit.Years),
                                   new Period(30, TimeUnit.Years) };
                double[] cStrike = { 3, 4, 5, 6 };
                double[] fStrike = { -1, 0, 1, 2 };
                int      ncStrikes = 4, nfStrikes = 4, ncfMaturities = 7;

                double[][] cPrice =
                {
                    new double[4] {
                        227.6, 100.27, 38.8, 14.94
                    },
                    new double[4] {
                        345.32, 127.9, 40.59, 14.11
                    },
                    new double[4] {
                        477.95, 170.19, 50.62, 16.88
                    },
                    new double[4] {
                        757.81, 303.95, 107.62, 43.61
                    },
                    new double[4] {
                        1140.73, 481.89, 168.4, 63.65
                    },
                    new double[4] {
                        1537.6, 607.72, 172.27, 54.87
                    },
                    new double[4] {
                        2211.67, 839.24, 184.75, 45.03
                    }
                };

                double[][] fPrice =
                {
                    new double[4] {
                        15.62, 28.38, 53.61, 104.6
                    },
                    new double[4] {
                        21.45, 36.73, 66.66, 129.6
                    },
                    new double[4] {
                        24.45, 42.08, 77.04, 152.24
                    },
                    new double[4] {
                        39.25, 63.52, 109.2, 203.44
                    },
                    new double[4] {
                        36.82, 63.62, 116.97, 232.73
                    },
                    new double[4] {
                        39.7, 67.47, 121.79, 238.56
                    },
                    new double[4] {
                        41.48, 73.9, 139.75, 286.75
                    }
                };

                // now load the data into vector and Matrix classes
                cStrikesUK     = new List <double>();
                fStrikesUK     = new List <double>();
                cfMaturitiesUK = new List <Period>();
                for (int i = 0; i < ncStrikes; i++)
                {
                    cStrikesUK.Add(cStrike[i]);
                }
                for (int i = 0; i < nfStrikes; i++)
                {
                    fStrikesUK.Add(fStrike[i]);
                }
                for (int i = 0; i < ncfMaturities; i++)
                {
                    cfMaturitiesUK.Add(cfMat[i]);
                }
                cPriceUK = new Matrix(ncStrikes, ncfMaturities);
                fPriceUK = new Matrix(nfStrikes, ncfMaturities);
                for (int i = 0; i < ncStrikes; i++)
                {
                    for (int j = 0; j < ncfMaturities; j++)
                    {
                        (cPriceUK)[i, j] = cPrice[j][i] / 10000.0;
                    }
                }
                for (int i = 0; i < nfStrikes; i++)
                {
                    for (int j = 0; j < ncfMaturities; j++)
                    {
                        (fPriceUK)[i, j] = fPrice[j][i] / 10000.0;
                    }
                }
            }
Esempio n. 36
0
        public T_Pathgenerator()
        {
       #endif

            backup = new SavedSettings();
        }
Esempio n. 37
0
            // setup
            public CommonVars()
            {
                backup = new SavedSettings();

                Calendar calendar = new TARGET();

                Date referenceDate = calendar.adjust(Date.Today);

                Settings.Instance.setEvaluationDate(referenceDate);

                termStructure = new RelinkableHandle <YieldTermStructure>();
                termStructure.linkTo(Utilities.flatRate(referenceDate, 0.05, new Actual365Fixed()));

                // ATM Volatility structure
                List <Period> atmOptionTenors = new List <Period>();

                atmOptionTenors.Add(new Period(1, TimeUnit.Months));
                atmOptionTenors.Add(new Period(6, TimeUnit.Months));
                atmOptionTenors.Add(new Period(1, TimeUnit.Years));
                atmOptionTenors.Add(new Period(5, TimeUnit.Years));
                atmOptionTenors.Add(new Period(10, TimeUnit.Years));
                atmOptionTenors.Add(new Period(30, TimeUnit.Years));

                List <Period> atmSwapTenors = new List <Period>();

                atmSwapTenors.Add(new Period(1, TimeUnit.Years));
                atmSwapTenors.Add(new Period(5, TimeUnit.Years));
                atmSwapTenors.Add(new Period(10, TimeUnit.Years));
                atmSwapTenors.Add(new Period(30, TimeUnit.Years));

                Matrix m = new Matrix(atmOptionTenors.Count, atmSwapTenors.Count);

                m[0, 0] = 0.1300; m[0, 1] = 0.1560; m[0, 2] = 0.1390; m[0, 3] = 0.1220;
                m[1, 0] = 0.1440; m[1, 1] = 0.1580; m[1, 2] = 0.1460; m[1, 3] = 0.1260;
                m[2, 0] = 0.1600; m[2, 1] = 0.1590; m[2, 2] = 0.1470; m[2, 3] = 0.1290;
                m[3, 0] = 0.1640; m[3, 1] = 0.1470; m[3, 2] = 0.1370; m[3, 3] = 0.1220;
                m[4, 0] = 0.1400; m[4, 1] = 0.1300; m[4, 2] = 0.1250; m[4, 3] = 0.1100;
                m[5, 0] = 0.1130; m[5, 1] = 0.1090; m[5, 2] = 0.1070; m[5, 3] = 0.0930;

                atmVol = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolatilityMatrix(calendar, BusinessDayConvention.Following, atmOptionTenors,
                                                 atmSwapTenors, m, new Actual365Fixed()));

                // Vol cubes
                List <Period> optionTenors = new List <Period>();

                optionTenors.Add(new Period(1, TimeUnit.Years));
                optionTenors.Add(new Period(10, TimeUnit.Years));
                optionTenors.Add(new Period(30, TimeUnit.Years));

                List <Period> swapTenors = new List <Period>();

                swapTenors.Add(new Period(2, TimeUnit.Years));
                swapTenors.Add(new Period(10, TimeUnit.Years));
                swapTenors.Add(new Period(30, TimeUnit.Years));

                List <double> strikeSpreads = new List <double>();

                strikeSpreads.Add(-0.020);
                strikeSpreads.Add(-0.005);
                strikeSpreads.Add(+0.000);
                strikeSpreads.Add(+0.005);
                strikeSpreads.Add(+0.020);

                int    nRows            = optionTenors.Count * swapTenors.Count;
                int    nCols            = strikeSpreads.Count;
                Matrix volSpreadsMatrix = new Matrix(nRows, nCols);

                volSpreadsMatrix[0, 0] = 0.0599;
                volSpreadsMatrix[0, 1] = 0.0049;
                volSpreadsMatrix[0, 2] = 0.0000;
                volSpreadsMatrix[0, 3] = -0.0001;
                volSpreadsMatrix[0, 4] = 0.0127;

                volSpreadsMatrix[1, 0] = 0.0729;
                volSpreadsMatrix[1, 1] = 0.0086;
                volSpreadsMatrix[1, 2] = 0.0000;
                volSpreadsMatrix[1, 3] = -0.0024;
                volSpreadsMatrix[1, 4] = 0.0098;

                volSpreadsMatrix[2, 0] = 0.0738;
                volSpreadsMatrix[2, 1] = 0.0102;
                volSpreadsMatrix[2, 2] = 0.0000;
                volSpreadsMatrix[2, 3] = -0.0039;
                volSpreadsMatrix[2, 4] = 0.0065;

                volSpreadsMatrix[3, 0] = 0.0465;
                volSpreadsMatrix[3, 1] = 0.0063;
                volSpreadsMatrix[3, 2] = 0.0000;
                volSpreadsMatrix[3, 3] = -0.0032;
                volSpreadsMatrix[3, 4] = -0.0010;

                volSpreadsMatrix[4, 0] = 0.0558;
                volSpreadsMatrix[4, 1] = 0.0084;
                volSpreadsMatrix[4, 2] = 0.0000;
                volSpreadsMatrix[4, 3] = -0.0050;
                volSpreadsMatrix[4, 4] = -0.0057;

                volSpreadsMatrix[5, 0] = 0.0576;
                volSpreadsMatrix[5, 1] = 0.0083;
                volSpreadsMatrix[5, 2] = 0.0000;
                volSpreadsMatrix[5, 3] = -0.0043;
                volSpreadsMatrix[5, 4] = -0.0014;

                volSpreadsMatrix[6, 0] = 0.0437;
                volSpreadsMatrix[6, 1] = 0.0059;
                volSpreadsMatrix[6, 2] = 0.0000;
                volSpreadsMatrix[6, 3] = -0.0030;
                volSpreadsMatrix[6, 4] = -0.0006;

                volSpreadsMatrix[7, 0] = 0.0533;
                volSpreadsMatrix[7, 1] = 0.0078;
                volSpreadsMatrix[7, 2] = 0.0000;
                volSpreadsMatrix[7, 3] = -0.0045;
                volSpreadsMatrix[7, 4] = -0.0046;

                volSpreadsMatrix[8, 0] = 0.0545;
                volSpreadsMatrix[8, 1] = 0.0079;
                volSpreadsMatrix[8, 2] = 0.0000;
                volSpreadsMatrix[8, 3] = -0.0042;
                volSpreadsMatrix[8, 4] = -0.0020;

                List <List <Handle <Quote> > > volSpreads = new InitializedList <List <Handle <Quote> > >(nRows);

                for (int i = 0; i < nRows; ++i)
                {
                    volSpreads[i] = new InitializedList <Handle <Quote> >(nCols);
                    for (int j = 0; j < nCols; ++j)
                    {
                        volSpreads[i][j] = new Handle <Quote>(new SimpleQuote(volSpreadsMatrix[i, j]));
                    }
                }

                iborIndex = new Euribor6M(termStructure);
                SwapIndex swapIndexBase      = new EuriborSwapIsdaFixA(new Period(10, TimeUnit.Years), termStructure);
                SwapIndex shortSwapIndexBase = new EuriborSwapIsdaFixA(new Period(2, TimeUnit.Years), termStructure);

                bool vegaWeightedSmileFit = false;

                SabrVolCube2 = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolCube2(atmVol,
                                         optionTenors,
                                         swapTenors,
                                         strikeSpreads,
                                         volSpreads,
                                         swapIndexBase,
                                         shortSwapIndexBase,
                                         vegaWeightedSmileFit));
                SabrVolCube2.link.enableExtrapolation();

                List <List <Handle <Quote> > > guess = new InitializedList <List <Handle <Quote> > >(nRows);

                for (int i = 0; i < nRows; ++i)
                {
                    guess[i]    = new InitializedList <Handle <Quote> >(4);
                    guess[i][0] = new Handle <Quote>(new SimpleQuote(0.2));
                    guess[i][1] = new Handle <Quote>(new SimpleQuote(0.5));
                    guess[i][2] = new Handle <Quote>(new SimpleQuote(0.4));
                    guess[i][3] = new Handle <Quote>(new SimpleQuote(0.0));
                }
                List <bool> isParameterFixed = new InitializedList <bool>(4, false);

                isParameterFixed[1] = true;

                // FIXME
                bool isAtmCalibrated = false;

                SabrVolCube1 = new Handle <SwaptionVolatilityStructure>(
                    new SwaptionVolCube1x(atmVol,
                                          optionTenors,
                                          swapTenors,
                                          strikeSpreads,
                                          volSpreads,
                                          swapIndexBase,
                                          shortSwapIndexBase,
                                          vegaWeightedSmileFit,
                                          guess,
                                          isParameterFixed,
                                          isAtmCalibrated));
                SabrVolCube1.link.enableExtrapolation();

                yieldCurveModels = new List <GFunctionFactory.YieldCurveModel>();
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.Standard);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.ExactYield);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.ParallelShifts);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.NonParallelShifts);
                yieldCurveModels.Add(GFunctionFactory.YieldCurveModel.NonParallelShifts); // for linear tsr model

                Handle <Quote> zeroMeanRev = new Handle <Quote>(new SimpleQuote(0.0));

                numericalPricers = new List <CmsCouponPricer>();
                analyticPricers  = new List <CmsCouponPricer>();
                for (int j = 0; j < yieldCurveModels.Count; ++j)
                {
                    if (j < yieldCurveModels.Count - 1)
                    {
                        numericalPricers.Add(new NumericHaganPricer(atmVol, yieldCurveModels[j], zeroMeanRev));
                    }
                    else
                    {
                        numericalPricers.Add(new LinearTsrPricer(atmVol, zeroMeanRev));
                    }

                    analyticPricers.Add(new AnalyticHaganPricer(atmVol, yieldCurveModels[j], zeroMeanRev));
                }
            }
Esempio n. 38
0
        public void testFdGreeks <Engine>() where Engine : IFDEngine, new()
        {
            using (SavedSettings backup = new SavedSettings())
            {
                Dictionary <string, double> calculated = new Dictionary <string, double>(),
                                            expected   = new Dictionary <string, double>(),
                                            tolerance  = new Dictionary <string, double>();

                tolerance.Add("delta", 7.0e-4);
                tolerance.Add("gamma", 2.0e-4);
                //tolerance["theta"]  = 1.0e-4;

                Option.Type[] types       = new Option.Type[] { Option.Type.Call, Option.Type.Put };
                double[]      strikes     = { 50.0, 99.5, 100.0, 100.5, 150.0 };
                double[]      underlyings = { 100.0 };
                double[]      qRates      = { 0.04, 0.05, 0.06 };
                double[]      rRates      = { 0.01, 0.05, 0.15 };
                int[]         years       = { 1, 2 };
                double[]      vols        = { 0.11, 0.50, 1.20 };

                Date today = Date.Today;
                Settings.setEvaluationDate(today);

                DayCounter         dc    = new Actual360();
                SimpleQuote        spot  = new SimpleQuote(0.0);
                SimpleQuote        qRate = new SimpleQuote(0.0);
                YieldTermStructure qTS   = Utilities.flatRate(today, qRate, dc);

                SimpleQuote           rRate = new SimpleQuote(0.0);
                YieldTermStructure    rTS   = Utilities.flatRate(today, rRate, dc);
                SimpleQuote           vol   = new SimpleQuote(0.0);
                BlackVolTermStructure volTS = Utilities.flatVol(today, vol, dc);

                for (int i = 0; i < types.Length; i++)
                {
                    for (int j = 0; j < strikes.Length; j++)
                    {
                        for (int k = 0; k < years.Length; k++)
                        {
                            Date                      exDate       = today + new Period(years[k], TimeUnit.Years);
                            Exercise                  exercise     = new AmericanExercise(today, exDate);
                            StrikedTypePayoff         payoff       = new PlainVanillaPayoff(types[i], strikes[j]);
                            BlackScholesMertonProcess stochProcess = new BlackScholesMertonProcess(new Handle <Quote>(spot),
                                                                                                   new Handle <YieldTermStructure>(qTS),
                                                                                                   new Handle <YieldTermStructure>(rTS),
                                                                                                   new Handle <BlackVolTermStructure>(volTS));

                            IPricingEngine engine = new Engine().factory(stochProcess);

                            VanillaOption option = new VanillaOption(payoff, exercise);
                            option.setPricingEngine(engine);

                            for (int l = 0; l < underlyings.Length; l++)
                            {
                                for (int m = 0; m < qRates.Length; m++)
                                {
                                    for (int n = 0; n < rRates.Length; n++)
                                    {
                                        for (int p = 0; p < vols.Length; p++)
                                        {
                                            double u = underlyings[l];
                                            double q = qRates[m],
                                                   r = rRates[n];
                                            double v = vols[p];
                                            spot.setValue(u);
                                            qRate.setValue(q);
                                            rRate.setValue(r);
                                            vol.setValue(v);

                                            double value = option.NPV();
                                            calculated.Add("delta", option.delta());
                                            calculated.Add("gamma", option.gamma());
                                            //calculated["theta"]  = option.theta();

                                            if (value > spot.value() * 1.0e-5)
                                            {
                                                // perturb spot and get delta and gamma
                                                double du = u * 1.0e-4;
                                                spot.setValue(u + du);
                                                double value_p = option.NPV(),
                                                       delta_p = option.delta();
                                                spot.setValue(u - du);
                                                double value_m = option.NPV(),
                                                       delta_m = option.delta();
                                                spot.setValue(u);
                                                expected.Add("delta", (value_p - value_m) / (2 * du));
                                                expected.Add("gamma", (delta_p - delta_m) / (2 * du));

                                                /*
                                                 * // perturb date and get theta
                                                 * Time dT = dc.yearFraction(today-1, today+1);
                                                 * Settings::instance().setEvaluationDate(today-1);
                                                 * value_m = option.NPV();
                                                 * Settings::instance().setEvaluationDate(today+1);
                                                 * value_p = option.NPV();
                                                 * Settings::instance().setEvaluationDate(today);
                                                 * expected["theta"] = (value_p - value_m)/dT;
                                                 */

                                                // compare
                                                foreach (string greek in calculated.Keys)
                                                {
                                                    double expct      = expected[greek],
                                                                calcl = calculated[greek],
                                                                tol   = tolerance[greek];
                                                    double error      = Utilities.relativeError(expct, calcl, u);
                                                    if (error > tol)
                                                    {
                                                        REPORT_FAILURE(greek, payoff, exercise,
                                                                       u, q, r, today, v,
                                                                       expct, calcl, error, tol);
                                                    }
                                                }
                                            }
                                            calculated.Clear();
                                            expected.Clear();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 39
0
   public T_TermStructures()
   {
 #endif
       backup = new SavedSettings();
   }
Esempio n. 40
0
 void Start()
 {
     clothesSettings = Data.Instance.clothesSettings;
     savedSettings = Data.Instance.savedSettings;
     AddPlayers();
 }