Esempio n. 1
0
 public void Construction_DefaultToInclusive()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2001, 6, 19);
     var interval = new DateInterval(start, end);
     Assert.IsTrue(interval.Inclusive);
 }
Esempio n. 2
0
 public void Construction_EndBeforeStart()
 {
     LocalDate start = new LocalDate(1600, 1, 1);
     LocalDate end = new LocalDate(1500, 1, 1);
     Assert.Throws<ArgumentException>(() => new DateInterval(start, end));
     Assert.Throws<ArgumentException>(() => new DateInterval(start, end, true));
 }
 public void Subtraction_PeriodWithTime()
 {
     LocalDate date = new LocalDate(2010, 1, 1);
     Period period = Period.FromHours(1);
     // Use method not operator here to form a valid statement
     Assert.Throws<ArgumentException>(() => LocalDate.Subtract(date, period));
 }
 public void PeriodAddition_MethodEquivalents()
 {
     LocalDate start = new LocalDate(2010, 6, 19);
     Period period = Period.FromMonths(3) + Period.FromDays(10);
     Assert.AreEqual(start + period, LocalDate.Add(start, period));
     Assert.AreEqual(start + period, start.Plus(period));
 }
 public void Subtraction_TruncatesOnShortMonth()
 {
     LocalDate start = new LocalDate(2010, 3, 30);
     Period period = Period.FromMonths(1);
     LocalDate expected = new LocalDate(2010, 2, 28);
     Assert.AreEqual(expected, start - period);
 }
 public void Subtraction_WithPeriod()
 {
     LocalDate start = new LocalDate(2010, 9, 29);
     Period period = Period.FromMonths(3) + Period.FromDays(10);
     LocalDate expected = new LocalDate(2010, 6, 19);
     Assert.AreEqual(expected, start - period);
 }
Esempio n. 7
0
        /// <summary>
        /// Addiert zu einem Datum (unter Berücksichtigung der geforderten Genauigkeit) die Anzahl an Jahren, Monaten und/oder Tagen.
        /// </summary>
        /// <param name="date">Das Datum zu dem die Jahre, Monate und Tage addiert werden sollen</param>
        /// <param name="addYears">Die Anzahl an Jahren die addiert werden sollen (kann auch negativ sein)</param>
        /// <param name="addMonths">Die Anzahl an Monaten die addiert werden sollen (kann auch negativ sein)</param>
        /// <param name="addDays">Die Anzahl an Tagen die addiert werden sollen (kann auch negativ sein)</param>
        /// <returns>Das neue Datum nach der Addition von Jahren, Monaten und/oder Tagen</returns>
        public LocalDate Add(LocalDate date, long addYears, long addMonths, long addDays)
        {
            var day = date.Day + addDays;
            var month = date.Month + addMonths;
            var year = date.Year + addYears;

            month += day / 30;
            day %= 30;

            if (day < 0)
            {
                day += 30;
                --month;
            }

            year += month / 12;
            month %= 12;
            if (month < 0)
            {
                month += 12;
                --year;
            }

            var newYear = (int)year;
            var newMonth = (int)month;
            var newDay = (int)day;
            var lastDayOfMonth = new LocalDate(newYear, newMonth, 1).GetLastDayOfMonth();
            if (lastDayOfMonth.Day < newDay)
                newDay = lastDayOfMonth.Day;

            return new LocalDate(newYear, newMonth, newDay);
        }
Esempio n. 8
0
 public void Construction_DifferentCalendars()
 {
     LocalDate start = new LocalDate(1600, 1, 1);
     LocalDate end = new LocalDate(1800, 1, 1, JulianCalendar);
     Assert.Throws<ArgumentException>(() => new DateInterval(start, end));
     Assert.Throws<ArgumentException>(() => new DateInterval(start, end, true));
 }
Esempio n. 9
0
        public void Transitions2000To2010()
        {
            // These were fetched with Joda Time 1.6.2, which definitely uses the new rules.
            var expectedDates = new[]
            {
                new LocalDate(2000, 3, 30), // Thursday morning
                new LocalDate(2001, 3, 29), // Thursday morning
                new LocalDate(2002, 3, 29), // Friday morning from here onwards
                new LocalDate(2003, 3, 28),
                new LocalDate(2004, 3, 26),
                new LocalDate(2005, 4, 1),
                new LocalDate(2006, 3, 31),
                new LocalDate(2007, 3, 30),
                new LocalDate(2008, 3, 28),
                new LocalDate(2009, 3, 27),
                new LocalDate(2010, 3, 26)
            };

            for (int year = 2000; year <= 2010; year++)
            {
                LocalDate summer = new LocalDate(year, 6, 1);
                var intervalPair = Jordan.MapLocal(summer.AtMidnight());
                Assert.AreEqual(1, intervalPair.Count);
                Assert.AreEqual(expectedDates[year - 2000], intervalPair.EarlyInterval.IsoLocalStart.Date);
            }
        }
 public void Length_Exclusive()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2000, 2, 10);
     var interval = new DateInterval(start, end, false);
     Assert.AreEqual(40, interval.Length);
 }
Esempio n. 11
0
 public void CombineWithTime()
 {
     LocalDate date = new LocalDate(2010, 6, 16);
     LocalTime time = new LocalTime(16, 20, 0);
     LocalDateTime dateTime = date + time;
     Assert.AreEqual("ISO: 2010-06-16T16:20:00 LOC", dateTime.ToString());
 }
Esempio n. 12
0
 /// <summary>
 /// Rundung des AfA-Datums
 /// </summary>
 /// <param name="date">Das zu rundende Datum</param>
 /// <param name="mode">Der Rundungsmodus</param>
 /// <returns>Das gerundete AfA-Datum</returns>
 public static LocalDate Round(this LocalDate date, DateRoundingMode mode)
 {
     LocalDate result;
     switch (mode)
     {
         case DateRoundingMode.Day:
             result = date;
             break;
         case DateRoundingMode.Month:
             result = new LocalDate(date.Year, date.Month, 1);
             if (date.Day >= 15)
                 result = result + Period.FromMonths(1);
             break;
         case DateRoundingMode.BeginOfMonth:
             result = new LocalDate(date.Year, date.Month, 1);
             break;
         case DateRoundingMode.HalfYear:
             if (date.Month >= 7)
             {
                 result = new LocalDate(date.Year, 7, 1);
             }
             else
             {
                 result = new LocalDate(date.Year, 1, 1);
             }
             break;
         case DateRoundingMode.BeginOfYear:
             result = new LocalDate(date.Year, 1, 1);
             break;
         default:
             throw new NotSupportedException();
     }
     return result;
 }
        public void ComparisonOperators_SameCalendar()
        {
            LocalDate date1 = new LocalDate(2011, 1, 2);
            LocalDate date2 = new LocalDate(2011, 1, 2);
            LocalDate date3 = new LocalDate(2011, 1, 5);

            Assert.IsFalse(date1 < date2);
            Assert.IsTrue(date1 < date3);
            Assert.IsFalse(date2 < date1);
            Assert.IsFalse(date3 < date1);

            Assert.IsTrue(date1 <= date2);
            Assert.IsTrue(date1 <= date3);
            Assert.IsTrue(date2 <= date1);
            Assert.IsFalse(date3 <= date1);

            Assert.IsFalse(date1 > date2);
            Assert.IsFalse(date1 > date3);
            Assert.IsFalse(date2 > date1);
            Assert.IsTrue(date3 > date1);

            Assert.IsTrue(date1 >= date2);
            Assert.IsFalse(date1 >= date3);
            Assert.IsTrue(date2 >= date1);
            Assert.IsTrue(date3 >= date1);
        }
