Exemplo n.º 1
0
        /// <summary>
        /// Create a surface from an FpML
        /// </summary>
        /// <param name="fpmlData"></param>
        public VolatilitySurface(Pair <PricingStructure, PricingStructureValuation> fpmlData)
        {
            IDayCounter dc         = Actual365.Instance;
            var         termPoints = new List <TermPoint>
            {
                TermPointFactory.Create(1.0m, new DateTime()),
                TermPointFactory.Create(0.99m, new DateTime().AddDays(10)),
                TermPointFactory.Create(0.97m, new DateTime().AddDays(100))
            };
            var termCurve = TermCurve.Create(new DateTime(), new InterpolationMethod {
                Value = "LinearInterpolation"
            }, true, termPoints);

            Interpolator = new TermCurveInterpolator(termCurve, new DateTime(), dc);//TODO need to create a surfaceinterpolator.
            _algorithm   = "Linear";
            SetFpMLData(fpmlData);
//            var holder = new PricingStructureAlgorithmsHolder();
            bool doBuild = GetVolatilityMatrix().dataPoints.point == null;

            if (doBuild)
            {
                //               var bootstrapperName = holder.GetValue(PricingStructureType.RateVolatilityMatrix, _algorithm, "Bootstrapper");

                //               Bootstrapper = Bootstrap(bootstrapperName, PricingStructure, PricingStructureValuation);
            }

            //           SetInterpolator(PricingStructureValuation.baseDate.Value, _algorithm, holder);
            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            ProcessVolatilityRepresentation();
        }
Exemplo n.º 2
0
        private static TermCurve  Load(TermCurve termCurve, DateTime[] rbaDates, DateTime baseDate, IDayCounter dayCounter)
        {
            var points  = new List <TermPoint>(termCurve.point);
            var counter = 0;

            foreach (var point in termCurve.point)
            {
                var date  = (DateTime)point.term.Items[0];
                var dates = rbaDates.Where(t => GetPreviousIndex(termCurve, t) == counter).ToList();
                foreach (var rbAdate in dates)
                {
                    if (dates.IndexOf(rbAdate) == 1)
                    {
                        var termPoint =
                            TermPointFactory.Create(InterpolateRate(termCurve, baseDate, dayCounter, dates[0]), dates[0]);
                        points.Insert(GetPreviousIndex(termCurve, date), termPoint);
                    }
                    else
                    {
                        var termPoint =
                            TermPointFactory.Create(InterpolateRate2(termCurve, baseDate, dayCounter, rbAdate), rbAdate);
                        points.Insert(GetPreviousIndex(termCurve, date), termPoint);
                    }
                }
                counter++;
            }
            return(termCurve);
        }
