public AffineDivCurveUtils(DividendQuote[] dividends,
                                   DiscountCurve discountCurve,
                                   ITimeMeasure time)
        {
            Contract.Requires(EnumerableUtils.IsSorted(dividends.Select(div => div.Date)));

            if (dividends.Length > 0)
            {
                double[] divDates         = dividends.Map(div => time[div.Date]);
                double[] spotYieldGrowths = dividends.Scan(1.0, (prev, div) => prev * (1.0 - div.Yield));
                var      spotYieldGrowth  = new StepFunction(divDates, spotYieldGrowths, 1.0);
                assetGrowth = t => spotYieldGrowth.Eval(t) / discountCurve.Zc(t);

                double[] discountedCashs = dividends.Map(div => div.Cash / assetGrowth(time[div.Date]));
                double[] cashBpvs        = discountedCashs.Scan(0.0, (prev, c) => prev + c);
                cashDivBpv      = new StepFunction(divDates, cashBpvs, 0.0);
                cashBpvIntegral = cashDivBpv.Integral(0.0);

                double[] squareTimeWeightedCashs = discountedCashs.ZipWith(divDates, (c, t) => c * t * t);
                squareTimeWeightedCash = new StepFunction(divDates, squareTimeWeightedCashs, 0.0);
            }
            else
            {
                assetGrowth     = t => 1.0 / discountCurve.Zc(t);
                cashDivBpv      = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN);
                cashBpvIntegral = RrFunctions.Zero;

                squareTimeWeightedCash = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN);
            }
        }
        public static BlackScholesWithDividendOption Build(double spot,
                                                           DividendQuote[] dividends,
                                                           DiscountCurve discountCurve,
                                                           ITimeMeasure time)
        {
            var divUtils = new AffineDivCurveUtils(dividends, discountCurve, time);

            return(new BlackScholesWithDividendOption(spot, divUtils));
        }
Example #3
0
        private void visualizerButton_Click(object sender, RoutedEventArgs e)
        {
            YieldCurve yc = ((PricingRequestWithResult)requestsListBox.SelectedItem).Request.Ycs.get();

            DiscountCurve dc = (DiscountCurve)yc;
            //IProcess hwp = new HullWhiteCalibrator().Calibrate(dc);
            IProcess rsp = RSCalibrator.Calibrate(dc);
            //var visualizerWindow1 = new ProcessVisualizer(yc, hwp);
            var visualizerWindow2 = new ProcessVisualizer(yc, rsp);

            visualizerWindow2.Show();
        }
        private static Market Market()
        {
            var refDate = DateTime.Parse("07/06/2009");
            var time    = TimeMeasure.Act365(refDate);
            var pillars = new[] { refDate + Duration.Year, refDate + 2 * Duration.Year, refDate + 3 * Duration.Year, refDate + 5 * Duration.Year };
            var zcRates = new[] { 0.0010, 0.003, 0.005, 0.008 };
            var zcs     = zcRates.Select((r, i) => Math.Exp(-time[pillars[i]] * r)).ToArray();

            DiscountCurve discountCurve = DiscountCurve.LinearRateInterpol(
                FinancingId.RiskFree(Currency.Eur),
                pillars, zcs, time);
            var market = new Market(new[] { discountCurve }, new AssetMarket[0]);

            return(market);
        }
        public static object Discount(object mktObj, object[,] dates, string curveId)
        {
            return(FunctionRunnerUtils.Run("Discount", () =>
            {
                var market = MarketManager.Instance.GetMarket(mktObj);
                var finCurveId = FinancingId.Parse(curveId);
                DiscountCurve curve = market.DiscountCurve(finCurveId);

                var result = dates.Map(o =>
                {
                    var dateOrDuration = DateAndDurationConverter.ConvertDateOrDuration(o);
                    var date = dateOrDuration.ToDate(curve.RefDate);
                    return curve.Zc(date);
                });

                return result;
            }));
        }