Esempio n. 14
0
        /// <summary>
        /// Checks that each day from the given start year to the end year (inclusive) is equal
        /// between the BCL and the Noda Time calendar. Additionally, the number of days in each month and year
        /// and the number of months (and leap year status) in each year is checked.
        /// </summary>
        internal static void AssertEquivalent(Calendar bcl, CalendarSystem noda, int fromYear, int toYear)
        {
            // We avoid asking the BCL to create a DateTime on each iteration, simply
            // because the BCL implementation is so slow. Instead, we just check at the start of each month that
            // we're at the date we expect.
            DateTime bclDate = bcl.ToDateTime(fromYear, 1, 1, 0, 0, 0, 0);
            for (int year = fromYear; year <= toYear; year++)
            {
                Assert.AreEqual(bcl.GetDaysInYear(year), noda.GetDaysInYear(year), "Year: {0}", year);
                Assert.AreEqual(bcl.GetMonthsInYear(year), noda.GetMonthsInYear(year), "Year: {0}", year);
                for (int month = 1; month <= noda.GetMonthsInYear(year); month++)
                {
                    // Sanity check at the start of each month. Even this is surprisingly slow.
                    // (These three tests make up about 20% of the total execution time for the test.)
                    Assert.AreEqual(year, bcl.GetYear(bclDate));
                    Assert.AreEqual(month, bcl.GetMonth(bclDate));
                    Assert.AreEqual(1, bcl.GetDayOfMonth(bclDate));

                    Assert.AreEqual(bcl.GetDaysInMonth(year, month), noda.GetDaysInMonth(year, month),
                        "Year: {0}; Month: {1}", year, month);
                    Assert.AreEqual(bcl.IsLeapYear(year), noda.IsLeapYear(year), "Year: {0}", year);
                    for (int day = 1; day <= noda.GetDaysInMonth(year, month); day++)
                    {
                        LocalDate nodaDate = new LocalDate(year, month, day, noda);
                        Assert.AreEqual(bclDate, nodaDate.ToDateTimeUnspecified(),
                            "Original calendar system date: {0:yyyy-MM-dd}", nodaDate);
                        Assert.AreEqual(nodaDate, LocalDate.FromDateTime(bclDate, noda));
                        Assert.AreEqual(year, nodaDate.Year);
                        Assert.AreEqual(month, nodaDate.Month);
                        Assert.AreEqual(day, nodaDate.Day);
                        bclDate = bclDate.AddDays(1);
                    }
                }
            }
        }
Esempio n. 15
0
 public void DayOfMonth()
 {
     var start = new LocalDate(2014, 6, 27);
     var end = new LocalDate(2014, 6, 19);
     var adjuster = DateAdjusters.DayOfMonth(19);
     Assert.AreEqual(end, adjuster(start));
 }
        public void BclThroughHistory_Scriptural()
        {
            var bcl = BclCalendars.Hebrew;
            var noda = CalendarSystem.HebrewScriptural;

            // The min supported date/time starts part way through the year
            var minYear = bcl.GetYear(bcl.MinSupportedDateTime) + 1;
            // The max supported date/time ends part way through the year
            var maxYear = bcl.GetYear(bcl.MaxSupportedDateTime) - 1;

            // Can't use BclEquivalenceHelper for this one, because of the month conversions.
            for (int year = minYear; year <= maxYear; year++)
            {
                int months = bcl.GetMonthsInYear(year);
                Assert.AreEqual(months, noda.GetMonthsInYear(year));
                for (int civilMonth = 1; civilMonth <= months; civilMonth++)
                {
                    int scripturalMonth = HebrewMonthConverter.CivilToScriptural(year, civilMonth);
                    Assert.AreEqual(bcl.GetDaysInMonth(year, civilMonth), noda.GetDaysInMonth(year, scripturalMonth),
                        "Year: {0}; Month: {1} (civil)", year, civilMonth);
                    for (int day = 1; day < bcl.GetDaysInMonth(year, civilMonth); day++)
                    {
                        DateTime bclDate = bcl.ToDateTime(year, civilMonth, day, 0, 0, 0, 0);
                        LocalDate nodaDate = new LocalDate(year, scripturalMonth, day, noda);
                        Assert.AreEqual(bclDate, nodaDate.AtMidnight().ToDateTimeUnspecified(), "{0}-{1}-{2}", year, scripturalMonth, day);
                        Assert.AreEqual(nodaDate, LocalDateTime.FromDateTime(bclDate, noda).Date);
                        Assert.AreEqual(year, nodaDate.Year);
                        Assert.AreEqual(scripturalMonth, nodaDate.Month);
                        Assert.AreEqual(day, nodaDate.Day);
                    }
                }
            }
        }
 public LocalDate Add(LocalDate localDate, int value)
 {
     var calendar = localDate.Calendar;
     var calculator = calendar.YearMonthDayCalculator;
     var yearMonthDay = calculator.AddMonths(localDate.YearMonthDay, value);
     return new LocalDate(yearMonthDay, calendar);
 }
 public void Constructor_PropertiesRoundTrip()
 {
     LocalDate date = new LocalDate(2023, 7, 27);
     Assert.AreEqual(2023, date.Year);
     Assert.AreEqual(7, date.MonthOfYear);
     Assert.AreEqual(27, date.DayOfMonth);
 }
 public void Constructor_PropertiesRoundTrip_CustomCalendar()
 {
     LocalDate date = new LocalDate(2023, 7, 27, CalendarSystem.GetJulianCalendar(4));
     Assert.AreEqual(2023, date.Year);
     Assert.AreEqual(7, date.MonthOfYear);
     Assert.AreEqual(27, date.DayOfMonth);
 }