Exemplo n.º 3
0
        //  need a based date?
        //
        ///<summary>
        ///</summary>
        ///<param name="discountCurve"></param>
        ///<param name="baseDate"></param>
        ///<param name="frequency"></param>
        ///<param name="dayCounter"></param>
        ///<returns></returns>
        ///<exception cref="System.Exception"></exception>
        public static TermCurve ToZeroCurve(TermCurve discountCurve, DateTime baseDate,
                                            CompoundingFrequencyEnum frequency, IDayCounter dayCounter)
        {
            TermCurve result = TermCurve.Create(new List <TermPoint>());

            foreach (TermPoint point in discountCurve.point)
            {
                DateTime pointDate = XsdClassesFieldResolver.TimeDimensionGetDate(point.term);
                double   zeroRateDouble;
                if (baseDate != pointDate)
                {
                    double time = dayCounter.YearFraction(baseDate, pointDate);
                    zeroRateDouble = RateAnalytics.DiscountFactorToZeroRate((double)point.mid, time, frequency);
                }
                else
                {
                    // set after the loop
                    zeroRateDouble = 0;
                }
                TermPoint zeroPoint = TermPointFactory.Create(Convert.ToDecimal(zeroRateDouble), pointDate);
                zeroPoint.id = point.id;
                result.Add(zeroPoint);
            }
            if (result.point[0].mid == 0)
            {
                result.point[0].mid = result.point[1].mid;
            }
            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// </summary>
        /// <param name="discountCurve"></param>
        /// <param name="tenor"></param>
        /// <param name="baseDate"></param>
        /// <param name="interpolatedCurve"></param>
        /// <param name="paymentCalendar"></param>
        /// <param name="dayCounter"></param>
        /// <returns></returns>
        /// <exception cref="System.Exception"></exception>
        public static TermCurve ToForwardCurve(TermCurve discountCurve, Period tenor, DateTime baseDate,
                                               InterpolatedCurve interpolatedCurve, IBusinessCalendar paymentCalendar, IDayCounter dayCounter)
        {
            TermCurve result = TermCurve.Create(new List <TermPoint>());
            var       length = discountCurve.point.Length;
            var       offset = new Offset
            {
                dayType          = DayTypeEnum.Calendar,
                dayTypeSpecified = true,
                period           = tenor.period,
                periodMultiplier = tenor.periodMultiplier,
                periodSpecified  = true
            };

            if (paymentCalendar == null)
            {
                return(result);
            }
            for (int i = 0; i < length - 1; i++) //This will only go to the penultimate point. Extrapolation required for more.
            {
                var      pointStart        = discountCurve.point[i];
                DateTime startDate         = XsdClassesFieldResolver.TimeDimensionGetDate(pointStart.term);
                var      endDate           = paymentCalendar.Advance(startDate, offset, BusinessDayConventionEnum.FOLLOWING);
                var      endPoint          = new DateTimePoint1D(baseDate, endDate);
                var      endDF             = interpolatedCurve.Value(endPoint);
                double   time              = dayCounter.YearFraction(startDate, endDate);
                var      forwardRateDouble =
                    RateAnalytics.DiscountFactorsToForwardRate((double)pointStart.mid, endDF, time);
                TermPoint forwardPoint = TermPointFactory.Create(Convert.ToDecimal(forwardRateDouble), startDate);
                forwardPoint.id = tenor.id;
                result.Add(forwardPoint);
            }
            return(result);
        }
Exemplo n.º 5
0
 ///<summary>
 /// Creates a term point array.
 ///</summary>
 ///<param name="dates"></param>
 ///<param name="discountFactors"></param>
 ///<returns></returns>
 public static TermPoint[] Create(IList <DateTime> dates, IList <decimal> discountFactors)
 {
     if (dates.Count != discountFactors.Count)
     {
         throw new ArgumentException(string.Format(TermPointConstructorArgumentError, dates.Count, discountFactors.Count));
     }
     return(dates.Select((t, i) => TermPointFactory.Create(discountFactors[i], t)).ToArray());
 }
Exemplo n.º 6
0
        ///<summary>
        /// Creates a term point array.
        ///</summary>
        public static TermPoint[] Create(IList <TimeDimension> timeDimensions, IList <decimal> termPointValues)
        {
            var termPoints = new List <TermPoint>();
            var length     = Math.Min(timeDimensions.Count, termPointValues.Count);

            for (var i = 0; i < length; i++)
            {
                var point = TermPointFactory.Create(termPointValues[i], timeDimensions[i]);
                termPoints.Add(point);
            }
            return(termPoints.ToArray());
        }
Exemplo n.º 7
0
        private void SetInterpolator()
        {
            IDayCounter dc         = Actual365.Instance;
            var         termPoints = new List <TermPoint>
            {
                TermPointFactory.Create(1.0m, new DateTime()),
                TermPointFactory.Create(0.99m, new DateTime().AddDays(10)),
                TermPointFactory.Create(0.97m, new DateTime().AddDays(100))
            };
            var termCurve = TermCurve.Create(new DateTime(), new InterpolationMethod {
                Value = "LinearInterpolation"
            }, true, termPoints);

            Interpolator = new TermCurveInterpolator(termCurve, new DateTime(), dc);
        }
Exemplo n.º 8
0
        ///<summary>
        /// Creates a term point array.
        ///</summary>
        public static TermPoint[] Create(IDictionary <DateTime, Pair <string, decimal> > items)
        {
            var termPoints = new List <TermPoint>();

            foreach (var item in items)
            {
                var point = TermPointFactory.Create(item.Value.Second, item.Key);
                if (!string.IsNullOrEmpty(item.Value.First))
                {
                    point.id = item.Value.First;
                }
                termPoints.Add(point);
            }
            return(termPoints.ToArray());
        }
Exemplo n.º 9
0
        private static TermCurve LoadAndSort(string centralBankName, TermCurve termCurve, IList <DateTime> centralBankDates, DateTime baseDate, IDayCounter dayCounter)
        {
            var cloneTermCurve = XmlSerializerHelper.Clone(termCurve);
            var points         = new List <TermPoint>();
            var tupleList      = ProcessTermCurve(cloneTermCurve);

            //Gap step Logic
            //1. Is there a reserve bank date(s) between 2 consecutive term curve points?
            //2. If yes then how many?
            //3. Initially ignore all but the first one.
            //4. Insert the first date.
            //5. Loop past any other dates.
            if (centralBankDates != null)
            {
                var dates = centralBankDates.ToList();
                for (int i = 1; i < tupleList.Count; i++)
                {
                    var intervalStartDate = tupleList[i - 1].Item1;
                    var intervalEndDate   = tupleList[i].Item1;
                    var intervalStartRate = tupleList[i - 1].Item2;
                    var intervalEndRate   = tupleList[i].Item2;
                    var dateList          = new List <DateTime>();
                    foreach (var centralDate in dates)
                    {
                        if (intervalStartDate < centralDate && centralDate < intervalEndDate)
                        {
                            dateList.Add(centralDate);
                        }
                    }
                    if (dateList.Count > 0)
                    {
                        var termPoint =
                            TermPointFactory.Create(centralBankName + ":" + dateList[0], InterpolateRate(baseDate, intervalStartDate, intervalStartRate,
                                                                                                         intervalEndDate, intervalEndRate, dayCounter, dateList[0]),
                                                    dates[0]);
                        points.Add(termPoint);
                    }
                }
            }
            var newPoints = cloneTermCurve.point.ToList();

            newPoints.AddRange(points);
            var sortedList = SortPoints(newPoints);

            cloneTermCurve.point = sortedList.ToArray();
            return(cloneTermCurve);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns a list of non-interpolated values found in a immediate vicinity of requested point.
        /// <remarks>
        /// If a GetValue method returns a exact match - this method should be returning null.
        /// </remarks>
        /// </summary>
        /// <param name="termCurve"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public static TermPoint GetPreviousPoint(TermCurve termCurve, DateTime date)
        {
            var dates  = termCurve.GetListTermDates();//GetDiscreteSpace().GetCoordinateArray(1);
            var values = termCurve.GetListMidValues();
            var index  = Array.BinarySearch(dates.ToArray(), date);

            if (index >= 0)
            {
                return(termCurve.point[index]);
            }
            var nextIndex = ~index;
            var prevIndex = nextIndex - 1;
            //TODO check for DateTime1D point and return the date.
            var prevPoint = TermPointFactory.Create(values[prevIndex], dates[prevIndex]);

            return(prevPoint);
        }
Exemplo n.º 11
0
        private static TermCurve  Load(TermCurve termCurve, IList <DateTime> centralBankDates, DateTime baseDate, IDayCounter dayCounter)
        {
            var points  = new List <TermPoint>(termCurve.point);
            var counter = 0;

            foreach (var point in termCurve.point)
            {
                var date = (DateTime)point.term.Items[0];
                if (centralBankDates != null)
                {
                    //dates are the central bank dates between the term curve node dates specified by the input instruments.
                    //TODO currently the intermediate central bank dates are forgotten.
                    //They need to be spliced into the term curve.
                    //Also, the interpolation routine needs to be set to the appropriate back fill/forward fill logic.
                    var dates = centralBankDates.Where(t => GetPreviousIndex(termCurve, t) == counter).ToList();
                    foreach (var centralBankdate in dates)
                    {
                        if (date == centralBankdate)
                        {
                            continue;
                        }
                        if (dates.IndexOf(centralBankdate) == 1)
                        {
                            var termPoint =
                                TermPointFactory.Create(InterpolateRate(termCurve, baseDate, dayCounter, dates[0]), dates[0]);
                            points.Insert(GetPreviousIndex(termCurve, date), termPoint);
                        }
                        else
                        {
                            var termPoint =
                                TermPointFactory.Create(InterpolateRate2(termCurve, baseDate, dayCounter, centralBankdate), centralBankdate);
                            points.Insert(GetPreviousIndex(termCurve, date), termPoint);
                        }
                    }
                }
                counter++;
            }
            //TODO does this fix the problem?
            //termCurve.point = points.ToArray();
            return(termCurve);
        }
Exemplo n.º 12
0
        ///<summary>
        ///</summary>
        ///<param name="discountCurve"></param>
        ///<param name="baseDate"></param>
        ///<param name="forwardRateTenor"></param>
        ///<param name="priceableXibor"></param>
        ///<returns></returns>
        public TermCurve ToPriceableXiborForwardCurve(TermCurve discountCurve, DateTime baseDate,
                                                      Period forwardRateTenor, PriceableXibor priceableXibor) //TODO
        {
            //CompoundingFrequency frequency = CompoundingFrequencyHelper.Create("Annual");
            var dates         = discountCurve.GetListTermDates();
            var yearFractions = new List <double>();

            foreach (var date in dates)
            {
                var yearFraction = (date - baseDate).TotalDays / 365.0;//TODO extend this with a general daycountraction.
                yearFractions.Add(yearFraction);
            }
            var midValues        = discountCurve.GetListMidValues();
            var discountFactors  = new List <double>(Array.ConvertAll(midValues.ToArray(), Convert.ToDouble));
            var forwardTermCurve = TermCurve.Create(new List <TermPoint>());
            var index            = 0;

            foreach (var startOfPeriodDateTime in dates)
            {
                var yearFractionsbeginPeriod  = yearFractions[index];
                var endOfPeriodDateTime       = forwardRateTenor.Add(startOfPeriodDateTime);
                var yearFractionAtEndOfPeriod = (endOfPeriodDateTime - baseDate).TotalDays / 365.0;
                //get df corresponding to end of period
                //
                IInterpolation interpolation = new LinearRateInterpolation();
                interpolation.Initialize(yearFractions.ToArray(), discountFactors.ToArray());
                var dfAtEndOfPeriod         = interpolation.ValueAt(yearFractionAtEndOfPeriod, true);
                var dfAtTheBeginingOfPeriod = discountFactors[index];
                var forwardRate             = (dfAtTheBeginingOfPeriod / dfAtEndOfPeriod - 1) /
                                              (yearFractionAtEndOfPeriod - yearFractionsbeginPeriod);
                var zeroPoint = TermPointFactory.Create(Convert.ToDecimal(forwardRate), startOfPeriodDateTime);
                forwardTermCurve.Add(zeroPoint);
                ++index;
            }
            return(forwardTermCurve);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Unpack a raw surface and create a VolatilitySurface
        /// The object array is assumed to be zero based when it is passed to the constructor
        /// (That is any Excel idiosyncrasies have been expunged)
        /// We'll test and modify if necessary to zero base the array
        /// </summary>
        /// <param name="rawSurface"></param>
        /// <param name="surfaceId"></param>
        /// <param name="date"></param>
        /// <param name="buildDateTime"></param>
        //       /// <param name="algorithm">The algorithm for interpolation. Not implemented yet.</param>
        public VolatilitySurface(object[,] rawSurface, VolatilitySurfaceIdentifier surfaceId, DateTime date, DateTime buildDateTime)
        {
            PricingStructureIdentifier = surfaceId;
            IDayCounter dc         = Actual365.Instance;
            var         termPoints = new List <TermPoint>
            {
                TermPointFactory.Create(1.0m, new DateTime()),
                TermPointFactory.Create(0.99m, new DateTime().AddDays(10)),
                TermPointFactory.Create(0.97m, new DateTime().AddDays(100))
            };
            var termCurve = TermCurve.Create(new DateTime(), new InterpolationMethod {
                Value = "LinearInterpolation"
            }, true, termPoints);

            Interpolator = new TermCurveInterpolator(termCurve, date, dc);//TODO need to create a surfaceinterpolator.
            var zeroedRawSurface = rawSurface.GetLowerBound(0) == 1 ? RedimensionRawSurface(rawSurface) : rawSurface;

            _algorithm = "Linear";
            // An ugly trick to find out if this is a cube or a surface
            bool isCube = !double.TryParse(zeroedRawSurface[1, 1].ToString(), out _);
            // Extract the strikes/tenors/expiries and build the surface
            var expiry     = ExtractExpiryFromRawSurface(zeroedRawSurface);
            var term       = ExtractTenorFromRawSurface(zeroedRawSurface, isCube);
            var strike     = ExtractStrikeFromRawSurface(zeroedRawSurface, isCube);
            var volatility = ExtractVolatilitiesFromRawSurface(zeroedRawSurface, isCube);

            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            var points = ProcessRawSurface(expiry, term, strike, volatility);

            PricingStructure = new VolatilityRepresentation
            {
                name  = surfaceId.Name,
                id    = surfaceId.Id,
                asset = new AnyAssetReference {
                    href = "Unknown"
                },
            };
            PricingStructureValuation
                = new VolatilityMatrix
                {
                dataPoints = new MultiDimensionalPricingData {
                    point = points
                },
                objectReference = new AnyAssetReference {
                    href = PricingStructure.id
                },
                baseDate = new IdentifiedDate {
                    Value = date
                },
                buildDateTime          = buildDateTime,
                buildDateTimeSpecified = true
                };
            // Record the row/column sizes of the inputs
            _matrixRowCount  = expiry.Length;
            _matrixRowCount *= term?.Length ?? 1;
            // Columns includes expiry and term (tenor) if it exists.
            _matrixColumnCount  = strike.Length + 1;
            _matrixColumnCount += term != null ? 1 : 0;
            // Generate an interpolator to use
            if (term == null || term.Length == 0)
            {
                _interpolation = new BilinearInterpolator();
            }
            else
            {
                _interpolation = new TrilinearInterpolator();
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// The constructor
        /// </summary>
        /// <param name="assetRef">The Asset this volatility models</param>
        /// <param name="name">The id to use with this matrix</param>
        /// <param name="date">The value date relating to this surface</param>
        /// <param name="expiry">An array of expiry definitions</param>
        /// <param name="term">An array of tenors or null if there is no term dimension.</param>
        /// <paparam name="strike">An array of strike descriptions</paparam>
        /// <param name="strike">The strike array.</param>
        /// <param name="volatility">A 2d array of volatilities.
        /// This must be equal to (expiry.Count x (1 &lt;= y &lt;= term.Count) x strike.Count </param>
        public VolatilitySurface(string assetRef, string name, DateTime date, string[] expiry, string[] term,
                                 string[] strike, double[,] volatility)
        {
            IDayCounter dc         = Actual365.Instance;
            var         termPoints = new List <TermPoint>
            {
                TermPointFactory.Create(1.0m, new DateTime()),
                TermPointFactory.Create(0.99m, new DateTime().AddDays(10)),
                TermPointFactory.Create(0.97m, new DateTime().AddDays(100))
            };
            var termCurve = TermCurve.Create(new DateTime(), new InterpolationMethod {
                Value = "LinearInterpolation"
            }, true, termPoints);

            Interpolator       = new TermCurveInterpolator(termCurve, date, dc);//TODO need to create a surfaceinterpolator.
            _algorithm         = "Linear";
            _matrixIndexHelper = new SortedList <ExpiryTenorStrikeKey, int>(new ExpiryTenorStrikeKey());
            var points = ProcessRawSurface(expiry, term, strike, volatility);

            PricingStructure = new VolatilityRepresentation {
                name = name
                ,
                id = name + date.ToString("yyyyMMdd")
                ,
                asset = new AnyAssetReference {
                    href = assetRef
                }
            };
            PricingStructureValuation = new VolatilityMatrix
            {
                dataPoints = new MultiDimensionalPricingData {
                    point = points
                }
                ,
                objectReference = new AnyAssetReference {
                    href = PricingStructure.id
                }
                ,
                baseDate = new IdentifiedDate {
                    Value = date
                }
                ,
                buildDateTime = DateTime.Now
                ,
                buildDateTimeSpecified = true
            };

            // Record the row/column sizes of the inputs
            _matrixRowCount  = expiry.Length;
            _matrixRowCount *= term?.Length ?? 1;
            // Columns includes expiry and term (tenor) if it exists.
            _matrixColumnCount  = strike.Length + 1;
            _matrixColumnCount += term != null ? 1 : 0;
            //TODO
            // Generate an interpolator to use
            if (term == null || term.Length == 0)
            {
                _interpolation = new BilinearInterpolator();
            }
            else
            {
                _interpolation = new TrilinearInterpolator();
            }
        }
Exemplo n.º 15
0
 ///<summary>
 /// Creates a term point array.
 ///</summary>
 ///<param name="dates"></param>
 ///<param name="discountFactors"></param>
 ///<returns></returns>
 public static TermPoint[] Create(IList <DateTime> dates, IList <double> discountFactors)
 {
     return(dates.Select((t, i) => TermPointFactory.Create((decimal)discountFactors[i], t)).ToArray());
 }