Example #6
0
        private static AssetMarket[] ProcessAssetMkt(object[,] bag, DateTime refDate, DiscountCurve[] discountCurves)
        {
            var eqtyTime      = TimeMeasure.Act365(refDate);
            var assetRawDatas = bag.ProcessLabelledMatrix("Asset", o => o.ToString(), o => o.ToString(), o => o);

            TimeMatrixDatas repoRawDatas = bag.ProcessTimeMatrixDatas("Repo");
            var             repoPillars  = repoRawDatas.RowLabels
                                           .Select(dOrDur => dOrDur.ToDate(refDate)).ToArray();

            var assetMkts = new List <AssetMarket>();

            for (int i = 0; i < assetRawDatas.RowLabels.Length; i++)
            {
                var    assetName   = assetRawDatas.RowLabels[i];
                var    rawCurrency = assetRawDatas.GetColFromLabel("Currency")[i].ToString();
                object rawSpot     = assetRawDatas.GetColFromLabel("Spot")[i];

                var currency = Currency.Parse(rawCurrency);
                var assetId  = new AssetId(assetName, currency);

                double spot;
                if (!NumberConverter.TryConvertDouble(rawSpot, out spot))
                {
                    throw new ArgumentException(String.Format("AssetMarketFactory, invalid {0} spot : {1}", assetName, rawSpot));
                }

                double[] repoRates = repoRawDatas.GetColFromLabel(assetName);
                var      repoZcs   = repoRates.Select((r, idx) => Math.Exp(-eqtyTime[repoPillars[idx]] * r)).ToArray();
                var      repoCurve = DiscountCurve.LinearRateInterpol(FinancingId.AssetCollat(assetId), repoPillars, repoZcs, eqtyTime);

                var divQuotes = ProcessDiv(bag, refDate, assetName);
                var volMatrix = AssetVolMatrix(bag, eqtyTime, assetName);

                var riskFreeDiscount = discountCurves.Single(curve => curve.Financing.Equals(FinancingId.RiskFree(currency)));

                var mkt = new AssetMarket(assetId, refDate, eqtyTime,
                                          spot, riskFreeDiscount, repoCurve,
                                          divQuotes, volMatrix);
                assetMkts.Add(mkt);
            }

            return(assetMkts.ToArray());
        }
Example #7
0
        protected override IProcessPathGenerator Build(LocalVolatilityModel model, Market market, PaymentInfo probaMeasure, DateTime[] simulatedDates)
        {
            var asset    = model.Asset;
            var assetMkt = market.AssetMarket(asset);

            if (!probaMeasure.Financing.Currency.Equals(probaMeasure.Currency) ||
                !probaMeasure.Currency.Equals(asset.Currency))
            {
                throw new NotImplementedException("TODO !");
            }

            var           numeraireDiscount = market.DiscountCurve(probaMeasure.Financing);
            DiscountCurve assetDiscount     = assetMkt.AssetFinancingCurve(numeraireDiscount);
            double        forward           = assetMkt.Spot / assetDiscount.Zc(probaMeasure.Date);

            LocalVolSimulatorStepDatas[] stepSimulDatas = EnumerableUtils.For(0, simulatedDates.Length,
                                                                              i => StepSimulDatas(i > 0 ? simulatedDates[i - 1] : market.RefDate, simulatedDates[i],
                                                                                                  model, assetDiscount, probaMeasure.Date));

            return(new LocalVolEquityPathGenerator(stepSimulDatas, forward));
        }
Example #8
0
        private static DiscountCurve[] RateCurveFromRawDatas(TimeMatrixDatas curveRawDatas, DateTime refDate)
        {
            var rateTimeInterpol = RateTimeMeasure(refDate);

            DateTime[] datePillars = curveRawDatas.RowLabels
                                     .Select(dOrDur => dOrDur.ToDate(refDate)).ToArray();

            var curves = new List <DiscountCurve>();

            foreach (var curveLabel in curveRawDatas.ColLabels)
            {
                FinancingId financingId;
                if (!FinancingId.TryParse(curveLabel, out financingId))
                {
                    throw new ArgumentException(String.Format("RateMarketFactory, invalid Discount Curve Id : {0}", curveLabel));
                }

                double[] zcs           = curveRawDatas.GetColFromLabel(curveLabel);
                var      discountCurve = DiscountCurve.LinearRateInterpol(financingId, datePillars, zcs, rateTimeInterpol);

                curves.Add(discountCurve);
            }
            return(curves.ToArray());
        }