Esempio n. 20
0
    public void LocalDateTest()
    {
      LocalDate d1 = new LocalDate(2016, 1, 10);
      LocalDate d2 = new LocalDate(2016, 1, 1);
      LocalDate d1other = new LocalDate(2016, 1, 10);
      Assert.AreNotEqual(d1, d2);
      Assert.AreEqual(d1, d1other);

      using (SessionNoServer session = new SessionNoServer(systemDir))
      {
        session.BeginUpdate();
        LocalDateField test1 = new LocalDateField("def", d1);
        session.Persist(test1);
        LocalDateField test = new LocalDateField("abc", d2);
        session.Persist(test);
        var result1 = session.AllObjects<LocalDateField>().First(t => t.Field2.Equals(d2)); // this works
        session.Commit();
      }

      using (SessionNoServer session = new SessionNoServer(systemDir))
      {
        session.BeginRead();
        var result2 = session.AllObjects<LocalDateField>().First(t => 
        {
          var l = t.Field2;
          return l.Equals(d2);
        }); // this should work and doesnt
        session.Commit();
      }
    }
Esempio n. 21
0
 public void CombineWithTime()
 {
     LocalDate date = new LocalDate(2010, 6, 16);
     LocalTime time = new LocalTime(16, 20);
     LocalDateTime dateTime = date + time;
     Assert.AreEqual(new LocalDateTime(2010, 6, 16, 16, 20, 0), dateTime);
 }
 public void ArithmeticExamples(int persianYear, int gregorianYear, int gregorianDayOfMarch)
 {
     var persian = new LocalDate(persianYear, 1, 1, CalendarSystem.PersianArithmetic);
     var gregorian = persian.WithCalendar(CalendarSystem.Gregorian);
     Assert.AreEqual(gregorianYear, gregorian.Year);
     Assert.AreEqual(3, gregorian.Month);
     Assert.AreEqual(gregorianDayOfMarch, gregorian.Day);
 }
 public void WithCalendar()
 {
     LocalDate isoEpoch = new LocalDate(1970, 1, 1);
     LocalDate julianEpoch = isoEpoch.WithCalendar(CalendarSystem.GetJulianCalendar(4));
     Assert.AreEqual(1969, julianEpoch.Year);
     Assert.AreEqual(12, julianEpoch.MonthOfYear);
     Assert.AreEqual(19, julianEpoch.DayOfMonth);
 }
 public void WeekYearDifferentToYear(int year, int month, int day, int weekYear, int weekOfWeekYear, IsoDayOfWeek dayOfWeek)
 {
     var date = new LocalDate(year, month, day);
     Assert.AreEqual(weekYear, WeekYearRules.Iso.GetWeekYear(date));
     Assert.AreEqual(weekOfWeekYear, WeekYearRules.Iso.GetWeekOfWeekYear(date));
     Assert.AreEqual(dayOfWeek, date.IsoDayOfWeek);
     Assert.AreEqual(date, WeekYearRules.Iso.GetLocalDate(weekYear, weekOfWeekYear, dayOfWeek));
 }
Esempio n. 25
0
 public void Construction_Properties()
 {
     LocalDate start = new LocalDate(2000, 1, 1);
     LocalDate end = new LocalDate(2001, 6, 19);
     var interval = new DateInterval(start, end, false);
     Assert.AreEqual(start, interval.Start);
     Assert.AreEqual(end, interval.End);
     Assert.IsFalse(interval.Inclusive);
 }
 public void GetMinYearOfEra()
 {
     LocalDate date = new LocalDate(1, 1, 1);
     Assert.AreEqual(date.YearOfEra, Iso.GetMinYearOfEra(Era.Common));
     Assert.AreEqual(Era.Common, date.Era);
     date = new LocalDate(0, 1, 1);
     Assert.AreEqual(date.YearOfEra, Iso.GetMinYearOfEra(Era.BeforeCommon));
     Assert.AreEqual(Era.BeforeCommon, date.Era);
 }
 public void GetAbsoluteYear()
 {
     Assert.AreEqual(5, CopticCalendar.GetAbsoluteYear(5, Era.AnnoMartyrum));
     // Prove it's right...
     LocalDate localDate = new LocalDate(5, 1, 1, CopticCalendar);
     Assert.AreEqual(5, localDate.Year);
     Assert.AreEqual(5, localDate.YearOfEra);
     Assert.AreEqual(Era.AnnoMartyrum, localDate.Era);
 }
 [TestCase(1981)] // Non-leap year in optimized period
 public void Constructor_WithDaysAndCalendar(int year)
 {
     LocalDate start = new LocalDate(year, 1, 1);
     int startDays = start.DaysSinceEpoch;
     for (int i = 0; i < 366; i++)
     {
         Assert.AreEqual(start.PlusDays(i), new LocalDate(startDays + i, CalendarSystem.Iso));
     }
 }
Esempio n. 29
0
 /// <summary>
 /// Constructs a date interval from a start date and an end date, and an indication
 /// of whether the end date should be included in the interval.
 /// </summary>
 /// <param name="start">Start date of the interval</param>
 /// <param name="end">End date of the interval</param>
 /// <param name="inclusive"><c>true</c> to include the end date in the interval;
 /// <c>false</c> to exclude it.
 /// </param>
 /// <exception cref="ArgumentException"><paramref name="end"/> is earlier than <paramref name="start"/>
 /// or the two dates are in different calendars.
 /// </exception>
 /// <returns>A date interval between the specified dates, with the specified inclusivity.</returns>
 public DateInterval(LocalDate start, LocalDate end, bool inclusive)
 {
     Preconditions.CheckArgument(start.Calendar.Equals(end.Calendar), nameof(end),
         "Calendars of start and end dates must be the same.");
     Preconditions.CheckArgument(!(end < start), nameof(end), "End date must not be earlier than the start date");
     this.Start = start;
     this.End = end;
     this.Inclusive = inclusive;
 }
Esempio n. 30
0
 public void Next(
     int year, int month, int day, IsoDayOfWeek dayOfWeek,
     int expectedYear, int expectedMonth, int expectedDay)
 {
     LocalDate start = new LocalDate(year, month, day);
     LocalDate actual = start.With(DateAdjusters.Next(dayOfWeek));
     LocalDate expected = new LocalDate(expectedYear, expectedMonth, expectedDay);
     Assert.AreEqual(expected, actual);
 }
