public static DateTime ConvertToLocalTime(this DateTime utcDateTime, string timeZoneId) { DateTime dUtc; switch (utcDateTime.Kind) { case DateTimeKind.Utc: dUtc = utcDateTime; break; case DateTimeKind.Local: dUtc = utcDateTime.ToUniversalTime(); break; default: //DateTimeKind.Unspecified dUtc = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc); break; } var timeZone = tzSource.GetZoneOrNull(timeZoneId); var instant = Instant.FromDateTimeUtc(dUtc); var zoned = new ZonedDateTime(instant, timeZone); return new DateTime( zoned.Year, zoned.Month, zoned.Day, zoned.Hour, zoned.Minute, zoned.Second, zoned.Millisecond, DateTimeKind.Unspecified); }
public void AmbiguousStartOfDay_TransitionAfterMidnight() { // Occurrence before transition var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 0, 0).WithOffset(Offset.FromHours(-2)), TransitionBackwardAfterMidnightZone); var actual = TransitionBackwardAfterMidnightZone.AtStartOfDay(TransitionDate); Assert.AreEqual(expected, actual); }
public void SkippedStartOfDay_TransitionAtMidnight() { // 1am because of the skip var expected = new ZonedDateTime(new LocalDateTime(2000, 6, 1, 1, 0).WithOffset(Offset.FromHours(-1)), TransitionForwardAtMidnightZone); var actual = TransitionForwardAtMidnightZone.AtStartOfDay(TransitionDate); Assert.AreEqual(expected, actual); }
public StoreTests() { store = GoogleCalendarStore.CreateForTestingWithTempCalendar("*****@*****.**").Result; var now = Instant.FromUtc(2014, 1, 18, 22, 50, 0); var timeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); localNow = new ZonedDateTime(now, timeZone); }
public DateTime DateTimeUtcToLocalWithOlsenZone(DateTime dateTimeUtc, string olsenTimeZone) { var dateTimeZoneProvider = DateTimeZoneProviders.Tzdb; var dateTimeZone = dateTimeZoneProvider[olsenTimeZone]; //var utcInstant = new Instant(dateTimeUtc.Ticks); var utcInstant = Instant.FromDateTimeUtc(dateTimeUtc); var zonedDateTime = new ZonedDateTime(utcInstant, dateTimeZone); return zonedDateTime.ToDateTimeUnspecified(); }
/// <summary> /// Constructs an instance from the given information. /// </summary> /// <remarks> /// <para> /// User code is unlikely to need to deliberately call this constructor except /// possibly for testing. /// </para> /// <para> /// The two mappings must have the same local time and time zone. /// </para> /// </remarks> /// <param name="earlierMapping">The earlier possible mapping</param> /// <param name="laterMapping">The later possible mapping</param> public AmbiguousTimeException(ZonedDateTime earlierMapping, ZonedDateTime laterMapping) : base("Local time " + earlierMapping.LocalDateTime + " is ambiguous in time zone " + earlierMapping.Zone.Id) { EarlierMapping = earlierMapping; LaterMapping = laterMapping; Preconditions.CheckArgument(earlierMapping.Zone == laterMapping.Zone, nameof(laterMapping), "Ambiguous possible values must use the same time zone"); Preconditions.CheckArgument(earlierMapping.LocalDateTime == laterMapping.LocalDateTime, nameof(laterMapping), "Ambiguous possible values must have the same local date/time"); }
/// <summary> /// Constructs an instance from the given information. /// </summary> /// <remarks> /// User code is unlikely to need to deliberately call this constructor except /// possibly for testing. /// </remarks> /// <param name="localDateTime">The local date and time that was ambiguous</param> /// <param name="zone">The time zone in which the mapping is ambiguous</param> /// <param name="earlierMapping">The earlier possible mapping</param> /// <param name="laterMapping">The later possible mapping</param> public AmbiguousTimeException(LocalDateTime localDateTime, DateTimeZone zone, ZonedDateTime earlierMapping, ZonedDateTime laterMapping) : base("Local time " + localDateTime + " is ambiguous in time zone " + zone.Id) { this.localDateTime = localDateTime; this.zone = zone; this.earlierMapping = earlierMapping; this.laterMapping = laterMapping; }
public RaceEntity(string name, SeasonReference season, ZonedDateTime raceDateTime, string url) { if (name == null) throw new ArgumentNullException("name"); if (season == null) throw new ArgumentNullException("season"); if (url == null) throw new ArgumentNullException("url"); Name = name; Season = season; RaceDateTime = raceDateTime; Url = url; }
public void Khartoum() { DateTimeZone khartoum = DateTimeZone.ForId("Africa/Khartoum"); Assert.IsNotNull(khartoum); Instant utc = Instant.FromUtc(2000, 1, 1, 0, 0, 0); ZonedDateTime inKhartoum = new ZonedDateTime(utc, khartoum); LocalDateTime expectedLocal = new LocalDateTime(2000, 1, 1, 2, 0); Assert.AreEqual(expectedLocal, inKhartoum.LocalDateTime); // Khartoum changed from +2 to +3 on January 15th 2000 utc = Instant.FromUtc(2000, 1, 16, 0, 0, 0); inKhartoum = new ZonedDateTime(utc, khartoum); expectedLocal = new LocalDateTime(2000, 1, 16, 3, 0); Assert.AreEqual(expectedLocal, inKhartoum.LocalDateTime); }
public void TestPeriod() { ////ZonedDateTime var now = SystemClock.Instance.Now; var dtzi = DateTimeZoneProviders.Tzdb; var berlinTz = dtzi["Europe/Berlin"]; var berlinNow = new ZonedDateTime(now, berlinTz); ////2014-05-08T22:42:08 Europe/Berlin (+02) //Console.WriteLine(berlinNow); var fourthieth = new LocalDate(2023, 4, 19); var today = berlinNow.LocalDateTime.Date; Period period = Period.Between(today, fourthieth, PeriodUnits.Days); Console.WriteLine(period); //P3257D Period between = Period.Between(today, fourthieth, PeriodUnits.YearMonthDay); Console.WriteLine(between); //P8Y11M }
public void CanLoadNodaTimeResourceFromOnePointOneRelease() { var assembly = typeof(TzdbDateTimeZoneSourceTest).Assembly; TzdbDateTimeZoneSource source; using (Stream stream = assembly.GetManifestResourceStream("NodaTime.Test.TestData.Tzdb2013bFromNodaTime1.1.nzd")) { source = TzdbDateTimeZoneSource.FromStream(stream); } Assert.AreEqual("TZDB: 2013b (mapping: 8274)", source.VersionId); var utc = Instant.FromUtc(2007, 8, 24, 9, 30, 0); // Test a regular zone with rules. var london = source.ForId("Europe/London"); var inLondon = new ZonedDateTime(utc, london); var expectedLocal = new LocalDateTime(2007, 8, 24, 10, 30); Assert.AreEqual(expectedLocal, inLondon.LocalDateTime); // Test a fixed-offset zone. var utcFixed = source.ForId("Etc/UTC"); var inUtcFixed = new ZonedDateTime(utc, utcFixed); expectedLocal = new LocalDateTime(2007, 8, 24, 9, 30); Assert.AreEqual(expectedLocal, inUtcFixed.LocalDateTime); // Test an alias. var jersey = source.ForId("Japan"); // Asia/Tokyo var inJersey = new ZonedDateTime(utc, jersey); expectedLocal = new LocalDateTime(2007, 8, 24, 18, 30); Assert.AreEqual(expectedLocal, inJersey.LocalDateTime); // Test ZoneLocations. var france = source.ZoneLocations.Single(g => g.CountryName == "France"); // Tolerance of about 2 seconds Assert.AreEqual(48.86666, france.Latitude, 0.00055); Assert.AreEqual(2.3333, france.Longitude, 0.00055); Assert.AreEqual("Europe/Paris", france.ZoneId); Assert.AreEqual("FR", france.CountryCode); Assert.AreEqual("", france.Comment); }
/// <summary> /// Restricted copy constructor. </summary> /// <param name="beanToCopy"> the bean to copy from, not null </param> internal Builder(NormalIborFutureOptionExpirySimpleMoneynessVolatilities beanToCopy) { this.index_Renamed = beanToCopy.Index; this.valuationDateTime_Renamed = beanToCopy.ValuationDateTime; this.surface_Renamed = beanToCopy.Surface; }
/// <summary> /// Sets the valuation date-time. /// <para> /// The volatilities are calibrated for this date-time. /// </para> /// </summary> /// <param name="valuationDateTime"> the new value, not null </param> /// <returns> this, for chaining, not null </returns> public Builder valuationDateTime(ZonedDateTime valuationDateTime) { JodaBeanUtils.notNull(valuationDateTime, "valuationDateTime"); this.valuationDateTime_Renamed = valuationDateTime; return(this); }
private static ZonedDateTimeRange GenerateZonedDateTimeRangeWithStepLargerThanRange( out ZonedDateTime start, out ZonedDateTime end, out Duration step) { // subtracting MinDuration twice from max length to give space for oversized step without converting type to perform the calculation to do so Duration length = RandomDuration(MinDuration, MaxDuration - MinDuration - MinDuration); start = RandomZonedDateTime(TestMinZonedDateTime, TestMaxZonedDateTime - length); end = start + length; step = RandomDuration(length + MinDuration, length + MinDuration + MinDuration); return new ZonedDateTimeRange(start, end, step); }
/// <summary> /// Computes the present value sensitivity to SABR parameters by replication in SABR framework with extrapolation on the right. /// </summary> /// <param name="cmsPeriod"> the CMS </param> /// <param name="provider"> the rates provider </param> /// <param name="swaptionVolatilities"> the swaption volatilities </param> /// <returns> the present value sensitivity </returns> public PointSensitivityBuilder presentValueSensitivityModelParamsSabr(CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.Currency; SwapIndex index = cmsPeriod.Index; ResolvedSwap swap = cmsPeriod.UnderlyingSwap; double dfPayment = provider.discountFactor(ccy, cmsPeriod.PaymentDate); ZonedDateTime valuationDate = swaptionVolatilities.ValuationDateTime; LocalDate fixingDate = cmsPeriod.FixingDate; ZonedDateTime expiryDate = fixingDate.atTime(index.FixingTime).atZone(index.FixingZone); double tenor = swaptionVolatilities.tenor(swap.StartDate, swap.EndDate); if (provider.ValuationDate.isAfter(cmsPeriod.PaymentDate)) { return(PointSensitivityBuilder.none()); } if (!fixingDate.isAfter(valuationDate.toLocalDate())) { double?fixedRate = provider.timeSeries(cmsPeriod.Index).get(fixingDate); if (fixedRate.HasValue) { return(PointSensitivityBuilder.none()); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new System.ArgumentException(Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.Index, fixingDate)); } } double expiryTime = swaptionVolatilities.relativeTime(expiryDate); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.Strike; double forward = swapPricer.parRate(swap, provider); double eta = index.Template.Convention.FixedLeg.DayCount.relativeYearFraction(cmsPeriod.PaymentDate, swap.StartDate); CmsIntegrantProvider intProv = new CmsIntegrantProvider(this, cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment / intProv.h(forward) * intProv.g(forward); double factor2 = factor * intProv.k(strikeCpn); double[] strikePartPrice = intProv.SabrExtrapolation.priceAdjointSabr(Math.Max(0d, strikeCpn + shift), intProv.PutCall).Derivatives.multipliedBy(factor2).toArray(); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL_VEGA, NUM_ITER); double[] totalSensi = new double[4]; for (int loopparameter = 0; loopparameter < 4; loopparameter++) { double integralPart = 0d; System.Func <double, double> integrant = intProv.integrantVega(loopparameter); try { if (intProv.PutCall.Call) { integralPart = dfPayment * integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPart = -dfPayment *integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn); } } catch (Exception e) { throw new Exception(e); } totalSensi[loopparameter] = (strikePartPrice[loopparameter] + integralPart) * cmsPeriod.Notional * cmsPeriod.YearFraction; } SwaptionVolatilitiesName name = swaptionVolatilities.Name; return(PointSensitivityBuilder.of(SwaptionSabrSensitivity.of(name, expiryTime, tenor, ALPHA, ccy, totalSensi[0]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, BETA, ccy, totalSensi[1]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, RHO, ccy, totalSensi[2]), SwaptionSabrSensitivity.of(name, expiryTime, tenor, NU, ccy, totalSensi[3]))); }
public void XmlSerialization_NonIso() { DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb; var zone = DateTimeZoneProviders.Tzdb["America/New_York"]; var localDateTime = new LocalDateTime(2013, 6, 12, 17, 53, 23, CalendarSystem.Julian); var value = new ZonedDateTime(localDateTime.WithOffset(Offset.FromHours(-4)), zone); TestHelper.AssertXmlRoundtrip(value, "<value zone=\"America/New_York\" calendar=\"Julian\">2013-06-12T17:53:23-04</value>"); }
public void DefaultConstructor() { var actual = new ZonedDateTime(); Assert.AreEqual(new LocalDateTime(1, 1, 1, 0, 0), actual.LocalDateTime); Assert.AreEqual(Offset.Zero, actual.Offset); Assert.AreEqual(DateTimeZone.Utc, actual.Zone); }
private DaylightSavingInformation GetDaylightSavingInfo(ZonedDateTime zonedDateTime) { if (zonedDateTime.GetZoneInterval().IsoLocalEnd.Year > 10000) return DaylightSavingInformation.CreateWithNoDaylightSavings(); var daylightSavingInfo = new DaylightSavingInformation { IsInDaylightSavingsTime = zonedDateTime.GetZoneInterval().Savings.Milliseconds > 0 }; if (daylightSavingInfo.IsInDaylightSavingsTime) { daylightSavingInfo.End = zonedDateTime.GetZoneInterval().IsoLocalEnd; daylightSavingInfo.EndDateSavingPutBackInMilliseconds = zonedDateTime.GetZoneInterval().Savings.Milliseconds; daylightSavingInfo.HasEnded = daylightSavingInfo.End.ToDateTimeUnspecified() < zonedDateTime.LocalDateTime.ToDateTimeUnspecified(); daylightSavingInfo.Start = zonedDateTime.GetZoneInterval().IsoLocalStart.Minus(Period.FromMilliseconds(zonedDateTime.GetZoneInterval().Savings.Milliseconds)); daylightSavingInfo.StartDateSavingPutForwardInMilliseconds = zonedDateTime.GetZoneInterval().Savings.Milliseconds; daylightSavingInfo.HasStarted = daylightSavingInfo.Start.ToDateTimeUnspecified() < zonedDateTime.LocalDateTime.ToDateTimeUnspecified(); } else { var previousZoneInterval = zonedDateTime.GetZoneInterval().Start.Minus(Duration.FromMilliseconds(1)).InZone(zonedDateTime.Zone).GetZoneInterval(); daylightSavingInfo.End = previousZoneInterval.IsoLocalEnd; daylightSavingInfo.EndDateSavingPutBackInMilliseconds = previousZoneInterval.Savings.Milliseconds; daylightSavingInfo.HasEnded = daylightSavingInfo.End.ToDateTimeUnspecified() < zonedDateTime.LocalDateTime.ToDateTimeUnspecified(); if (!daylightSavingInfo.NoDaylightSavings) { var nextZoneInterval = zonedDateTime.GetZoneInterval().End.Plus(Duration.FromMilliseconds(1)).InZone(zonedDateTime.Zone).GetZoneInterval(); daylightSavingInfo.Start = nextZoneInterval.IsoLocalStart.Minus(Period.FromMilliseconds(nextZoneInterval.Savings.Milliseconds)); daylightSavingInfo.StartDateSavingPutForwardInMilliseconds = nextZoneInterval.Savings.Milliseconds; daylightSavingInfo.HasStarted = daylightSavingInfo.Start.ToDateTimeUnspecified() < zonedDateTime.LocalDateTime.ToDateTimeUnspecified(); } } return daylightSavingInfo; }
public RoleEdited(Role role, UserId editedBy, DomainEventId id, ZonedDateTime created) : base(id, TYPE, created) { RoleId = role.Id; Rolename = role.Rolename; EditedBy = editedBy; }
public static PKError SwitchMoveBeforeSecondLast(ZonedDateTime time) => new PKError($"Can't move switch to before last switch time ({Formats.ZonedDateTimeFormat.Format(time)}), as it would cause conflicts.");
/// <summary> /// Returns the date time parsed from the given string. /// </summary> /// <param name="expireTime">The expire time.</param> /// <returns>The converted <see cref="ZonedDateTime"/>.</returns> public static string ToExpireTimeFormat(ZonedDateTime expireTime) { // ReSharper disable once StringLiteralTypo (correct format) return(expireTime.ToString("MMddyyyyHHmmss", CultureInfo.InvariantCulture.DateTimeFormat)); }
public static string ToPrettyTime(this ZonedDateTime dateTime) { return(dateTime.ToString("HH:mm", CultureInfo.InvariantCulture)); }
public static DateTimeOffset NowInCentralEuropeanTime() { var zonedDateTime = new ZonedDateTime(SystemClock.Instance.GetCurrentInstant(), DateTimeZoneProviders.Tzdb["Europe/Paris"]); return(zonedDateTime.ToDateTimeOffset()); }
private async Task <ServiceResponse> InteractivePokemonResolve(Type textResource, ZonedDateTime requestStartInUtc, DateTimeZone userZone, TimeSpan timeLeft, RaidOcrResult raidOcrResult, FenceConfiguration[] fences, int interactiveLimit) { if (InteractiveServiceHelper.UseInteractiveMode(raidOcrResult.Pokemon.Results)) { var pokemonCallbacks = InteractiveServiceHelper.GenericCreateCallbackAsync(interactiveLimit, (selectedPokemon) => InteractiveGymResolve(textResource, requestStartInUtc, userZone, timeLeft, GetRaidbossPokemonById(selectedPokemon, raidOcrResult).Raidboss.Level, GetRaidbossPokemonById(selectedPokemon, raidOcrResult), raidOcrResult, fences, interactiveLimit), pokemon => pokemon.Pokemon.Id, (pokemon, list) => Task.FromResult(pokemon.Pokemon.Name), list => LocalizationService.Get(textResource, "Pokemon_Errors_ToManyFound", list.Count, raidOcrResult.Pokemon.OcrValue, interactiveLimit, "raidboss-"), list => LocalizationService.Get(textResource, "Pokemon_Errors_InteractiveMode", list.Count, raidOcrResult.Pokemon.OcrValue, "raidboss-"), raidOcrResult.Pokemon.Results.Select(e => e.Key).ToList()); return(await pokemonCallbacks); } var raidbossPokemon = raidOcrResult.Pokemon.GetFirst(); return(await InteractiveGymResolve(textResource, requestStartInUtc, userZone, timeLeft, raidbossPokemon.Raidboss.Level, raidbossPokemon, raidOcrResult, fences, interactiveLimit)); }
private async Task <ServiceResponse> InteractiveGymResolve(Type textResource, ZonedDateTime requestStartInUtc, DateTimeZone userZone, TimeSpan timeLeft, int level, RaidbossPokemon raidbossPokemon, RaidOcrResult raidOcrResult, FenceConfiguration[] fences, int interactiveLimit) { if (!InteractiveServiceHelper.UseInteractiveMode(raidOcrResult.Gym.Results)) { return(await AddRaidAsync(textResource, requestStartInUtc, userZone, raidOcrResult.Gym.GetFirst().Id, level, raidbossPokemon, timeLeft, raidOcrResult, fences, interactiveLimit)); } if (raidOcrResult.Gym.Results == null || raidOcrResult.Gym.Results.Length == 0) { return(new ServiceResponse(false, LocalizationService.Get(textResource, "Gyms_Errors_NothingFound", raidOcrResult.Gym.OcrValue))); } var gymCallbacks = InteractiveServiceHelper.GenericCreateCallbackAsync(interactiveLimit, (selectedGym) => AddRaidAsync(textResource, requestStartInUtc, userZone, selectedGym, level, raidbossPokemon, timeLeft, raidOcrResult, fences, interactiveLimit), gym => gym.Id, (gym, list) => GymService.GetGymNameWithAdditionAsync(gym, list), list => LocalizationService.Get(textResource, "Gyms_Errors_ToManyFound", list.Count, raidOcrResult.Gym.OcrValue, interactiveLimit), list => LocalizationService.Get(textResource, "Gyms_Errors_InteractiveMode", list.Count, raidOcrResult.Gym.OcrValue), raidOcrResult.Gym.Results.Select(e => e.Key).ToList()); return(await gymCallbacks); }
public void UnambiguousStartOfDay() { // Just a simple midnight in March. var expected = new ZonedDateTime(new LocalDateTime(2000, 3, 1, 0, 0).WithOffset(Offset.FromHours(-2)), TransitionForwardAtMidnightZone); var actual = TransitionForwardAtMidnightZone.AtStartOfDay(new LocalDate(2000, 3, 1)); Assert.AreEqual(expected, actual); }
public static void Test_ZonedDateTime_ForDisplay(int year, int month, int day, int hour, int minute, int second, string expectedText) { var zonedDateTime = new ZonedDateTime(Instant.FromUtc(year, month, day, hour, minute, second), DateCalculator.LondonTimeZone); Assert.Equal(expectedText, zonedDateTime.ForDisplay()); }
public void ConvertDateStringIntoDateTime() { string timeZone = "America/Los_Angeles"; fakeClock.Reset(GetLocalInstant(new LocalDateTime(2020, 1, 15, 11, 30), timeZone)); ZonedDateTime nextDayDateTime = helperMethods.ConvertDateStringIntoDateTime("day", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 16, 12, 0), timeZone), nextDayDateTime); ZonedDateTime sundayDateTime = helperMethods.ConvertDateStringIntoDateTime("sunday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 19, 12, 0), timeZone), sundayDateTime); ZonedDateTime mondayDateTime = helperMethods.ConvertDateStringIntoDateTime("monday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 20, 12, 0), timeZone), mondayDateTime); ZonedDateTime tuesdayDateTime = helperMethods.ConvertDateStringIntoDateTime("tuesday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 21, 12, 0), timeZone), tuesdayDateTime); ZonedDateTime wednesdayDateTime = helperMethods.ConvertDateStringIntoDateTime("wednesday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 22, 12, 0), timeZone), wednesdayDateTime); ZonedDateTime thursdayDateTime = helperMethods.ConvertDateStringIntoDateTime("thursday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 16, 12, 0), timeZone), thursdayDateTime); ZonedDateTime fridayDateTime = helperMethods.ConvertDateStringIntoDateTime("friday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 17, 12, 0), timeZone), fridayDateTime); ZonedDateTime saturdayDateTime = helperMethods.ConvertDateStringIntoDateTime("saturday", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 18, 12, 0), timeZone), saturdayDateTime); ZonedDateTime beginningOfTheMonthDateTime = helperMethods.ConvertDateStringIntoDateTime("beginning of the month", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 2, 1, 12, 0), timeZone), beginningOfTheMonthDateTime); ZonedDateTime endOfTheMonthDateTime = helperMethods.ConvertDateStringIntoDateTime("end of the month", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 31, 12, 0), timeZone), endOfTheMonthDateTime); ZonedDateTime dateAfterNowDateTime = helperMethods.ConvertDateStringIntoDateTime("18", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 18, 12, 0), timeZone), dateAfterNowDateTime); ZonedDateTime dateBeforeNowDateTime = helperMethods.ConvertDateStringIntoDateTime("14", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 2, 14, 12, 0), timeZone), dateBeforeNowDateTime); ZonedDateTime parsedLocalDateDateTime = helperMethods.ConvertDateStringIntoDateTime("2020-01-20", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 20, 12, 0), timeZone), parsedLocalDateDateTime); ZonedDateTime parsedLocalDateTimeDateTime = helperMethods.ConvertDateStringIntoDateTime("2020-01-20T10:30", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 20, 10, 30), timeZone), parsedLocalDateTimeDateTime); ZonedDateTime parsedLocalDateTimeWithSecondsDateTime = helperMethods.ConvertDateStringIntoDateTime("2020-01-20T10:30:01", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 1, 20, 10, 30, 1), timeZone), parsedLocalDateTimeWithSecondsDateTime); // "edge cases" aka February // on Feb 29th, requesting 30th of every month will get set to March 30th because we don't schedule // on the day we're on fakeClock.Reset(GetLocalInstant(new LocalDateTime(2020, 2, 29, 11, 30), timeZone)); ZonedDateTime march30 = helperMethods.ConvertDateStringIntoDateTime("30", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 3, 30, 12, 0), timeZone), march30); // on Feb 15th, requesting 30th of every month will get set to Feb 29th because Feb only has 29 days fakeClock.Reset(GetLocalInstant(new LocalDateTime(2020, 2, 15, 11, 30), timeZone)); ZonedDateTime feb29 = helperMethods.ConvertDateStringIntoDateTime("30", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 2, 29, 12, 0), timeZone), feb29); // on March 31st, requesting 31st of every month will get set to April 30th because we don't schedule // on the day we're on and April only has 30 days fakeClock.Reset(GetLocalInstant(new LocalDateTime(2020, 3, 31, 11, 30), timeZone)); ZonedDateTime april30 = helperMethods.ConvertDateStringIntoDateTime("31", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 4, 30, 12, 0), timeZone), april30); // on Jan 31st, requesting the 31st of every month will get set to Feb 29th because we don't schedule // on the day we're on and Feb only has 29 days (in a leap year) fakeClock.Reset(GetLocalInstant(new LocalDateTime(2020, 1, 31, 11, 30), timeZone)); ZonedDateTime feb292 = helperMethods.ConvertDateStringIntoDateTime("31", timeZone, fakeClock); Assert.Equal(CreateZonedDateTime(new LocalDateTime(2020, 2, 29, 12, 0), timeZone), feb292); }
public void Construct_FromLocal_ValidUnambiguousOffset() { SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3); LocalDateTime local = new LocalDateTime(2000, 1, 2, 3, 4, 5); ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.EarlyInterval.WallOffset); Assert.AreEqual(zoned, local.InZoneStrictly(zone)); }
public virtual void SupportsMinusZonedDateTime(ZonedDateTime zonedDateTime) { SupportsPropertyOrMethod(x => x.Minus(zonedDateTime)); }
public void XmlSerialization_Iso() { DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb; var zone = DateTimeZoneProviders.Tzdb["America/New_York"]; var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone); TestHelper.AssertXmlRoundtrip(value, "<value zone=\"America/New_York\">2013-04-12T17:53:23-04</value>"); }
public virtual void SupportsMinusZonedDateTimeOperator(ZonedDateTime zonedDateTime) { SupportsPropertyOrMethod(x => x - zonedDateTime); }
public void ZonedDateTimeConverter() { // Deliberately give it an ambiguous local time, in both ways. var zone = DateTimeZoneProviders.Tzdb["Europe/London"]; var earlierValue = new ZonedDateTime(new LocalDateTime(2012, 10, 28, 1, 30), zone, Offset.FromHours(1)); var laterValue = new ZonedDateTime(new LocalDateTime(2012, 10, 28, 1, 30), zone, Offset.FromHours(0)); string earlierJson = "\"2012-10-28T01:30:00+01 Europe/London\""; string laterJson = "\"2012-10-28T01:30:00Z Europe/London\""; var converter = NodaConverters.CreateZonedDateTimeConverter(DateTimeZoneProviders.Tzdb); AssertConversions(earlierValue, earlierJson, converter); AssertConversions(laterValue, laterJson, converter); }
static void Main(string[] args) { // Initialize the PRNG. // Parallel version uses a ThreadSafe PRNG. Globals.Random = new RandomOps.ThreadSafe.CMWC4096(); // Set max number of threads allowed. Globals.ParallelOptions.MaxDegreeOfParallelism = 8; // Create a fitness trace for tracing the progress of meta-optimization. int MaxMeanIntervals = 3000; FitnessTrace fitnessTrace = new FitnessTraceMean(MetaNumIterations, MaxMeanIntervals); FeasibleTrace feasibleTrace = new FeasibleTrace(MetaNumIterations, MaxMeanIntervals, fitnessTrace); // Assign the fitness trace to the meta-optimizer. MetaOptimizer.FitnessTrace = feasibleTrace; // Output settings. Console.WriteLine("Meta-Optimization of benchmark problems. (Parallel)", Color.Yellow); Console.WriteLine(); Console.WriteLine("Meta-method: {0}", MetaOptimizer.Name, Color.Yellow); Console.WriteLine("Using following parameters:", Color.Yellow); Tools.PrintParameters(MetaOptimizer, MetaParameters); Console.WriteLine("Number of meta-runs: {0}", MetaNumRuns, Color.Yellow); Console.WriteLine("Number of meta-iterations: {0}", MetaNumIterations, Color.Yellow); Console.WriteLine(); Console.WriteLine("Method to be meta-optimized: {0}", Optimizer.Name, Color.Yellow); Console.WriteLine("Number of benchmark problems: {0}", WeightedProblems.Length, Color.Yellow); foreach (var t in WeightedProblems) { Problem problem = t.Problem; double weight = t.Weight; Console.WriteLine("\t({0})\t{1}", weight, problem.Name, Color.Yellow); } Console.WriteLine("Dimensionality for each benchmark problem: {0}", Dim, Color.Yellow); Console.WriteLine("Number of runs per benchmark problem: {0}", NumRuns, Color.Yellow); Console.WriteLine("Number of iterations per run: {0}", NumIterations, Color.Yellow); Console.WriteLine("(Search-space mangling not supported for parallel meta-optimization.)", Color.Yellow); Console.WriteLine(); Console.WriteLine("0/1 Boolean whether optimizer's control parameters are feasible.", Color.Yellow); Console.WriteLine("*** Indicates meta-fitness/feasibility is an improvement.", Color.Yellow); // Start-time. ZonedDateTime t1 = LocalDateTime.FromDateTime(DateTime.Now).InUtc(); // Perform the meta-optimization runs. double fitness = MetaRepeat.Fitness(MetaParameters); // End-time. ZonedDateTime t2 = LocalDateTime.FromDateTime(DateTime.Now).InUtc(); Duration diff = t2.ToInstant() - t1.ToInstant(); // Compute result-statistics. Statistics.Compute(); // Retrieve best-found control parameters for the optimizer. double[] bestParameters = Statistics.BestResult.Parameters; // Output results and statistics. Console.WriteLine(); Console.WriteLine("Best found parameters for {0} optimizer:", Optimizer.Name, Color.Green); Tools.PrintParameters(Optimizer, bestParameters); Console.WriteLine("Parameters written in array notation:", Color.Green); Console.WriteLine("\t{0}", Tools.ArrayToString(bestParameters, 4), Color.Green); Console.WriteLine("Best parameters have meta-fitness: {0}", Tools.FormatNumber(Statistics.FitnessMin), Color.Green); Console.WriteLine("Worst meta-fitness: {0}", Tools.FormatNumber(Statistics.FitnessMax), Color.Green); Console.WriteLine("Mean meta-fitness: {0}", Tools.FormatNumber(Statistics.FitnessMean), Color.Green); Console.WriteLine("StdDev for meta-fitness: {0}", Tools.FormatNumber(Statistics.FitnessStdDev), Color.Green); // Output best found parameters. Console.WriteLine(); Console.WriteLine("Best {0} found parameters:", LogSolutions.Capacity, Color.Green); foreach (Solution candidateSolution in LogSolutions.Log) { Console.WriteLine("\t{0}\t{1}\t{2}", Tools.ArrayToStringRaw(candidateSolution.Parameters, 4), Tools.FormatNumber(candidateSolution.Fitness), (candidateSolution.Feasible) ? (1) : (0), Color.Green); } // Output time-usage. Console.WriteLine(); Console.WriteLine("Time usage: {0}", t2 - t1); // Output fitness and feasible trace. string traceFilename = MetaOptimizer.Name + "-" + Optimizer.Name + "-" + WeightedProblems.Length + "Bnch" + "-" + DimFactor + "xDim.txt"; fitnessTrace.WriteToFile("MetaFitnessTrace-" + traceFilename); feasibleTrace.WriteToFile("MetaFeasibleTrace-" + traceFilename); //Console.WriteLine("Press any key to exit ..."); //Console.ReadKey(); }
private static ZonedDateTimeRange GenerateZonedDateTimeRangeWithStepSmallerThanRange( out ZonedDateTime start, out ZonedDateTime end, out Duration step) { Duration length = RandomDuration(MinDuration + MinDuration, MaxDuration); start = RandomZonedDateTime(TestMinZonedDateTime, TestMaxZonedDateTime - length); end = start + length; step = RandomDuration(MinDuration, length - MinDuration); return new ZonedDateTimeRange(start, end, step); }
/// <summary> /// Returns a string formatted to the millisecond (ISO-8601) from the given /// <see cref="ZonedDateTime"/>. /// </summary> /// <param name="time">The time.</param> /// <returns>A <see cref="string"/>.</returns> public static string ToIso8601String(this ZonedDateTime time) { Debug.NotDefault(time, nameof(time)); return(time.ToString(Iso8601DateTimeParsePattern, CultureInfo.InvariantCulture.DateTimeFormat) + "Z"); }
/// <summary> /// Choose a random date and time within a given range. /// </summary> /// <param name="minimum">The minimum date possible.</param> /// <param name="maximum">The maximum date possible.</param> /// <returns> /// A <see cref="T:System.ZonedDateTime"/> between <paramref name="minimum"/> and <paramref name="maximum"/>. /// </returns> private static ZonedDateTime RandomZonedDateTime(ZonedDateTime minimum, ZonedDateTime maximum) { return minimum + Duration.FromTicks((long)((maximum.ToInstant() - minimum.ToInstant()).Ticks * Random.NextDouble())); }
//------------------------------------------------------------------------- /// <summary> /// Computes the present value by replication in SABR framework with extrapolation on the right. /// </summary> /// <param name="cmsPeriod"> the CMS </param> /// <param name="provider"> the rates provider </param> /// <param name="swaptionVolatilities"> the swaption volatilities </param> /// <returns> the present value </returns> public CurrencyAmount presentValue(CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.Currency; if (provider.ValuationDate.isAfter(cmsPeriod.PaymentDate)) { return(CurrencyAmount.zero(ccy)); } SwapIndex index = cmsPeriod.Index; ResolvedSwap swap = cmsPeriod.UnderlyingSwap; double dfPayment = provider.discountFactor(ccy, cmsPeriod.PaymentDate); ZonedDateTime valuationDate = swaptionVolatilities.ValuationDateTime; LocalDate fixingDate = cmsPeriod.FixingDate; double expiryTime = swaptionVolatilities.relativeTime(fixingDate.atTime(index.FixingTime).atZone(index.FixingZone)); double tenor = swaptionVolatilities.tenor(swap.StartDate, swap.EndDate); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.Strike; if (!fixingDate.isAfter(valuationDate.toLocalDate())) { double?fixedRate = provider.timeSeries(cmsPeriod.Index).get(fixingDate); if (fixedRate.HasValue) { double payoff = payOff(cmsPeriod.CmsPeriodType, strikeCpn, fixedRate.Value); return(CurrencyAmount.of(ccy, dfPayment * payoff * cmsPeriod.Notional * cmsPeriod.YearFraction)); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new System.ArgumentException(Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.Index, fixingDate)); } } double forward = swapPricer.parRate(swap, provider); if (expiryTime < MIN_TIME) { double payoff = payOff(cmsPeriod.CmsPeriodType, strikeCpn, forward); return(CurrencyAmount.of(ccy, dfPayment * payoff * cmsPeriod.Notional * cmsPeriod.YearFraction)); } double eta = index.Template.Convention.FixedLeg.DayCount.relativeYearFraction(cmsPeriod.PaymentDate, swap.StartDate); CmsIntegrantProvider intProv = new CmsIntegrantProvider(this, cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment / intProv.h(forward) * intProv.g(forward); double strikePart = factor * intProv.k(strikeCpn) * intProv.bs(strikeCpn); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL, NUM_ITER); double integralPart = 0d; System.Func <double, double> integrant = intProv.integrant(); try { if (intProv.PutCall.Call) { integralPart = dfPayment * integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPart = -dfPayment *integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn); } } catch (Exception e) { throw new MathException(e); } double priceCMS = (strikePart + integralPart); if (cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON)) { priceCMS -= dfPayment * shift; } priceCMS *= cmsPeriod.Notional * cmsPeriod.YearFraction; return(CurrencyAmount.of(ccy, priceCMS)); }
public AuthUserBuilder WithCreatedAt(ZonedDateTime createdAt) { _createdAt = createdAt; return(this); }
public static Instant NextValid( this Instant instant, Month month = Month.Every, Week week = Week.Every, Day day = Day.Every, WeekDay weekDay = WeekDay.Every, Hour hour = Hour.Zeroth, Minute minute = Minute.Zeroth, Second second = Second.Zeroth, [CanBeNull] CalendarSystem calendarSystem = null, [CanBeNull] DateTimeZone timeZone = null) { // Never case, if any are set to never, we'll never get a valid date. if ((month == Month.Never) || (week == Week.Never) || (day == Day.Never) || (weekDay == WeekDay.Never) || (hour == Hour.Never) || (minute == Minute.Never) || (second == Second.Never)) return Instant.MaxValue; if (calendarSystem == null) calendarSystem = CalendarSystem.Iso; if (timeZone == null) timeZone = DateTimeZone.Utc; Debug.Assert(calendarSystem != null); Debug.Assert(timeZone != null); // Move to next second. instant = instant.CeilingSecond(); // Every second case. if ((month == Month.Every) && (day == Day.Every) && (weekDay == WeekDay.Every) && (hour == Hour.Every) && (minute == Minute.Every) && (second == Second.Every) && (week == Week.Every)) return instant; // Get days and months. int[] days = Days(day).OrderBy(dy => dy).ToArray(); int[] months = month.Months().ToArray(); // Remove months where the first day isn't in the month. int firstDay = days.First(); if (firstDay > 28) { // 2000 is a leap year, so February has 29 days. months = months.Where(mn => calendarSystem.GetDaysInMonth(2000, mn) >= firstDay).ToArray(); if (months.Length < 1) return Instant.MaxValue; } // Get zoned date time. ZonedDateTime zdt = new ZonedDateTime(instant, timeZone, calendarSystem); int y = zdt.Year; int m = zdt.Month; int d = zdt.Day; int h = zdt.Hour; int n = zdt.Minute; int s = zdt.Second; int[] weeks = week.Weeks().ToArray(); IsoDayOfWeek[] weekDays = weekDay.WeekDays().ToArray(); int[] hours = hour.Hours().OrderBy(i => i).ToArray(); int[] minutes = minute.Minutes().OrderBy(i => i).ToArray(); int[] seconds = second.Seconds().ToArray(); do { foreach (int currentMonth in months) { if (currentMonth < m) continue; if (currentMonth > m) { d = 1; h = n = s = 0; } m = currentMonth; foreach (int currentDay in days) { if (currentDay < d) continue; if (currentDay > d) h = n = s = 0; d = currentDay; // Check day is valid for this month. if (d > calendarSystem.GetDaysInMonth(y, m)) break; // We have a potential day, check week and week day zdt = timeZone.AtLeniently(new LocalDateTime(y, m, d, h, n, s, calendarSystem)); if ((week != Week.Every) && (!weeks.Contains(zdt.WeekOfWeekYear))) continue; if ((weekDay != WeekDay.Every) && (!weekDays.Contains(zdt.IsoDayOfWeek))) continue; // We have a date match, check time. foreach (int currentHour in hours) { if (currentHour < h) continue; if (currentHour > h) n = s = 0; h = currentHour; foreach (int currentMinute in minutes) { if (currentMinute < n) continue; if (currentMinute > n) s = 0; n = currentMinute; foreach (int currentSecond in seconds) { if (currentSecond < s) continue; return timeZone.AtLeniently( new LocalDateTime(y, m, d, h, n, currentSecond, calendarSystem)).ToInstant(); } n = s = 0; } h = n = s = 0; } d = 1; } d = 1; h = n = s = 0; } y++; // Don't bother checking max year. if (y >= calendarSystem.MaxYear) return Instant.MaxValue; // Start next year m = d = 1; h = n = s = 0; } while (true); }
//------------------------------------------------------------------------- public double relativeTime(ZonedDateTime zonedDateTime) { ArgChecker.notNull(zonedDateTime, "date"); return(dayCount.relativeYearFraction(valuationDateTime.toLocalDate(), zonedDateTime.toLocalDate())); }
private readonly DayCount dayCount; // cached, not a property //------------------------------------------------------------------------- /// <summary> /// Obtains an instance from the volatility surface and the date-time for which it is valid. /// <para> /// The surface is specified by an instance of <seealso cref="Surface"/>, such as <seealso cref="InterpolatedNodalSurface"/>. /// The surface must contain the correct metadata: /// <ul> /// <li>The x-value type must be <seealso cref="ValueType#YEAR_FRACTION"/> /// <li>The y-value type must be <seealso cref="ValueType#SIMPLE_MONEYNESS"/> /// <li>The z-value type must be <seealso cref="ValueType#NORMAL_VOLATILITY"/> /// <li>The day count must be set in the additional information using <seealso cref="SurfaceInfoType#DAY_COUNT"/> /// </ul> /// Suitable surface metadata can be created using /// <seealso cref="Surfaces#normalVolatilityByExpirySimpleMoneyness(String, DayCount, MoneynessType)"/>. /// /// </para> /// </summary> /// <param name="index"> the Ibor index </param> /// <param name="surface"> the implied volatility surface </param> /// <param name="valuationDateTime"> the valuation date-time </param> /// <returns> the volatilities </returns> public static NormalIborFutureOptionExpirySimpleMoneynessVolatilities of(IborIndex index, ZonedDateTime valuationDateTime, Surface surface) { return(new NormalIborFutureOptionExpirySimpleMoneynessVolatilities(index, valuationDateTime, surface)); }
internal ContractDataTimeEvent(ZonedDateTime time, ContractTimeStatus status) { Time = time; Status = status; }
/// <summary> /// Computes the present value sensitivity to strike by replication in SABR framework with extrapolation on the right. /// </summary> /// <param name="cmsPeriod"> the CMS </param> /// <param name="provider"> the rates provider </param> /// <param name="swaptionVolatilities"> the swaption volatilities </param> /// <returns> the present value sensitivity </returns> public double presentValueSensitivityStrike(CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { ArgChecker.isFalse(cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON), "presentValueSensitivityStrike is not relevant for CMS coupon"); Currency ccy = cmsPeriod.Currency; SwapIndex index = cmsPeriod.Index; if (provider.ValuationDate.isAfter(cmsPeriod.PaymentDate)) { return(0d); } ResolvedSwap swap = cmsPeriod.UnderlyingSwap; double dfPayment = provider.discountFactor(ccy, cmsPeriod.PaymentDate); ZonedDateTime valuationDate = swaptionVolatilities.ValuationDateTime; LocalDate fixingDate = cmsPeriod.FixingDate; double tenor = swaptionVolatilities.tenor(swap.StartDate, swap.EndDate); ZonedDateTime expiryDate = fixingDate.atTime(index.FixingTime).atZone(index.FixingZone); double expiryTime = swaptionVolatilities.relativeTime(expiryDate); double strike = cmsPeriod.Strike; double shift = swaptionVolatilities.shift(expiryTime, tenor); if (!fixingDate.isAfter(valuationDate.toLocalDate())) { double?fixedRate = provider.timeSeries(cmsPeriod.Index).get(fixingDate); if (fixedRate.HasValue) { double payoff = 0d; switch (cmsPeriod.CmsPeriodType) { case CAPLET: payoff = fixedRate.Value >= strike ? -1d : 0d; break; case FLOORLET: payoff = fixedRate.Value < strike ? 1d : 0d; break; default: throw new System.ArgumentException("unsupported CMS type"); } return(payoff * cmsPeriod.Notional * cmsPeriod.YearFraction * dfPayment); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new System.ArgumentException(Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.Index, fixingDate)); } } double forward = swapPricer.parRate(swap, provider); double eta = index.Template.Convention.FixedLeg.DayCount.relativeYearFraction(cmsPeriod.PaymentDate, swap.StartDate); CmsIntegrantProvider intProv = new CmsIntegrantProvider(this, cmsPeriod, swap, swaptionVolatilities, forward, strike, expiryTime, tenor, cutOffStrike, eta); double factor = dfPayment * intProv.g(forward) / intProv.h(forward); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL_STRIKE, NUM_ITER); double[] kpkpp = intProv.kpkpp(strike); double firstPart; double thirdPart; System.Func <double, double> integrant = intProv.integrantDualDelta(); if (intProv.PutCall.Call) { firstPart = -kpkpp[0] * intProv.bs(strike); thirdPart = integrateCall(integrator, integrant, swaptionVolatilities, forward, strike, expiryTime, tenor); } else { firstPart = -kpkpp[0] * intProv.bs(strike); thirdPart = -integrator.integrate(integrant, -shift + ZERO_SHIFT, strike).Value; } double secondPart = intProv.k(strike) * intProv.SabrExtrapolation.priceDerivativeStrike(strike + shift, intProv.PutCall); return(cmsPeriod.Notional * cmsPeriod.YearFraction * factor * (firstPart + secondPart + thirdPart)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @ImmutableConstructor private NormalIborFutureOptionExpirySimpleMoneynessVolatilities(com.opengamma.strata.basics.index.IborIndex index, java.time.ZonedDateTime valuationDateTime, com.opengamma.strata.market.surface.Surface surface) private NormalIborFutureOptionExpirySimpleMoneynessVolatilities(IborIndex index, ZonedDateTime valuationDateTime, Surface surface) { ArgChecker.notNull(index, "index"); ArgChecker.notNull(valuationDateTime, "valuationDateTime"); ArgChecker.notNull(surface, "surface"); surface.Metadata.XValueType.checkEquals(ValueType.YEAR_FRACTION, "Incorrect x-value type for Normal volatilities"); surface.Metadata.YValueType.checkEquals(ValueType.SIMPLE_MONEYNESS, "Incorrect y-value type for Normal volatilities"); surface.Metadata.ZValueType.checkEquals(ValueType.NORMAL_VOLATILITY, "Incorrect z-value type for Normal volatilities"); DayCount dayCount = surface.Metadata.findInfo(SurfaceInfoType.DAY_COUNT).orElseThrow(() => new System.ArgumentException("Incorrect surface metadata, missing DayCount")); MoneynessType moneynessType = surface.Metadata.findInfo(SurfaceInfoType.MONEYNESS_TYPE).orElseThrow(() => new System.ArgumentException("Incorrect surface metadata, missing MoneynessType")); this.index = index; this.valuationDateTime = valuationDateTime; this.surface = surface; this.moneynessOnPrice = moneynessType == MoneynessType.PRICE; this.dayCount = dayCount; }
void INpgsqlSimpleTypeHandler <ZonedDateTime> .Write(ZonedDateTime value, NpgsqlWriteBuffer buf, NpgsqlParameter?parameter) => Write(value.ToInstant(), buf, parameter);
public void CreateResolver_Skipped() { ZonedDateTime zoned = new ZonedDateTime(TimeInTransition.PlusDays(1).WithOffset(GapZone.EarlyInterval.WallOffset), GapZone); AmbiguousTimeResolver ambiguityResolver = (earlier, later) => { Assert.Fail("Shouldn't be called"); return default(ZonedDateTime); }; SkippedTimeResolver skippedTimeResolver = (local, zone, before, after) => zoned; var resolver = Resolvers.CreateMappingResolver(ambiguityResolver, skippedTimeResolver); var resolved = resolver(GapZone.MapLocal(TimeInTransition)); Assert.AreEqual(zoned, resolved); }
int INpgsqlSimpleTypeHandler <ZonedDateTime> .ValidateAndGetLength(ZonedDateTime value, NpgsqlParameter?parameter) => 8;
public void WithZone() { Instant instant = Instant.FromUtc(2012, 2, 4, 12, 35); ZonedDateTime zoned = new ZonedDateTime(instant, SampleZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 16, 35, 0), zoned.LocalDateTime); // Will be UTC-8 for our instant. DateTimeZone newZone = new SingleTransitionDateTimeZone(Instant.FromUtc(2000, 1, 1, 0, 0), -7, -8); ZonedDateTime converted = zoned.WithZone(newZone); Assert.AreEqual(new LocalDateTime(2012, 2, 4, 4, 35, 0), converted.LocalDateTime); Assert.AreEqual(converted.ToInstant(), instant); }
private readonly DayCount dayCount; // cached, not a property //------------------------------------------------------------------------- /// <summary> /// Obtains an instance from the implied volatility surface and the date-time for which it is valid. /// <para> /// The surface is specified by an instance of <seealso cref="Surface"/>, such as <seealso cref="InterpolatedNodalSurface"/>. /// The surface must contain the correct metadata: /// <ul> /// <li>The x-value type must be <seealso cref="ValueType#YEAR_FRACTION"/> /// <li>The y-value type must be <seealso cref="ValueType#YEAR_FRACTION"/> /// <li>The z-value type must be <seealso cref="ValueType#BLACK_VOLATILITY"/> /// <li>The day count must be set in the additional information using <seealso cref="SurfaceInfoType#DAY_COUNT"/> /// </ul> /// Suitable surface metadata can be created using /// <seealso cref="Surfaces#blackVolatilityByExpiryTenor(String, DayCount)"/>. /// /// </para> /// </summary> /// <param name="convention"> the swap convention that the volatilities are to be used for </param> /// <param name="valuationDateTime"> the valuation date-time </param> /// <param name="surface"> the implied volatility surface </param> /// <returns> the volatilities </returns> public static BlackSwaptionExpiryTenorVolatilities of(FixedIborSwapConvention convention, ZonedDateTime valuationDateTime, Surface surface) { return(new BlackSwaptionExpiryTenorVolatilities(convention, valuationDateTime, surface)); }
public void Construct_FromLocal_ValidLaterOffset() { SingleTransitionDateTimeZone zone = new SingleTransitionDateTimeZone(Instant.FromUtc(2011, 6, 12, 22, 0), 4, 3); LocalDateTime local = new LocalDateTime(2011, 6, 13, 1, 30); ZonedDateTime zoned = new ZonedDateTime(local, zone, zone.LateInterval.WallOffset); // Map the local time to the later of the offsets in a way which is tested elsewhere. var resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnLater, Resolvers.ThrowWhenSkipped); Assert.AreEqual(zoned, local.InZone(zone, resolver)); }
public UserGainedRole(Role role, AuthUser user, UserId assignedBy, DomainEventId id, ZonedDateTime created) : base(id, TYPE, created) { RoleId = role.Id; Rolename = role.Rolename; UserId = user.Id; Username = user.Username; AssignedBy = assignedBy; }
public void BinarySerialization_Iso() { DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb; var zone = DateTimeZoneProviders.Tzdb["America/New_York"]; var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone); TestHelper.AssertBinaryRoundtrip(value); }
private static async Task <FinancialMonthReportModel> BuildReportForAPeriodAsync( IServiceProvider serviceProvider, ApplicationSettings config, ToshHttpApiClient toshHttpApiClient, LocalDateTime fromLocal, LocalDateTime toLocal, DateTimeZone dateTimeZone ) { ZonedDateTime fromUtc = fromLocal.InZoneLeniently(dateTimeZone).ToInstant().InUtc(); ZonedDateTime toUtc = toLocal.InZoneLeniently(dateTimeZone).ToInstant().InUtc(); // var me = await toshHttpApiClient.MeAsync(); const string cashAccountName = "Cash"; const string dreamsAccountName = "Dreams"; const string cryptoAccountName = "Crypto"; const string taxesCategoryName = "Taxes"; const string loansCategoryName = "Loans"; const string depositCategoryName = "Deposit"; const string tradingCategoryName = "Trading"; const string reimbursementsCategoryName = "Reimbursements"; const string sellingCategoryName = "Selling"; _accounts = _accounts ?? await toshHttpApiClient.AccountListAsync(); var cashAccount = _accounts.Single(x => x.Name == cashAccountName); var dreamsAccount = _accounts.Single(x => x.Name == dreamsAccountName); var cryptoAccount = _accounts.Single(x => x.Name == cryptoAccountName); _expenseCategories = _expenseCategories ?? await toshHttpApiClient.CategoryListAsync( type : "expense", page : 0, perPage : ToshHttpApiClient.MaxPerPage ); _incomeCategories = _incomeCategories ?? await toshHttpApiClient.CategoryListAsync( type : "income", page : 0, perPage : ToshHttpApiClient.MaxPerPage ); var expenseEntries = await toshHttpApiClient.EntryListAllAsync( fromDate : fromUtc.Date.ToString("yyyy-MM-dd", null), toDate : toUtc.Date.ToString("yyyy-MM-dd", null), type : "expense", accounts : new List <string>() { cashAccount.Id }, notCategories : new List <string>() { } ); var incomeEntries = await toshHttpApiClient.EntryListAllAsync( fromDate : fromUtc.Date.ToString("yyyy-MM-dd", null), toDate : toUtc.Date.ToString("yyyy-MM-dd", null), type : "income", accounts : new List <string>() { cashAccount.Id }, notCategories : new List <string>() { } ); // entry filters var transfersToAccountsBlackList = new List <string>() { cryptoAccount.Id, }; var expenseUnregularCategories = new List <string>() { _expenseCategories.Single(x => x.Name == taxesCategoryName).Id, _expenseCategories.Single(x => x.Name == loansCategoryName).Id, }; var incomeUnregularCategories = new List <string>() { _incomeCategories.Single(x => x.Name == depositCategoryName).Id, _incomeCategories.Single(x => x.Name == tradingCategoryName).Id, _incomeCategories.Single(x => x.Name == reimbursementsCategoryName).Id, _incomeCategories.Single(x => x.Name == sellingCategoryName).Id, }; var incomeTradingCategories = new List <string>() { _incomeCategories.Single(x => x.Name == tradingCategoryName).Id, }; // filter entries Func <EntryResponseDto, bool> expenseEntryFilteringPredicate = (x) => { if (x.IsTransfer && transfersToAccountsBlackList.Contains(x.Transaction.Account)) { return(false); } if (expenseUnregularCategories.Contains(x.Category)) { return(false); } return(true); }; Func <EntryResponseDto, bool> incomeEntryFilteringPredicate = (x) => { //if (x.IsTransfer && transfersToAccountsBlackList.Contains(x.Transaction.Account)) //{ // return false; //} if (incomeUnregularCategories.Contains(x.Category)) { return(false); } return(true); }; var expenseRegularEntries = expenseEntries.Where(x => expenseEntryFilteringPredicate(x)).ToList(); var expenseUnregularEntries = expenseEntries.Where(x => !expenseEntryFilteringPredicate(x)).ToList(); var incomeRegularEntries = incomeEntries.Where(x => incomeEntryFilteringPredicate(x)).ToList(); var incomeUnregularEntries = incomeEntries.Where(x => !incomeEntryFilteringPredicate(x)).ToList(); var expenseTradingEntries = expenseEntries.Where(x => { if (x.IsTransfer && x.Transaction.Account == cryptoAccount.Id) { return(true); } return(false); }).ToList(); var incomeTradingEntries = incomeEntries.Where(x => { if (x.IsTransfer && x.Transaction.Account == cashAccount.Id) { return(true); } if (incomeTradingCategories.Contains(x.Category)) { return(true); } return(false); }).ToList(); // build report decimal totalExpenes = expenseEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalRegularExpenes = expenseRegularEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalUnregularExpenes = expenseUnregularEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalIncome = incomeEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalRegularIncome = incomeRegularEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalUnregularIncome = incomeUnregularEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalTradingExpenes = expenseTradingEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); decimal totalTradingIncome = incomeTradingEntries.Aggregate(0m, (accum, curr) => accum + curr.Amount); return(new FinancialMonthReportModel() { From = fromLocal.ToDateTimeUnspecified(), To = toLocal.ToDateTimeUnspecified(), PeriodName = fromLocal.ToDateTimeUnspecified().ToString("yyyy MMMM"), // 2020 April TotalExpenes = totalExpenes, TotalRegularExpenes = totalRegularExpenes, TotalUnregularExpenes = totalUnregularExpenes, TotalIncome = totalIncome, TotalRegularIncome = totalRegularIncome, TotalUnregularIncome = totalUnregularIncome, TotalTradingExpenes = totalTradingExpenes, TotalTradingIncome = totalTradingIncome, }); }
public void BinarySerialization_Bcl() { // Skip this on Mono, which will have different BCL time zones. We can't easily // guess which will be available :( if (!TestHelper.IsRunningOnMono) { DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Bcl; var zone = DateTimeZoneProviders.Bcl["Eastern Standard Time"]; var value = new ZonedDateTime(new LocalDateTime(2013, 4, 12, 17, 53, 23).WithOffset(Offset.FromHours(-4)), zone); TestHelper.AssertBinaryRoundtrip(value); } }
public void get_timezone_id_from_utc_offset() { var instant = Instant.FromUtc(2012, 1, 2, 3, 4, 5); var offset = Offset.FromHours(-5); var tz = new ZonedDateTime(instant, DateTimeZone.ForOffset(offset)); var odt = instant.WithOffset(offset); _output.WriteLine(odt.ToString()); // InFixedZone means Fixed Time Zone - no DST observance _output.WriteLine(odt.InFixedZone().ToString()); _output.WriteLine(DateTimeZone.ForOffset(offset).ToString()); _output.WriteLine(tz.ToJson()); }
public void BinarySerialization_NonIso() { DateTimeZoneProviders.Serialization = DateTimeZoneProviders.Tzdb; var zone = DateTimeZoneProviders.Tzdb["America/New_York"]; var localDateTime = new LocalDateTime(2013, 6, 12, 17, 53, 23, CalendarSystem.Julian); var value = new ZonedDateTime(localDateTime.WithOffset(Offset.FromHours(-4)), zone); TestHelper.AssertBinaryRoundtrip(value); }
public void ChangeTimeZone(DateTimeZone dateTimeZone) { ZonedDateTime = new ZonedDateTime(ZonedDateTime.LocalDateTime, dateTimeZone, dateTimeZone.GetUtcOffset(Instant.FromDateTimeOffset(ZonedDateTime.ToDateTimeOffset()))); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @ImmutableConstructor private BlackSwaptionExpiryTenorVolatilities(com.opengamma.strata.product.swap.type.FixedIborSwapConvention convention, java.time.ZonedDateTime valuationDateTime, com.opengamma.strata.market.surface.Surface surface) private BlackSwaptionExpiryTenorVolatilities(FixedIborSwapConvention convention, ZonedDateTime valuationDateTime, Surface surface) { ArgChecker.notNull(convention, "convention"); ArgChecker.notNull(valuationDateTime, "valuationDateTime"); ArgChecker.notNull(surface, "surface"); surface.Metadata.XValueType.checkEquals(ValueType.YEAR_FRACTION, "Incorrect x-value type for Black volatilities"); surface.Metadata.YValueType.checkEquals(ValueType.YEAR_FRACTION, "Incorrect y-value type for Black volatilities"); surface.Metadata.ZValueType.checkEquals(ValueType.BLACK_VOLATILITY, "Incorrect z-value type for Black volatilities"); DayCount dayCount = surface.Metadata.findInfo(SurfaceInfoType.DAY_COUNT).orElseThrow(() => new System.ArgumentException("Incorrect surface metadata, missing DayCount")); this.valuationDateTime = valuationDateTime; this.surface = surface; this.convention = convention; this.dayCount = dayCount; }
//------------------------------------------------------------------------- /// <summary> /// Computes the present value curve sensitivity by replication in SABR framework with extrapolation on the right. /// </summary> /// <param name="cmsPeriod"> the CMS </param> /// <param name="provider"> the rates provider </param> /// <param name="swaptionVolatilities"> the swaption volatilities </param> /// <returns> the present value sensitivity </returns> public PointSensitivityBuilder presentValueSensitivityRates(CmsPeriod cmsPeriod, RatesProvider provider, SabrSwaptionVolatilities swaptionVolatilities) { Currency ccy = cmsPeriod.Currency; if (provider.ValuationDate.isAfter(cmsPeriod.PaymentDate)) { return(PointSensitivityBuilder.none()); } SwapIndex index = cmsPeriod.Index; ResolvedSwap swap = cmsPeriod.UnderlyingSwap; double dfPayment = provider.discountFactor(ccy, cmsPeriod.PaymentDate); ZonedDateTime valuationDate = swaptionVolatilities.ValuationDateTime; LocalDate fixingDate = cmsPeriod.FixingDate; double expiryTime = swaptionVolatilities.relativeTime(fixingDate.atTime(index.FixingTime).atZone(index.FixingZone)); double tenor = swaptionVolatilities.tenor(swap.StartDate, swap.EndDate); double shift = swaptionVolatilities.shift(expiryTime, tenor); double strikeCpn = cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON) ? -shift : cmsPeriod.Strike; if (!fixingDate.isAfter(valuationDate.toLocalDate())) { double?fixedRate = provider.timeSeries(cmsPeriod.Index).get(fixingDate); if (fixedRate.HasValue) { double payoff = payOff(cmsPeriod.CmsPeriodType, strikeCpn, fixedRate.Value); return(provider.discountFactors(ccy).zeroRatePointSensitivity(cmsPeriod.PaymentDate).multipliedBy(payoff * cmsPeriod.Notional * cmsPeriod.YearFraction)); } else if (fixingDate.isBefore(valuationDate.toLocalDate())) { throw new System.ArgumentException(Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", cmsPeriod.Index, fixingDate)); } } double forward = swapPricer.parRate(swap, provider); double eta = index.Template.Convention.FixedLeg.DayCount.relativeYearFraction(cmsPeriod.PaymentDate, swap.StartDate); CmsDeltaIntegrantProvider intProv = new CmsDeltaIntegrantProvider(this, cmsPeriod, swap, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor, cutOffStrike, eta); RungeKuttaIntegrator1D integrator = new RungeKuttaIntegrator1D(ABS_TOL, REL_TOL, NUM_ITER); double[] bs = intProv.bsbsp(strikeCpn); double[] n = intProv.Nnp; double strikePartPrice = intProv.k(strikeCpn) * n[0] * bs[0]; double integralPartPrice = 0d; double integralPart = 0d; System.Func <double, double> integrant = intProv.integrant(); System.Func <double, double> integrantDelta = intProv.integrantDelta(); try { if (intProv.PutCall.Call) { integralPartPrice = integrateCall(integrator, integrant, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); integralPart = dfPayment * integrateCall(integrator, integrantDelta, swaptionVolatilities, forward, strikeCpn, expiryTime, tenor); } else { integralPartPrice = -integrator.integrate(integrant, -shift + ZERO_SHIFT, strikeCpn).Value; integralPart = -dfPayment *integrator.integrate(integrantDelta, -shift, strikeCpn); } } catch (Exception e) { throw new MathException(e); } double deltaPD = strikePartPrice + integralPartPrice; if (cmsPeriod.CmsPeriodType.Equals(CmsPeriodType.COUPON)) { deltaPD -= shift; } deltaPD *= cmsPeriod.Notional * cmsPeriod.YearFraction; double strikePart = dfPayment * intProv.k(strikeCpn) * (n[1] * bs[0] + n[0] * bs[1]); double deltaFwd = (strikePart + integralPart) * cmsPeriod.Notional * cmsPeriod.YearFraction; PointSensitivityBuilder sensiFwd = swapPricer.parRateSensitivity(swap, provider).multipliedBy(deltaFwd); PointSensitivityBuilder sensiDf = provider.discountFactors(ccy).zeroRatePointSensitivity(cmsPeriod.PaymentDate).multipliedBy(deltaPD); return(sensiFwd.combinedWith(sensiDf)); }