Example #9
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(DiscountCurve obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
        /// <summary>
        /// Calculates the specified model data.
        /// </summary>
        /// <param name="modelData">The model data.</param>
        /// <returns></returns>
        public override BasicAssetValuation Calculate(IAssetControllerData modelData)
        {
            ModelData = modelData;
            switch (ModelIdentifier)
            {
            case "CapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;

            case "DiscountCapAsset":
                AnalyticsModel = new RateOptionAssetAnalytic();
                break;
            }
            var metrics = MetricsHelper.GetMetricsToEvaluate(Metrics, AnalyticsModel.Metrics);
            // Determine if DFAM has been requested - if so thats all we evaluate - every other metric is ignored
            var bEvalLastForewardVolatiltiy = false;

            if (metrics.Contains(RateOptionMetrics.VolatilityAtExpiry))
            {
                bEvalLastForewardVolatiltiy = true;
                metrics.RemoveAll(
                    metricItem => metricItem != RateOptionMetrics.VolatilityAtExpiry);
            }
            var metricsToEvaluate = metrics.ToArray();
            IRateOptionAssetParameters analyticModelParameters = new RateOptionAssetParameters();

            AnalyticResults = new RateOptionAssetResults();
            var marketEnvironment = modelData.MarketEnvironment;

            //1. instantiate curve
            if (marketEnvironment.GetType() == typeof(SimpleMarketEnvironment))
            {
                DiscountCurve     = (IRateCurve)((ISimpleMarketEnvironment)marketEnvironment).GetPricingStructure();
                DiscountCurveName = DiscountCurve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurve     = DiscountCurve;
                ForecastCurveName = DiscountCurveName;
                var volatilities = CreateList((double)Volatility, TimesToExpiry.Count);
                analyticModelParameters.Volatilities = volatilities;
            }
            if (marketEnvironment.GetType() == typeof(SwapLegEnvironment))
            {
                DiscountCurve       = ((ISwapLegEnvironment)marketEnvironment).GetDiscountRateCurve();
                DiscountCurveName   = DiscountCurve.GetPricingStructureId().UniqueIdentifier;
                ForecastCurve       = ((ISwapLegEnvironment)marketEnvironment).GetForecastRateCurve();
                ForecastCurveName   = ForecastCurve.GetPricingStructureId().UniqueIdentifier;
                VolatilityCurve     = ((ISwapLegEnvironment)marketEnvironment).GetVolatilitySurface();
                VolatilityCurveName = VolatilityCurve.GetPricingStructureId().UniqueIdentifier;
                analyticModelParameters.Volatilities = GetVolatilties(VolatilityCurve, TimesToExpiry, Strikes);
            }
            if (marketEnvironment.GetType() == typeof(MarketEnvironment))
            {
                if (DiscountCurveName != null)
                {
                    DiscountCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(DiscountCurveName);
                }
                if (ForecastCurveName != null)
                {
                    ForecastCurve = (IRateCurve)modelData.MarketEnvironment.GetPricingStructure(ForecastCurveName);
                }
                if (VolatilityCurveName != null)
                {
                    VolatilityCurve = (IVolatilitySurface)modelData.MarketEnvironment.GetPricingStructure(VolatilityCurveName);
                }
                analyticModelParameters.Volatilities = GetVolatilties(VolatilityCurve, TimesToExpiry, Strikes);
            }
            analyticModelParameters.FlatVolatility = Volatility;
            //2. Set the premium
            if (Premium == null)
            {
                Premium = CalculatePremium();
            }
            if (Premium != null)
            {
                analyticModelParameters.Premium = (double)Premium;
            }
            if (bEvalLastForewardVolatiltiy)
            {
                //3. Set the start diccount factor and vol.
                analyticModelParameters.PremiumPaymentDiscountFactor =
                    GetDiscountFactor(DiscountCurve, AdjustedStartDate, modelData.ValuationDate);
                //4. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                               metricsToEvaluate);
            }
            else
            {
                analyticModelParameters.IsDiscounted = false;
                analyticModelParameters.IsPut        = !IsCap;
                analyticModelParameters.Notionals    = Notionals;
                analyticModelParameters.ForwardRates = ResetRates;
                //2. Get the discount factors
                analyticModelParameters.PaymentDiscountFactors =
                    GetDiscountFactors(DiscountCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                analyticModelParameters.ForecastDiscountFactors =
                    GetDiscountFactors(ForecastCurve, AdjustedPeriodDates.ToArray(), modelData.ValuationDate);
                //3. Get the respective year fractions
                analyticModelParameters.YearFractions = GetYearFractions();
                analyticModelParameters.Strikes       = Strikes;
                analyticModelParameters.Rate          = (double)CalculateImpliedParRate(modelData.ValuationDate);
                analyticModelParameters.TimesToExpiry = TimesToExpiry;
                //5. Set the anaytic input parameters and Calculate the respective metrics
                AnalyticResults =
                    AnalyticsModel.Calculate <IRateOptionAssetResults, RateOptionAssetResults>(analyticModelParameters,
                                                                                               metricsToEvaluate);
            }
            return(GetValue(AnalyticResults));
        }
Example #11
0
 public EquitySpotRepresentation(AssetId asset, DiscountCurve assetDiscountCurve, PaymentInfo probaMeasure)
 {
     this.assetDiscountCurve = assetDiscountCurve;
     this.probaMeasure       = probaMeasure;
     Asset = asset;
 }
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(DiscountCurve obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Example #13
0
        private LocalVolSimulatorStepDatas StepSimulDatas(DateTime start, DateTime end, LocalVolatilityModel model, DiscountCurve assetDiscount, DateTime horizon)
        {
            DateTime[] dates;
            bool[]     isDivDate;
            DiscreteLocalDividend[] dividends;
            StepSchedule(start, end, model, out dates, out isDivDate, out dividends);

            var horizonDiscount = assetDiscount.Zc(horizon);
            var discounts       = dividends.Map(div => horizonDiscount / assetDiscount.Zc(div.Date));

            var localVols = EnumerableUtils.For(0, dates.Length,
                                                i => StepLocalVol(i > 0 ? dates[i - 1] : start, dates[i], model));

            var step = RealInterval.Compact(model.Time[start], model.Time[end]);

            return(new LocalVolSimulatorStepDatas(step, dates.Map(d => model.Time[d]), isDivDate, dividends, discounts, localVols));
        }
        private void generatePlot()
        {
            dc      = (DiscountCurve)QuandlDataProvider.Instance.GetYieldCurve();
            process = RSCalibrator.Calibrate(dc);

            //ZBP1/////////////////////////////////////////////////////////
            Bond b = new Bond()
            {
                FaceValue = 1, Maturity = 1, Rate = 0.0, Coupon = CouponPaymentType.None
            };

            double[] bondPrices1 = BondPrices(b);

            var bond1 = AvgConvergencePlot(bondPrices1);

            double b1base    = dc[1.0];
            var    bond1base = new List <DataPoint>();

            bond1base.Add(new DataPoint(1, b1base));
            bond1base.Add(new DataPoint(n, b1base));

            var bond1error = bond1.Select(p => new DataPoint(p.X, Math.Abs(p.Y - b1base) / b1base * 100)).ToList();
            /////////////////////////////////////////////////////////////

            //ZBP10/////////////////////////////////////////////////////////
            Bond b2 = new Bond()
            {
                FaceValue = 1, Maturity = 10, Rate = 0.0, Coupon = CouponPaymentType.None
            };

            double[] bondPrices2 = BondPrices(b2);

            var bond2 = AvgConvergencePlot(bondPrices2);

            double b2base    = dc[10.0];
            var    bond2base = new List <DataPoint>();

            bond2base.Add(new DataPoint(1, b2base));
            bond2base.Add(new DataPoint(n, b2base));

            var bond2error = bond2.Select(p => new DataPoint(p.X, Math.Abs(p.Y - b2base) / b2base * 100)).ToList();
            /////////////////////////////////////////////////////////////


            Bond b3 = new Bond()
            {
                FaceValue = 1, Maturity = 5, Rate = 0.02, Coupon = CouponPaymentType.Annual
            };
            var bond = AvgConvergencePlot(BondPrices(b3));

            BondOption bo = new BondOption()
            {
                ExecutionTime = 3, StrikePrice = 0.8, Type = BondOption.OptionType.Call, UnderlyingBond = b3
            };
            var bondoption = AvgConvergencePlot(BondOptionPrices(bo));

            Swap sw = new Swap()
            {
                FaceValue = 1, Maturity = 5, Rate = 0.02, Coupon = CouponPaymentType.Annual, Type = Swap.SwapType.Receiver
            };
            var swap = AvgConvergencePlot(SwapPrices(sw));

            Swaption swo = new Swaption()
            {
                ExecutionTime = 3, UnderlyingSwap = sw
            };
            var swaption = AvgConvergencePlot(SwaptionPrices(swo));

            /////////////////////////////////////////////////////////////////

            Bond b4 = new Bond()
            {
                FaceValue = 1, Maturity = 5, Rate = 0.002, Coupon = CouponPaymentType.Annual
            };
            BondOption bo2 = new BondOption()
            {
                ExecutionTime = 3, Type = BondOption.OptionType.Call, UnderlyingBond = b3
            };

            var boladder = new List <DataPoint>();
            //for (double sp = 0.9; sp < 1.0; sp += 0.005)
            //{
            //    bo2.StrikePrice = sp;
            //    double price = BondOptionPrices(bo2).Average();
            //    boladder.Add(new DataPoint(sp, price));

            //}

            //WIENER////

            WienerProcess wp = new WienerProcess(0, 1);

            double t  = -1;
            var    w1 = new List <DataPoint>(wp.generatePathFrom(new WienerProcess.State(0), 0, 1, 100).Select(fx => new DataPoint(t += 1, fx.r)));

            t = -1;
            var w2 = new List <DataPoint>(wp.generatePathFrom(new WienerProcess.State(0), 0, 1, 100).Select(fx => new DataPoint(t += 1, fx.r)));

            t = -1;
            var w3 = new List <DataPoint>(wp.generatePathFrom(new WienerProcess.State(0), 0, 1, 100).Select(fx => new DataPoint(t += 1, fx.r)));

            t = -1;
            var w4 = new List <DataPoint>(wp.generatePathFrom(new WienerProcess.State(0), 0, 1, 100).Select(fx => new DataPoint(t += 1, fx.r)));

            t = -1;
            var w5 = new List <DataPoint>(wp.generatePathFrom(new WienerProcess.State(0), 0, 1, 100).Select(fx => new DataPoint(t += 1, fx.r)));
            //////////

            ////GAUSS///////

            Func <double, double, double, double> nrd = (nu, sigma, x) => {
                return(1.0 / Math.Sqrt(2 * Math.PI * sigma * sigma) * Math.Exp(-(x - nu) * (x - nu) / (2 * sigma * sigma)));
            };

            var nrd1 = new List <DataPoint>();
            var nrd2 = new List <DataPoint>();
            var nrd3 = new List <DataPoint>();
            var nrd4 = new List <DataPoint>();

            for (double x = -5; x < 5; x += 0.05)
            {
                nrd1.Add(new DataPoint(x, nrd(0, 1, x)));
                nrd2.Add(new DataPoint(x, nrd(0, 0.5, x)));
                nrd3.Add(new DataPoint(x, nrd(0, 0.1, x)));
                nrd4.Add(new DataPoint(x, nrd(-2, 0.4, x)));
            }

            ////////////////

            this.DataContext = new
            {
                bond1      = bond1,
                bond1base  = bond1base,
                bond1error = bond1error,
                bond2      = bond2,
                bond2base  = bond2base,
                bond2error = bond2error,
                bond       = bond,
                bondoption = bondoption,
                swap       = swap,
                swaption   = swaption,
                boladder   = boladder,
                w1         = w1,
                w2         = w2,
                w3         = w3,
                w4         = w4,
                w5         = w5,
                nrd1       = nrd1,
                nrd2       = nrd2,
                nrd3       = nrd3,
                nrd4       = nrd4
            };
        }
        private BsEqtySimulatorStepDatas StepSimulDatas(DateTime start, DateTime end, BlackScholesModel model, DiscountCurve assetDiscount, DateTime horizon)
        {
            DiscreteLocalDividend[] stepDividends = model.Dividends
                                                    .Where(div => start < div.Date && div.Date <= end)
                                                    .OrderBy(div => div.Date)
                                                    .ToArray();
            //If step end date is not a div date, we insert a fictious zero dividend
            if (!(stepDividends.Any() && end.Equals(stepDividends.Last().Date)))
            {
                stepDividends = stepDividends.Union(new[] { DiscreteLocalDividend.ZeroDiv(end) }).ToArray();
            }

            var variance      = (model.Sigma * model.Sigma).Integral(0.0);
            var stepVols      = new double[stepDividends.Length];
            var stepVarDrifts = new double[stepDividends.Length];

            for (int i = 0; i < stepDividends.Length; i++)
            {
                var subStepStart = i > 0 ? stepDividends[i - 1].Date : start;
                var subStepEnd   = stepDividends[i].Date;

                var subStep      = RealInterval.Compact(model.Time[subStepStart], model.Time[subStepEnd]);
                var stepVariance = variance.Eval(subStep.Sup) - variance.Eval(subStep.Inf);
                var stepVarDrift = -0.5 * stepVariance;

                stepVols[i]      = Math.Sqrt(stepVariance / subStep.Length);
                stepVarDrifts[i] = stepVarDrift;
            }

            var horizonDiscount = assetDiscount.Zc(horizon);
            var discounts       = stepDividends.Map(div => horizonDiscount / assetDiscount.Zc(div.Date));

            var dates = model.Time[stepDividends.Map(div => div.Date)];
            var step  = RealInterval.Compact(model.Time[start], model.Time[end]);

            return(new BsEqtySimulatorStepDatas(step, dates, stepDividends, discounts, stepVols, stepVarDrifts));
        }
Example #16
0
 public double P0(double T) => DiscountCurve.GetDf(DiscountCurve.BuildDate, DateExtensions.AddYearFraction(DiscountCurve.BuildDate, T, DayCountBasis));