Esempio n. 31
0
        public static List <ExportRow> MatchMediusFlowWithSIE(IEnumerable <int> years, List <InvoiceFull> invoices, List <RootRecord> sie, List <SBC.Invoice> sbcInvoices)
        {
            // SLR/LR are added when expense is registered, and contains the expense accounts
            // LB is when it's payed
            // LB will be dated at or after SLR/LR

            // SLRs company names are supposedly same as LB, but LRs can have
            var(invoiceSummaries, sieVouchers) = PrepareFiltered(years, invoices, sie);
            var result = InvoiceSIEMatch.MatchInvoiceWithLB_SLR(sieVouchers, invoiceSummaries);

            var missingPayment = result.Matches.Where(o => o.SLR.Voucher == null).ToList();

            if (missingPayment.Any())
            {
                // Ignore those with due date later than latest found payment:
                var latestDate = sieVouchers.Where(o => o.VoucherType == VoucherType.SLR).Max(o => o.Date).ToDateTimeUnspecified();
                missingPayment = missingPayment.Where(o => o.Invoice.DueDate < latestDate).ToList();
                if (missingPayment.Any())
                {
                    System.Diagnostics.Debugger.Break();
                }
            }
            //Assert.IsFalse(missing.Any());

            // Some urgent invoices go (by request) direct to payment, without passing MediusFlow (e.g. 2020 "Office for design", "Stenbolaget")
            // The same goes for SBCs own periodical invoices and bank/interest payments
            // These should be found here: https://varbrf.sbc.se/Portalen/Ekonomi/Utforda-betalningar/
            // Actually, this is just a view for SLR records - with an additional link for the invoice

            // try getting LBs for sbcInvoices
            // tricky thing with sbcInvoices - one row for each non-admin transaction in SLRs
            var lbs            = sieVouchers.Where(o => o.VoucherType == VoucherType.LB).ToList();
            var sbcInvoiceToLB = sbcInvoices.Where(o => o.PaymentDate != null).GroupBy(o => o.IdSLR)
                                 .Select(grp =>
            {
                var invoiceSum  = grp.Sum(v => v.Amount);
                var paymentDate = LocalDate.FromDateTime(grp.First().PaymentDate.Value);
                return(new
                {
                    Invoice = grp.First(),
                    LBs = lbs.Where(l => l.Date == paymentDate && l.Transactions.First(t => t.AccountId == 24400).Amount == invoiceSum).ToList()
                });
            });
            var sbcInvoiceToSingleLB = sbcInvoiceToLB.Where(o => o.LBs.Count == 1).ToDictionary(o => o.Invoice.IdSLR, o => o.LBs.Single());
            var stillUnmatchedLBs    = result.UnmatchedLB.Except(sbcInvoiceToSingleLB.Values).ToList();

            var sbcMatchedSLRSNs   = sbcInvoiceToSingleLB.Select(o => o.Key).ToList();
            var stillUnmatchedSLRs = result.UnmatchedSLR.Where(o => !sbcMatchedSLRSNs.Contains(o.Id));

            var vouchersSlrLr       = sieVouchers.Where(o => o.VoucherType == VoucherType.TaxAndExpense).Concat(stillUnmatchedSLRs).ToList();
            var matchRemaining      = MatchVoucherTypes(vouchersSlrLr, stillUnmatchedLBs, false);
            var stillUnmatchedSlrLr = vouchersSlrLr.Except(matchRemaining.Select(o => o.Key)).ToList();

            stillUnmatchedLBs = stillUnmatchedLBs.Except(matchRemaining.Select(o => o.Value)).ToList();

            var finalMatch = MatchVoucherTypes(stillUnmatchedSlrLr, stillUnmatchedLBs, true);

            stillUnmatchedSlrLr = stillUnmatchedSlrLr.Except(finalMatch.Select(o => o.Key)).ToList();
            stillUnmatchedLBs   = stillUnmatchedLBs.Except(finalMatch.Select(o => o.Value)).ToList();
            foreach (var kv in finalMatch)
            {
                matchRemaining.Add(kv.Key, kv.Value);
            }

            var matchesBySLR = result.Matches.Where(o => o.SLR.Voucher != null)
                               .Select(m => new { Key = m.SLR.Voucher.Id, Value = m })
                               .ToDictionary(o => o.Key, o => o.Value);
            var fullResult = sieVouchers.Where(o => o.VoucherType == VoucherType.SLR || o.VoucherType == VoucherType.TaxAndExpense).Select(slr =>
            {
                // TODO: should we have multiple rows if SLR has >1 non-admin transaction?
                //var sbcInv = sbcInvoices.FirstOrDefault(o => o.RegisteredDate.Year == slr.Date.Year && o.VerNum == slr.SerialNumber);
                var sbcInv = sbcInvoices.FirstOrDefault(o => o.IdSLR == slr.Id);
                var info   = new InvoiceInfo {
                    SLR = slr, SbcImageLink = sbcInv?.InvoiceLink
                };
                if (matchesBySLR.TryGetValue(slr.Id, out var found))
                {
                    info.Invoice = found.Invoice;
                    info.LB      = found.LB.Voucher;
                }
                if (info.LB == null && sbcInv != null)
                {
                    if (sbcInvoiceToSingleLB.TryGetValue(sbcInv.IdSLR, out var lb))
                    {
                        info.LB = lb;
                    }
                }
                if (info.LB == null && matchRemaining.ContainsKey(slr))
                {
                    info.LB = matchRemaining[slr];
                }
                return(info);
            }).OrderByDescending(o => o.RegisteredDate).ToList();

            fullResult.ForEach(o => { try { var tmp = o.MainAccountId; } catch { throw new Exception($"Missing MainAccountId in {o}"); } });

            var accountIdToAccountName = sie.SelectMany(s => s.Children.OfType <AccountRecord>()).GroupBy(o => o.AccountId).ToDictionary(o => o.Key, o => o.First().AccountName);

            foreach (var accountId in accountIdToAccountName.Keys)
            {
                var found = invoiceSummaries.FirstOrDefault(o => o.AccountId == accountId);
                if (found != null)
                {
                    accountIdToAccountName[accountId] = found.AccountName;
                }
            }

            //var header = new[] {
            //	"Date",
            //	"Missing",
            //	"Amount",
            //	"Supplier",
            //	"AccountId",
            //	"AccountName",
            //	"Comments",
            //	"InvoiceId",
            //	"ReceiptId",
            //	"CurrencyDate",
            //	"TransactionText",
            //	"TransactionRef"
            //};
            var rows =             //string.Join("\n", new[] { header }.Concat(
                       fullResult.OrderByDescending(o => o.RegisteredDate)
                       .Select(o =>
            {
                var supplier = o.SLR.Transactions.First().CompanyName;
                var comments = o.Invoice != null ? InvoiceSummary.ShortenComments(o.Invoice?.Comments ?? "")
                                                        : (o.LB?.CompanyName != o.SLR.Transactions.First().CompanyName ? o.LB?.CompanyName : "");
                if (o.Invoice == null && !string.IsNullOrEmpty(comments))
                {
                    // in this case SLR "CompanyName" is actually the purpose, and LB has recipient
                    supplier = comments;
                    comments = o.SLR.Transactions.First().CompanyName;
                }

                var accountChanged = o.SLR.Transactions.GroupBy(t => t.AccountId).Where(t => t.Select(tt => Math.Sign(tt.Amount)).Distinct().Count() > 1);
                return(new ExportRow {
                    Date = o.RegisteredDate,
                    Missing = "",
                    Amount = o.Amount,
                    Supplier = supplier,
                    AccountId = o.MainAccountId,
                    AccountName = accountIdToAccountName[o.MainAccountId],
                    Comments = comments,
                    InvoiceId = o.Invoice?.Id.ToString() ?? "",
                    ReceiptId = $"{o.SLR.Series} {o.SLR.SerialNumber}",
                    CurrencyDate = o.LB?.Date,
                    TransactionText = "",
                    TransactionRef = string.IsNullOrEmpty(o.SbcImageLink) ? "" :
                                     (o.SbcImageLink.StartsWith("http") ? o.SbcImageLink : $"https://varbrf.sbc.se{o.SbcImageLink}"),                    //https://varbrf.sbc.se/InvoiceViewer.aspx?id=
                    AccountChange = accountChanged.Any() ? string.Join(", ", accountChanged.Where(x => x.Key != o.MainAccountId).Select(x => x.Key).Distinct()) : "",
                });
                //	return new string[] {
                //		o.RegisteredDate.ToSimpleDateString(),
                //		"",
                //		o.Amount.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture),
                //		supplier,
                //		o.MainAccountId.ToString(),
                //		accountIdToAccountName[o.MainAccountId],
                //		comments,
                //		o.Invoice?.Id.ToString() ?? "",
                //		$"{o.SLR.Series} {o.SLR.SerialNumber}", //o.LB?.Id ?? "",
                //		o.LB?.Date.ToSimpleDateString() ?? "",
                //		"",
                //		string.IsNullOrEmpty(o.SbcImageLink) ? "" :
                //			(o.SbcImageLink.StartsWith("http") ? o.SbcImageLink : $"https://varbrf.sbc.se{o.SbcImageLink}"), //https://varbrf.sbc.se/InvoiceViewer.aspx?id=
                //		accountChanged.Any() ? string.Join(", ", accountChanged.Where(x => x.Key != o.MainAccountId).Select(x => x.Key).Distinct()) : "",
                //};
            }
                               //)).Select(o => string.Join("\t", o))
                               ).ToList();

            return(rows);
            // https://varbrf.sbc.se/Portalen/Ekonomi/Revisor/Underlagsparm/
        }
 /// <summary>
 /// Returns the last date of the given date's month.
 /// </summary>
 /// <param name="date">The date whose month should be used.</param>
 /// <returns>The last date of the given date's month.</returns>
 public static LocalDate EndOfMonth(this LocalDate date) => DateAdjusters.EndOfMonth(date);
 /// <summary>
 /// Returns a date interval starting and ending on the first and last day of the week that <paramref name="date"/> is in,
 /// given the week starts on <paramref name="firstDayOfWeek"/>.
 /// </summary>
 /// <param name="date">The local date.</param>
 /// <param name="firstDayOfWeek">The week day considered the first day of the week.</param>
 /// <returns>The week date interval.</returns>
 public static DateInterval GetContainingWeekInterval(this LocalDate date, IsoDayOfWeek firstDayOfWeek) => new DateInterval(date.StartOfWeek(firstDayOfWeek), date.EndOfWeek(firstDayOfWeek));
 /// <summary>
 /// Converts the date to an annual date, ignoring the year.
 /// </summary>
 /// <param name="date">A local date.</param>
 /// <returns>An annual date with the same month and day as the given date.</returns>
 public static AnnualDate ToAnnualDate(this LocalDate date) => new AnnualDate(date.Month, date.Day);
 /// <summary>
 /// Converts a date to a string in a normal format.
 /// </summary>
 /// <param name="date">The date to be converted.</param>
 /// <returns>The string.</returns>
 public static string ToDateString(this LocalDate date)
 {
     return(date.ToString("d", new CultureInfo("en-US")));
 }
        public virtual PointSensitivityBuilder rateSensitivity(OvernightCompoundedRateComputation computation, LocalDate startDate, LocalDate endDate, RatesProvider provider)
        {
            OvernightIndexRates rates   = provider.overnightIndexRates(computation.Index);
            ObservationDetails  details = new ObservationDetails(computation, rates);

            return(details.calculateRateSensitivity());
        }
Esempio n. 37
0
 protected void Selected(LocalDate localDate)
 {
     isVisible    = false;
     currentValue = localDate.ToDateTimeUnspecified();
 }
Esempio n. 38
0
        public List <HolidayData> FilterRelevantHolidays(List <HolidayData> holidayData, LocalDate yearStart, LocalDate yearEnd)
        {
            var result = new List <HolidayData>();

            foreach (var holiday in holidayData)
            {
                if (holiday.End < yearStart)
                {
                    continue;
                }
                if (holiday.Start > yearEnd)
                {
                    continue;
                }
                if (holiday.Start == holiday.End && !this.IsNotWeekend(holiday.Start.DayOfWeek))
                {
                    continue;
                }
                result.Add(holiday);
            }
            return(result);
        }
Esempio n. 39
0
 public LocalDateField(string field1, LocalDate field2)
 {
     m_Field1 = field1;
     m_Field2 = field2;
 }
Esempio n. 40
0
 protected void Add(Period period)
 {
     RenderedValue = RenderedValue.Plus(period);
 }
Esempio n. 41
0
 protected void SetDate(LocalDate date)
 {
     RenderedValue = date;
     AcceptValue();
 }
Esempio n. 42
0
 protected override void OnParametersSet()
 {
     RenderedValue = Value ?? Today;
 }
        public virtual double explainRate(OvernightCompoundedRateComputation computation, LocalDate startDate, LocalDate endDate, RatesProvider provider, ExplainMapBuilder builder)
        {
            double rate = this.rate(computation, startDate, endDate, provider);

            builder.put(ExplainKey.COMBINED_RATE, rate);
            return(rate);
        }
Esempio n. 44
0
 //-------------------------------------------------------------------------
 /// <summary>
 /// Calculates the reference price for the trade.
 /// <para>
 /// If the valuation date equals the trade date, then the reference price is the trade price.
 /// Otherwise, the reference price is the last settlement price used for margining.
 ///
 /// </para>
 /// </summary>
 /// <param name="trade">  the trade </param>
 /// <param name="valuationDate">  the date for which the reference price should be calculated </param>
 /// <param name="lastSettlementPrice">  the last settlement price used for margining, in decimal form </param>
 /// <returns> the reference price, in decimal form </returns>
 internal virtual double referencePrice(ResolvedOvernightFutureTrade trade, LocalDate valuationDate, double lastSettlementPrice)
 {
     ArgChecker.notNull(valuationDate, "valuationDate");
     return(trade.TradedPrice.filter(tp => tp.TradeDate.Equals(valuationDate)).map(tp => tp.Price).orElse(lastSettlementPrice));
 }
Esempio n. 45
0
        public static bool IsAllowedCheckinTime(this Property p, DateTime currentLocalTime, LocalDate arrivalOpsdate)
        {
            var offset = p.CheckinTimeOfDay.ToTimeSpan().Subtract(new TimeSpan(Convert.ToInt32(p.AllowedEarlyCheckinHours), 0, 0));

            return((currentLocalTime - offset).ConvertDateTimeLocalDate() >= arrivalOpsdate);
        }
 /// <summary>
 /// Converts a date time object to a local date object.
 /// </summary>
 /// <param name="dateTime">The date time object.</param>
 /// <returns>The local date.</returns>
 public static LocalDate ToLocalDate(this DateTime dateTime)
 {
     return(LocalDate.FromDateTime(dateTime));
 }
            // Check that the fixing is present. Throws an exception if not and return the rate as double.
            internal static double checkedFixing(LocalDate currentFixingTs, LocalDateDoubleTimeSeries indexFixingDateSeries, OvernightIndex index)
            {
                double?fixedRate = indexFixingDateSeries.get(currentFixingTs);

                return(fixedRate.orElseThrow(() => new PricingException("Could not get fixing value of index " + index.Name + " for date " + currentFixingTs)));
            }
        //-------------------------------------------------------------------------
        public virtual void duplicateInputDataKeys()
        {
            FxSwapTemplate  template1               = FxSwapTemplate.of(Period.ofMonths(1), FxSwapConventions.EUR_USD);
            FxSwapTemplate  template2               = FxSwapTemplate.of(Period.ofMonths(2), FxSwapConventions.EUR_USD);
            QuoteId         pointsKey1a             = QuoteId.of(StandardId.of("test", "1a"));
            QuoteId         pointsKey1b             = QuoteId.of(StandardId.of("test", "1b"));
            QuoteId         pointsKey2a             = QuoteId.of(StandardId.of("test", "2a"));
            QuoteId         pointsKey2b             = QuoteId.of(StandardId.of("test", "2b"));
            FxSwapCurveNode node1a                  = FxSwapCurveNode.of(template1, pointsKey1a);
            FxSwapCurveNode node1b                  = FxSwapCurveNode.of(template2, pointsKey1b);
            FxSwapCurveNode node2                   = FxSwapCurveNode.of(template1, pointsKey2a);
            FxSwapCurveNode node2b                  = FxSwapCurveNode.of(template2, pointsKey2b);
            CurveName       curveName1              = CurveName.of("curve1");
            InterpolatedNodalCurveDefinition curve1 = InterpolatedNodalCurveDefinition.builder().name(curveName1).nodes(node1a, node1b).xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).dayCount(ACT_360).interpolator(CurveInterpolators.LINEAR).extrapolatorLeft(CurveExtrapolators.LINEAR).extrapolatorRight(CurveExtrapolators.LINEAR).build();
            CurveName curveName2 = CurveName.of("curve2");
            InterpolatedNodalCurveDefinition curve2   = InterpolatedNodalCurveDefinition.builder().name(curveName2).nodes(node2, node2b).xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.ZERO_RATE).dayCount(ACT_360).interpolator(CurveInterpolators.LINEAR).extrapolatorLeft(CurveExtrapolators.LINEAR).extrapolatorRight(CurveExtrapolators.LINEAR).build();
            CurveGroupName            curveGroupName  = CurveGroupName.of("group");
            RatesCurveGroupDefinition groupDefinition = RatesCurveGroupDefinition.builder().name(curveGroupName).addDiscountCurve(curve1, Currency.EUR).addDiscountCurve(curve2, Currency.USD).build();

            RatesCurveGroupMarketDataFunction fn = new RatesCurveGroupMarketDataFunction();
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> marketDataMap1 = com.google.common.collect.ImmutableMap.of(com.opengamma.strata.data.FxRateId.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD), com.opengamma.strata.basics.currency.FxRate.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD, 1.01), pointsKey1a, 0.1d, pointsKey1b, 0.2d);
            IDictionary <MarketDataId <object>, object> marketDataMap1 = ImmutableMap.of(FxRateId.of(Currency.EUR, Currency.USD), FxRate.of(Currency.EUR, Currency.USD, 1.01), pointsKey1a, 0.1d, pointsKey1b, 0.2d);
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> marketDataMap2 = com.google.common.collect.ImmutableMap.of(com.opengamma.strata.data.FxRateId.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD), com.opengamma.strata.basics.currency.FxRate.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD, 1.01), pointsKey2a, 0.1d, pointsKey2b, 0.2d);
            IDictionary <MarketDataId <object>, object> marketDataMap2 = ImmutableMap.of(FxRateId.of(Currency.EUR, Currency.USD), FxRate.of(Currency.EUR, Currency.USD, 1.01), pointsKey2a, 0.1d, pointsKey2b, 0.2d);
            RatesCurveInputs            curveInputs1 = RatesCurveInputs.of(marketDataMap1, DefaultCurveMetadata.of("curve1"));
            RatesCurveInputs            curveInputs2 = RatesCurveInputs.of(marketDataMap2, DefaultCurveMetadata.of("curve2"));
            ImmutableScenarioMarketData marketData   = ImmutableScenarioMarketData.builder(LocalDate.of(2011, 3, 8)).addValue(RatesCurveInputsId.of(curveGroupName, curveName1, ObservableSource.NONE), curveInputs1).addValue(RatesCurveInputsId.of(curveGroupName, curveName2, ObservableSource.NONE), curveInputs2).build();

            fn.buildCurveGroup(groupDefinition, CALIBRATOR, marketData, REF_DATA, ObservableSource.NONE);

            // This has a duplicate key with a different value which should fail
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, Object> badMarketDataMap = com.google.common.collect.ImmutableMap.of(com.opengamma.strata.data.FxRateId.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD), com.opengamma.strata.basics.currency.FxRate.of(com.opengamma.strata.basics.currency.Currency.EUR, com.opengamma.strata.basics.currency.Currency.USD, 1.02), pointsKey2a, 0.2d);
            IDictionary <MarketDataId <object>, object> badMarketDataMap = ImmutableMap.of(FxRateId.of(Currency.EUR, Currency.USD), FxRate.of(Currency.EUR, Currency.USD, 1.02), pointsKey2a, 0.2d);
            RatesCurveInputs   badCurveInputs = RatesCurveInputs.of(badMarketDataMap, DefaultCurveMetadata.of("curve2"));
            ScenarioMarketData badMarketData  = ImmutableScenarioMarketData.builder(LocalDate.of(2011, 3, 8)).addValue(RatesCurveInputsId.of(curveGroupName, curveName1, ObservableSource.NONE), curveInputs1).addValue(RatesCurveInputsId.of(curveGroupName, curveName2, ObservableSource.NONE), badCurveInputs).build();
            string             msg            = "Multiple unequal values found for identifier .*\\. Values: .* and .*";

            assertThrowsIllegalArg(() => fn.buildCurveGroup(groupDefinition, CALIBRATOR, badMarketData, REF_DATA, ObservableSource.NONE), msg);
        }
 /// <summary>
 /// Determines whether the local date is on the annual date, i.e. whether the months and days are equal.
 /// </summary>
 /// <remarks>
 /// <para>
 /// If the annual date represents February 29th, and the specified date represents February 28th in a non-leap
 /// year, the returned value will be <c>true</c>; if it is a leap year, only a date representing February 29th
 /// will return <c>true</c>.
 /// </para>
 /// </remarks>
 /// <param name="date">The local date.</param>
 /// <param name="annualDate">The annual date.</param>
 /// <returns><c>true</c>, if the date is on the annual date; <c>false</c>, otherwise.</returns>
 public static bool IsOnAnnualDate(this LocalDate date, AnnualDate annualDate) => annualDate.InYear(date.Year) == date;
 /// <summary>
 /// Finds the next time the date (month and day) occurs, starting from <paramref name="fromDate"/>.
 /// </summary>
 // TODO: Add documentation
 public static LocalDate NextOccurrenceOfDate(this LocalDate date, LocalDate fromDate) => date.ToAnnualDate().NextOccurrence(fromDate);
Esempio n. 51
0
        internal string ToString(IFormatProvider formatProvider)
        {
            LocalDate localDate = new LocalDate(Year, Month, Day);

            return(localDate.ToString("d", formatProvider));
        }
Esempio n. 52
0
        public void Construction_EqualStartAndEnd()
        {
            LocalDate start = new LocalDate(2000, 1, 1);

            Assert.DoesNotThrow(() => new DateInterval(start, start));
        }
Esempio n. 53
0
        public void Includes_ReturnsFalse_WhenDateIsOutOfRange(DateTime from, DateTime to, DateTime targetDate)
        {
            var range = new DateRange(from, to);

            range.Includes(LocalDate.FromDateTime(targetDate)).Should().BeFalse();
        }
Esempio n. 54
0
        public void Includes_ReturnsTrue_WhenDateIsWithinRange(DateTime from, DateTime to, DateTime targetDate)
        {
            var range = new DateRange(from, to);

            range.Includes(LocalDate.FromDateTime(targetDate)).Should().BeTrue();
        }
 /// <summary>
 /// Returns a date interval with the first and last date of the month that <paramref name="date"/> is in.
 /// </summary>
 /// <param name="date">The local date.</param>
 /// <returns>The week date interval.</returns>
 public static DateInterval GetContainingMonthInterval(this LocalDate date) => new DateInterval(date.StartOfMonth(), date.EndOfMonth());
Esempio n. 56
0
 public void LocalDateConstructor_ThrowsException_WhenFromDateIsLaterThanToDate(DateTime from, DateTime to)
 {
     Assert.Throws <ArgumentException>(() => new DateRange(LocalDate.FromDateTime(from), LocalDate.FromDateTime(to)));
 }
 /// <summary>
 /// Returns the first date of the given date's month.
 /// </summary>
 /// <param name="date">The date whose month should be used.</param>
 /// <returns>The first date of the given date's month.</returns>
 public static LocalDate StartOfMonth(this LocalDate date) => DateAdjusters.StartOfMonth(date);
        public void LocalDateConverter_SerializeNonIso_Throws()
        {
            var localDate = new LocalDate(2012, 1, 2, CalendarSystem.Coptic);

            Assert.Throws <ArgumentException>(() => JsonConvert.SerializeObject(localDate, Formatting.None, NodaConverters.LocalDateConverter));
        }
Esempio n. 59
0
        /// <summary>
        /// Check that the sensitivities of parameters with respect to data is stored in the metadata.
        /// Compare the sensitivities to a finite difference approximation.
        /// This test is relatively slow as it calibrates the full surface multiple times.
        /// </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void log_normal_cube_sensitivity()
        public virtual void log_normal_cube_sensitivity()
        {
            double  beta         = 1.0;
            Surface betaSurface  = ConstantSurface.of("Beta", beta).withMetadata(DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).zValueType(ValueType.SABR_BETA).surfaceName("Beta").build());
            double  shift        = 0.0000;
            Surface shiftSurface = ConstantSurface.of("Shift", shift).withMetadata(DefaultSurfaceMetadata.builder().xValueType(ValueType.YEAR_FRACTION).yValueType(ValueType.YEAR_FRACTION).surfaceName("Shift").build());
            SabrParametersSwaptionVolatilities calibrated = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(DEFINITION, CALIBRATION_TIME, DATA_SPARSE, MULTICURVE, betaSurface, shiftSurface);
            double fdShift = 1.0E-5;

            SurfaceMetadata alphaMetadata = calibrated.Parameters.AlphaSurface.Metadata;
            Optional <IList <ParameterMetadata> > alphaParameterMetadataOption = alphaMetadata.ParameterMetadata;

            assertTrue(alphaParameterMetadataOption.Present);
            IList <ParameterMetadata>             alphaParameterMetadata     = alphaParameterMetadataOption.get();
            IList <DoubleArray>                   alphaJacobian              = calibrated.DataSensitivityAlpha.get();
            SurfaceMetadata                       rhoMetadata                = calibrated.Parameters.RhoSurface.Metadata;
            Optional <IList <ParameterMetadata> > rhoParameterMetadataOption = rhoMetadata.ParameterMetadata;

            assertTrue(rhoParameterMetadataOption.Present);
            IList <ParameterMetadata>             rhoParameterMetadata      = rhoParameterMetadataOption.get();
            IList <DoubleArray>                   rhoJacobian               = calibrated.DataSensitivityRho.get();
            SurfaceMetadata                       nuMetadata                = calibrated.Parameters.NuSurface.Metadata;
            Optional <IList <ParameterMetadata> > nuParameterMetadataOption = nuMetadata.ParameterMetadata;

            assertTrue(nuParameterMetadataOption.Present);
            IList <ParameterMetadata> nuParameterMetadata = nuParameterMetadataOption.get();
            IList <DoubleArray>       nuJacobian          = calibrated.DataSensitivityNu.get();

            int surfacePointIndex = 0;

            for (int loopexpiry = 0; loopexpiry < EXPIRIES.Count; loopexpiry++)
            {
                for (int looptenor = 0; looptenor < TENORS.Count; looptenor++)
                {
                    Tenor         tenor                = TENORS[looptenor];
                    double        tenorYears           = tenor.get(ChronoUnit.YEARS);
                    LocalDate     expiry               = EUR_FIXED_1Y_EURIBOR_6M.FloatingLeg.StartDateBusinessDayAdjustment.adjust(CALIBRATION_DATE.plus(EXPIRIES[loopexpiry]), REF_DATA);
                    ZonedDateTime expiryDateTime       = expiry.atTime(11, 0).atZone(ZoneId.of("Europe/Berlin"));
                    double        time                 = calibrated.relativeTime(expiryDateTime);
                    Pair <DoubleArray, DoubleArray> ds = DATA_SPARSE.getData(tenor).availableSmileAtExpiry(EXPIRIES[loopexpiry]);
                    if (!ds.First.Empty)
                    {
                        int availableDataIndex = 0;

                        ParameterMetadata alphaPM = alphaParameterMetadata[surfacePointIndex];
                        assertTrue(alphaPM is SwaptionSurfaceExpiryTenorParameterMetadata);
                        SwaptionSurfaceExpiryTenorParameterMetadata pmAlphaSabr = (SwaptionSurfaceExpiryTenorParameterMetadata)alphaPM;
                        assertEquals(tenorYears, pmAlphaSabr.Tenor);
                        assertEquals(time, pmAlphaSabr.YearFraction, TOLERANCE_EXPIRY);
                        DoubleArray       alphaSensitivityToData = alphaJacobian[surfacePointIndex];
                        ParameterMetadata rhoPM = rhoParameterMetadata[surfacePointIndex];
                        assertTrue(rhoPM is SwaptionSurfaceExpiryTenorParameterMetadata);
                        SwaptionSurfaceExpiryTenorParameterMetadata pmRhoSabr = (SwaptionSurfaceExpiryTenorParameterMetadata)rhoPM;
                        assertEquals(tenorYears, pmRhoSabr.Tenor);
                        assertEquals(time, pmRhoSabr.YearFraction, TOLERANCE_EXPIRY);
                        DoubleArray       rhoSensitivityToData = rhoJacobian[surfacePointIndex];
                        ParameterMetadata nuPM = nuParameterMetadata[surfacePointIndex];
                        assertTrue(nuPM is SwaptionSurfaceExpiryTenorParameterMetadata);
                        SwaptionSurfaceExpiryTenorParameterMetadata pmNuSabr = (SwaptionSurfaceExpiryTenorParameterMetadata)nuPM;
                        assertEquals(tenorYears, pmNuSabr.Tenor);
                        assertEquals(time, pmNuSabr.YearFraction, TOLERANCE_EXPIRY);
                        DoubleArray nuSensitivityToData = nuJacobian[surfacePointIndex];

                        for (int loopmoney = 0; loopmoney < MONEYNESS.size(); loopmoney++)
                        {
                            if (!double.IsNaN(DATA_LOGNORMAL[looptenor][loopexpiry][loopmoney]))
                            {
                                double[] alphaShifted = new double[2];
                                double[] rhoShifted   = new double[2];
                                double[] nuShifted    = new double[2];
                                for (int loopsign = 0; loopsign < 2; loopsign++)
                                {
                                    TenorRawOptionData dataShifted = SabrSwaptionCalibratorSmileTestUtils.rawDataShiftPoint(TENORS, EXPIRIES, ValueType.SIMPLE_MONEYNESS, MONEYNESS, ValueType.BLACK_VOLATILITY, DATA_LOGNORMAL, looptenor, loopexpiry, loopmoney, (2 * loopsign - 1) * fdShift);
                                    SabrParametersSwaptionVolatilities calibratedShifted = SABR_CALIBRATION.calibrateWithFixedBetaAndShift(DEFINITION, CALIBRATION_TIME, dataShifted, MULTICURVE, betaSurface, shiftSurface);
                                    alphaShifted[loopsign] = calibratedShifted.Parameters.AlphaSurface.zValue(time, tenorYears);
                                    rhoShifted[loopsign]   = calibratedShifted.Parameters.RhoSurface.zValue(time, tenorYears);
                                    nuShifted[loopsign]    = calibratedShifted.Parameters.NuSurface.zValue(time, tenorYears);
                                }
                                double alphaSensitivityComputed = alphaSensitivityToData.get(availableDataIndex);
                                double alphaSensitivityExpected = (alphaShifted[1] - alphaShifted[0]) / (2 * fdShift);
                                checkAcceptable(alphaSensitivityComputed, alphaSensitivityExpected, TOLERANCE_PARAM_SENSITIVITY, "Alpha: " + looptenor + " / " + loopexpiry + " / " + loopmoney);
                                double rhoSensitivityComputed = rhoSensitivityToData.get(availableDataIndex);
                                double rhoSensitivityExpected = (rhoShifted[1] - rhoShifted[0]) / (2 * fdShift);
                                checkAcceptable(rhoSensitivityComputed, rhoSensitivityExpected, TOLERANCE_PARAM_SENSITIVITY, "Rho: " + looptenor + " / " + loopexpiry + " / " + loopmoney);
                                double nuSensitivityComputed = nuSensitivityToData.get(availableDataIndex);
                                double nuSensitivityExpected = (nuShifted[1] - nuShifted[0]) / (2 * fdShift);
                                checkAcceptable(nuSensitivityComputed, nuSensitivityExpected, TOLERANCE_PARAM_SENSITIVITY, "Nu: " + looptenor + " / " + loopexpiry + " / " + loopmoney);
                                availableDataIndex++;
                            }
                        }
                        surfacePointIndex++;
                    }
                }
            }
        }
Esempio n. 60
0
 /// <summary>
 /// Set the date range to be queried
 /// </summary>
 /// <param name="start">Start date of range</param>
 /// <param name="end">End date of range</param>
 /// <returns>MasQuery</returns>
 public MasQuery InAbsoluteDateRange(LocalDate start, LocalDate end)
 {
     _inAbsoluteDateRange(start, end);
     return(this);
 }