Exemplo n.º 1
0
 public FutureSettingsFromJson(ICalendarProvider calendarProvider, string fileName, ILoggerFactory loggerFactory)
 {
     _logger           = loggerFactory.CreateLogger <FutureSettingsFromJson>();
     _calendarProvider = calendarProvider;
     _jsonSettings     = new JsonSerializerSettings()
     {
         DateFormatString = "yyyyMMdd",
         Converters       = new JsonConverter[]
         {
             new MarketShutRuleSetConverter(_calendarProvider),
             new FutureDatesGeneratorConverter(_calendarProvider),
         },
     };
     try
     {
         _allFutureSettings = JsonConvert.DeserializeObject <List <FutureSettings> >(System.IO.File.ReadAllText(fileName), _jsonSettings);
         foreach (var fs in _allFutureSettings)
         {
             foreach (var n in fs.Names)
             {
                 _allSettingsByName.Add(n, fs);
             }
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Error loading future settings from json");
     }
 }
Exemplo n.º 2
0
 public WorkflowApplier(NiisWebContext context, ITaskRegister <Domain.Entities.Contract.Contract> taskRegister, INotificationSender notificationSender, ICalendarProvider calendarProvider)
 {
     _context            = context;
     _taskRegister       = taskRegister;
     _notificationSender = notificationSender;
     _calendarProvider   = calendarProvider;
 }
Exemplo n.º 3
0
 public SpeedingCitation(ICalendarProvider calendar, ITicketer issuer, ILegalEntity citee, CitationSeverity severity)
 {
     _calendar    = calendar ?? throw new ArgumentNullException(nameof(calendar));
     Issuer       = issuer ?? throw new ArgumentNullException(nameof(issuer));
     Citee        = citee ?? throw new ArgumentNullException(nameof(citee));
     Severity     = severity;
     CitationDate = _calendar.CurrentDate;
 }
Exemplo n.º 4
0
 public FxPair(TO_FxPair transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
 {
     Foreign           = currencyProvider.GetCurrency(transportObject.Foreign);
     Domestic          = currencyProvider.GetCurrency(transportObject.Domestic);
     SpotLag           = new Frequency(transportObject.SpotLag);
     PrimaryCalendar   = calendarProvider.Collection[transportObject.PrimaryCalendar];
     SecondaryCalendar = calendarProvider.Collection[transportObject.SecondaryCalendar];
 }
Exemplo n.º 5
0
 public TaskRegister(NiisWebContext context, ICalendarProvider calendarProvider)
 {
     _context          = context;
     _calendarProvider = calendarProvider;
     _resultStageMap   = new Dictionary <string, string> {
         { "DK03.03", "DK02.9.1" },
         { "DK02.4.0", String.Empty },
         { "DK02.4.2", "DK02.4" }
     };
 }
Exemplo n.º 6
0
 public FundingModel(DateTime buildDate, Dictionary <string, IrCurve> curves, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
 {
     _currencyProvider = currencyProvider;
     _calendarProvider = calendarProvider;
     BuildDate         = buildDate;
     Curves            = new Dictionary <string, IrCurve>(curves);
     FxMatrix          = new FxMatrix(_currencyProvider);
     VolSurfaces       = new Dictionary <string, IVolSurface>();
     SetupMappings();
 }
Exemplo n.º 7
0
 public FloatRateIndex(TO_FloatRateIndex transportObject, ICalendarProvider calendarProvider, ICurrencyProvider currencyProvider)
 {
     DayCountBasis      = transportObject.DayCountBasis;
     DayCountBasisFixed = transportObject.DayCountBasisFixed;
     ResetTenor         = new Frequency(transportObject.ResetTenor);
     ResetTenorFixed    = new Frequency(transportObject.ResetTenorFixed);
     HolidayCalendars   = calendarProvider.GetCalendarSafe(transportObject.HolidayCalendars);
     RollConvention     = transportObject.RollConvention;
     Currency           = currencyProvider.GetCurrencySafe(transportObject.Currency);
     FixingOffset       = new Frequency(transportObject.FixingOffset);
 }
Exemplo n.º 8
0
 public GetPlaceInventoryQueryHandler(
     IEventTicketDetailRepository eventTicketDetail,
     IPlaceHolidayDatesRepository placeHolidayDatesRepository,
     IEventTicketAttributeRepository eventTicketAttribute,
     ITicketCategoryRepository ticketCategoryRepository,
     IPlaceTicketRedemptionDetailRepository placeTicketRedemptionDetailRepository,
     IEventDeliveryTypeDetailRepository eventDeliveryTypeDetailRepository,
     IEventDetailRepository eventDetailRepository,
     IEventRepository eventRepository,
     IRefundPolicyRepository refundPolicyRepository,
     IPlaceCustomerDocumentTypeMappingRepository placeCustomerDocumentTypeMappingRepository,
     IPlaceDocumentTypeMappingRepository placeDocumentTypeMappingRepository,
     ICustomerDocumentTypeRepository customerDocumentTypeRepository,
     ICustomerInformationRepository customerInformationRepository,
     IEventCustomerInformationMappingRepository eventCustomerInformationMappingRepository,
     IEventTicketDetailTicketCategoryTypeMappingRepository eventTicketDetailTicketCategoryTypeMappingRepository,
     IDaysRepository daysRepository,
     IPlaceWeekOpenDaysRepository placeWeekOpenDaysRepository,
     IDayTimeMappingsRepository dayTimeMappingsRepository,
     IPlaceSeasonDetailsRepository placeSeasonDetailsRepository,
     ISeasonDayTimeMappingsRepository seasonDayTimeMappingsRepository,
     ISeasonDaysMappingsRepository seasonDaysMappingsRepository,
     IPlaceSpecialDayTimeMappingsRepository placeSpecialDayTimeMappingsRepository,
     ICalendarProvider calendarProvider,
     IEventAttributeRepository eventAttributeRepository,
     IPlaceWeekOffRepository placeWeekOffRepository, ITicketFeeDetailRepository ticketFeeDetailRepository)
 {
     _eventTicketDetail = eventTicketDetail;
     _eventDeliveryTypeDetailRepository  = eventDeliveryTypeDetailRepository;
     _eventDetailRepository              = eventDetailRepository;
     _ticketCategoryRepository           = ticketCategoryRepository;
     _placeDocumentTypeMappingRepository = placeDocumentTypeMappingRepository;
     _eventRepository        = eventRepository;
     _eventTicketAttribute   = eventTicketAttribute;
     _refundPolicyRepository = refundPolicyRepository;
     _placeTicketRedemptionDetailRepository      = placeTicketRedemptionDetailRepository;
     _placeCustomerDocumentTypeMappingRepository = placeCustomerDocumentTypeMappingRepository;
     _placeHolidydates              = placeHolidayDatesRepository;
     _placeWeekOffRepository        = placeWeekOffRepository;
     _customerInformationRepository = customerInformationRepository;
     _eventTicketDetailTicketCategoryTypeMappingRepository = eventTicketDetailTicketCategoryTypeMappingRepository;
     _customerDocumentTypeRepository            = customerDocumentTypeRepository;
     _eventCustomerInformationMappingRepository = eventCustomerInformationMappingRepository;
     _daysRepository = daysRepository;
     _placeWeekOpenDaysRepository           = placeWeekOpenDaysRepository;
     _dayTimeMappingsRepository             = dayTimeMappingsRepository;
     _placeSeasonDetailsRepository          = placeSeasonDetailsRepository;
     _seasonDayTimeMappingsRepository       = seasonDayTimeMappingsRepository;
     _seasonDaysMappingsRepository          = seasonDaysMappingsRepository;
     _placeSpecialDayTimeMappingsRepository = placeSpecialDayTimeMappingsRepository;
     _calendarProvider          = calendarProvider;
     _eventAttributeRepository  = eventAttributeRepository;
     _ticketFeeDetailRepository = ticketFeeDetailRepository;
 }
Exemplo n.º 9
0
 public FeelEventLearnPageQueryHandler(IEventTicketAttributeRepository eventTicketAttributeRepository,
                                       IEventLearnPageProvider eventLearnPageProvider,
                                       IEventTicketDetailRepository eventTicketDetailRepository,
                                       IUserRepository userRepository,
                                       IRatingRepository ratingRepository,
                                       ITicketCategoryRepository ticketCategoryRepository,
                                       IEventAmenityRepository eventAmenityRepository,
                                       IClientPointOfContactRepository clientPointOfContactRepository,
                                       ICurrencyTypeRepository currencyTypeRepository,
                                       IEventLearnMoreAttributeRepository eventLearnMoreAttributeRepository,
                                       IEventCategoryMappingRepository eventCategoryMappingRepository,
                                       ICalendarProvider calendarProvider,
                                       IEventCategoryRepository eventCategoryRepository,
                                       ILocalTimeZoneConvertProvider localTimeZoneConvertProvider,
                                       ITicketAlertEventMappingRepository ticketAlertEventMappingRepository,
                                       IAmenityRepository amenityRepository, ICitySightSeeingRouteRepository citySightSeeingRouteRepository, ICitySightSeeingRouteDetailRepository citySightSeeingRouteDetailRepository, ITiqetProductCheckoutDetailRepository tiqetProductCheckoutDetailRepository, ITiqetEventDetailMappingRepository tiqetEventDetailMappingRepository, IEventHostMappingRepository eventHostMappingRepository, IPlaceWeekOpenDaysRepository placeWeekOpenDaysRepository, IDayTimeMappingsRepository dayTimeMappingsRepository, IEventAttributeRepository eventAttributeRepository)
 {
     _eventLearnPageProvider         = eventLearnPageProvider;
     _eventTicketAttributeRepository = eventTicketAttributeRepository;
     _eventTicketDetailRepository    = eventTicketDetailRepository;
     _userRepository                       = userRepository;
     _ratingRepository                     = ratingRepository;
     _ticketCategoryRepository             = ticketCategoryRepository;
     _eventAmenityRepository               = eventAmenityRepository;
     _clientPointOfContactRepository       = clientPointOfContactRepository;
     _currencyTypeRepository               = currencyTypeRepository;
     _eventLearnMoreAttributeRepository    = eventLearnMoreAttributeRepository;
     _amenityRepository                    = amenityRepository;
     _calendarProvider                     = calendarProvider;
     _citySightSeeingRouteRepository       = citySightSeeingRouteRepository;
     _citySightSeeingRouteDetailRepository = citySightSeeingRouteDetailRepository;
     _eventCategoryMappingRepository       = eventCategoryMappingRepository;
     _tiqetProductCheckoutDetailRepository = tiqetProductCheckoutDetailRepository;
     _eventCategoryRepository              = eventCategoryRepository;
     _tiqetEventDetailMappingRepository    = tiqetEventDetailMappingRepository;
     _eventHostMappingRepository           = eventHostMappingRepository;
     _placeWeekOpenDaysRepository          = placeWeekOpenDaysRepository;
     _dayTimeMappingsRepository            = dayTimeMappingsRepository;
     _eventAttributeRepository             = eventAttributeRepository;
     _ticketAlertEventMappingRepository    = ticketAlertEventMappingRepository;
     _localTimeZoneConvertProvider         = localTimeZoneConvertProvider;
 }
Exemplo n.º 10
0
 public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILogger <CurrenciesFromJson> logger)
 {
     _logger           = logger;
     _calendarProvider = calendarProvider;
     _jsonSettings     = new JsonSerializerSettings()
     {
         Converters = new JsonConverter[]
         {
             new CurrencyConverter(_calendarProvider),
         },
     };
     try
     {
         _allCurrencies    = JsonConvert.DeserializeObject <List <Currency> >(System.IO.File.ReadAllText(fileName), _jsonSettings);
         _currenciesByName = _allCurrencies.ToDictionary(c => c.Ccy, c => c, StringComparer.OrdinalIgnoreCase);
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Failed to load currencies from Json");
     }
 }
Exemplo n.º 11
0
        public static DateTime OptionExpiryFromNymexRecord(NYMEXOptionRecord record, ICalendarProvider calendarProvider)
        {
            switch (record.Symbol)
            {
            case "LO":     //WTI American
                return(new DateTime(record.ContractYear, record.ContractMonth, 26)
                       .AddMonths(-1)
                       .SubtractPeriod(RollType.P, calendarProvider.Collection["NYC"], 7.Bd()));

            case "ON":     //HH Natgas
            case "OH":     //Heat
            case "OB":     //Heat
                return(new DateTime(record.ContractYear, record.ContractMonth, 1)
                       .SubtractPeriod(RollType.P, calendarProvider.Collection["NYC"], 4.Bd()));

            case "BZO":     //NYMEX Brent
                return(new DateTime(record.ContractYear, record.ContractMonth, 1)
                       .AddMonths(-1)
                       .SubtractPeriod(RollType.P, calendarProvider.Collection["LON"], 4.Bd()));

            default:
                throw new Exception($"No option expiry mapping found for {record.Symbol}");
            }
        }
Exemplo n.º 12
0
        public static RiskyFlySurface GetSurfaceForCode(string nymexSymbol, string nymexOptionFilename, string qwackCode, BasicPriceCurve priceCurve, ICalendarProvider calendarProvider, ICurrencyProvider currency, IFutureSettingsProvider futureSettingsProvider)
        {
            var parsed = NYMEXOptionParser.Instance.Parse(nymexOptionFilename).Where(r => r.Symbol == nymexSymbol);

            var(optionExerciseType, optionMarginingType) = OptionTypeFromCode(nymexSymbol);
            var origin = DateTime.ParseExact(parsed.First().TradeDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);

            var q = parsed.Where(x => x.Settle > 0).Select(x => new ListedOptionSettlementRecord
            {
                CallPut               = x.PutCall == "C"?OptionType.C:OptionType.P,
                ExerciseType          = optionExerciseType,
                MarginType            = optionMarginingType,
                PV                    = x.Settle,
                Strike                = x.Strike,
                UnderlyingFuturesCode = Year2to1(x.Contract.Split(' ')[0].Replace(nymexSymbol, qwackCode)),
                ExpiryDate            = OptionExpiryFromNymexRecord(x, calendarProvider),
                ValDate               = origin
            }).Where(z => z.ExpiryDate > origin).ToList();

            var priceDict = priceCurve.PillarLabels.ToDictionary(x => x, x => priceCurve.GetPriceForDate(priceCurve.PillarDatesForLabel(x)));

            ListedSurfaceHelper.ImplyVols(q, priceDict, new ConstantRateIrCurve(0.0, origin, "dummy", currency.GetCurrency("USD")));
            var smiles = ListedSurfaceHelper.ToDeltaSmiles(q, priceDict);

            var allOptionExpiries = new List <DateTime>();
            var lastDate          = q.Max(x => x.ExpiryDate);

            var dummyFutureCode = $"{qwackCode}Z{DateExtensions.SingleDigitYear(DateTime.Today.Year + 2)}";
            var c = new FutureCode(dummyFutureCode, DateTime.Today.Year - 2, futureSettingsProvider);

            var contract     = c.GetFrontMonth(origin, false);
            var lastContract = c.GetFrontMonth(lastDate, false);

            while (contract != lastContract)
            {
                var cc     = new FutureCode(contract, origin.Year, futureSettingsProvider);
                var exp    = ListedUtils.FuturesCodeToDateTime(contract);
                var record = new NYMEXOptionRecord
                {
                    ContractMonth = exp.Month,
                    ContractYear  = exp.Year,
                    Symbol        = nymexSymbol
                };
                var optExpiry = OptionExpiryFromNymexRecord(record, calendarProvider);
                if (optExpiry > origin)
                {
                    allOptionExpiries.Add(optExpiry);
                }

                contract = cc.GetNextCode(false);
            }

            var surface = ListedSurfaceHelper.ToRiskyFlySurfaceStepFlat(smiles, origin, priceCurve, allOptionExpiries, currency);

            return(surface);
        }
Exemplo n.º 13
0
        public static (IrCurve curve, double spotPrice) GetMetalCurveForCode(string cmxSettleFwdFilename, string cmxSymbol, FxPair metalPair, string curveName, DateTime valDate, IrCurve baseCurve, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
        {
            var blob = CMEFileParser.Instance.GetBlob(cmxSettleFwdFilename);
            var fwds = blob.Batch.Where(b => b.Instrmt.Sym == cmxSymbol).ToDictionary(x => x.Instrmt.MatDt, x => Convert.ToDouble(x.Full.Where(x => x.Typ == "6").First().Px));

            var curveCcy = metalPair.Domestic;
            var bc       = baseCurve.Clone();

            bc.SolveStage = -1;
            var spotDate = metalPair.SpotDate(valDate);
            var spotRate = Convert.ToDouble(fwds[spotDate]);

            fwds = Downsample(fwds, spotDate, metalPair.PrimaryCalendar);

            var fwdObjects = fwds.Select(x => new FxForward
            {
                DomesticCCY          = metalPair.Foreign,
                DeliveryDate         = x.Key,
                DomesticQuantity     = 1e6,
                ForeignCCY           = metalPair.Domestic,
                PillarDate           = x.Key,
                SolveCurve           = curveName,
                Strike               = Convert.ToDouble(x.Value),
                ForeignDiscountCurve = baseCurve.Name,
            });

            var fic = new FundingInstrumentCollection(currencyProvider);

            fic.AddRange(fwdObjects);
            var pillars  = fwds.Keys.OrderBy(x => x).ToArray();
            var curve    = new IrCurve(pillars, pillars.Select(p => 0.01).ToArray(), valDate, curveName, Interpolator1DType.Linear, curveCcy);
            var fm       = new FundingModel(valDate, new[] { curve, bc }, currencyProvider, calendarProvider);
            var matrix   = new FxMatrix(currencyProvider);
            var discoMap = new Dictionary <Currency, string> {
                { curveCcy, curveName }, { baseCurve.Currency, baseCurve.Name }
            };

            matrix.Init(metalPair.Foreign, valDate, new Dictionary <Currency, double> {
                { metalPair.Domestic, spotRate }
            }, new List <FxPair> {
                metalPair
            }, discoMap);
            fm.SetupFx(matrix);
            var solver = new NewtonRaphsonMultiCurveSolverStaged()
            {
                InLineCurveGuessing = true
            };

            solver.Solve(fm, fic);

            return(curve, spotRate);
        }
Exemplo n.º 14
0
        public static IrCurve GetCurveForCode(string cmeId, string cmeFilename, string qwackCode, string curveName, Dictionary <string, FloatRateIndex> indices, Dictionary <string, string> curves, IFutureSettingsProvider futureSettingsProvider, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
        {
            var parsed      = CMEFileParser.Parse(cmeFilename).Where(r => r.ID == cmeId && r.SecTyp == "FUT");
            var q           = parsed.ToDictionary(x => DateTime.ParseExact(x.MatDt, "yyyy-MM-dd", CultureInfo.InvariantCulture), x => x.SettlePrice);
            var origin      = DateTime.ParseExact(parsed.First().BizDt, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            var instruments = parsed.Select(p => ToQwackIns(p, qwackCode, futureSettingsProvider, currencyProvider, indices, curves)).ToList();
            var pillars     = instruments.Select(x => x.PillarDate).OrderBy(x => x).ToArray();
            var fic         = new FundingInstrumentCollection(currencyProvider);

            fic.AddRange(instruments);
            var curve = new IrCurve(pillars, pillars.Select(p => 0.01).ToArray(), origin, curveName, Interpolator1DType.Linear, currencyProvider.GetCurrency("USD"));
            var fm    = new FundingModel(origin, new[] { curve }, currencyProvider, calendarProvider);

            var solver = new NewtonRaphsonMultiCurveSolverStaged();

            solver.Solve(fm, fic);
            return(curve);
        }
Exemplo n.º 15
0
 public static FxPair FxPairFromString(this string pair, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) => new FxPair
 {
     Domestic          = currencyProvider.GetCurrency(pair.Substring(0, 3)),
     Foreign           = currencyProvider.GetCurrency(pair.Substring(pair.Length - 3, 3)),
     PrimaryCalendar   = calendarProvider.Collection[pair.Substring(0, 3)],
     SecondaryCalendar = calendarProvider.Collection[pair.Substring(pair.Length - 3, 3)],
     SpotLag           = 2.Bd()
 };
Exemplo n.º 16
0
        public AssetFxMCModel(DateTime originDate, Portfolio portfolio, IAssetFxModel model, McSettings settings, ICurrencyProvider currencyProvider, IFutureSettingsProvider futureSettingsProvider, ICalendarProvider calendarProvider)
        {
            if (settings.CompactMemoryMode && settings.AveragePathCorrection)
            {
                throw new Exception("Can't use both CompactMemoryMode and PathCorrection");
            }

            _currencyProvider       = currencyProvider;
            _futureSettingsProvider = futureSettingsProvider;
            _calendarProvider       = calendarProvider;
            Engine = new PathEngine(settings.NumberOfPaths)
            {
                Parallelize       = settings.Parallelize,
                CompactMemoryMode = settings.CompactMemoryMode
            };
            OriginDate = originDate;
            Portfolio  = portfolio;
            Model      = model;
            Settings   = settings;
            switch (settings.Generator)
            {
            case RandomGeneratorType.MersenneTwister:
                Engine.AddPathProcess(new Random.MersenneTwister.MersenneTwister64()
                {
                    UseNormalInverse = true,
                    UseAnthithetic   = false
                });
                break;

            case RandomGeneratorType.Sobol:
                var directionNumers = new Random.Sobol.SobolDirectionNumbers(GetSobolFilename());
                Engine.AddPathProcess(new Random.Sobol.SobolPathGenerator(directionNumers, 1000)
                {
                    UseNormalInverse = true
                });
                break;

            case RandomGeneratorType.Constant:
                Engine.AddPathProcess(new Random.Constant.Constant()
                {
                    UseNormalInverse = true,
                });
                break;

            case RandomGeneratorType.FlipFlop:
                Engine.AddPathProcess(new Random.Constant.FlipFlop(settings.CreditSettings.ConfidenceInterval, true));
                break;
            }
            Engine.IncrementDepth();

            if (model.CorrelationMatrix != null)
            {
                if (settings.LocalCorrelation)
                {
                    Engine.AddPathProcess(new CholeskyWithTime(model.CorrelationMatrix, model));
                }
                else
                {
                    Engine.AddPathProcess(new Cholesky(model.CorrelationMatrix));
                }
                Engine.IncrementDepth();
            }

            var lastDate         = portfolio.LastSensitivityDate;
            var assetIds         = portfolio.AssetIds();
            var assetInstruments = portfolio.Instruments
                                   .Where(x => x is IAssetInstrument)
                                   .Select(x => x as IAssetInstrument);
            var fixingsNeeded = new Dictionary <string, List <DateTime> >();

            foreach (var ins in assetInstruments)
            {
                var fixingsForIns = ins.PastFixingDates(originDate);
                if (fixingsForIns.Any())
                {
                    foreach (var kv in fixingsForIns)
                    {
                        if (!fixingsNeeded.ContainsKey(kv.Key))
                        {
                            fixingsNeeded.Add(kv.Key, new List <DateTime>());
                        }
                        fixingsNeeded[kv.Key] = fixingsNeeded[kv.Key].Concat(kv.Value).Distinct().ToList();
                    }
                }
            }

            //asset processes
            var fxAssetsToAdd = new List <string>();
            var corrections   = new Dictionary <string, SimpleAveragePathCorrector>();

            foreach (var assetId in assetIds)
            {
                if (assetId.Length == 7 && assetId[3] == '/')
                {
                    fxAssetsToAdd.Add(assetId);
                    continue;
                }

                if (!(model.GetVolSurface(assetId) is IATMVolSurface surface))
                {
                    throw new Exception($"Vol surface for asset {assetId} could not be cast to IATMVolSurface");
                }
                var fixingDict = fixingsNeeded.ContainsKey(assetId) ? model.GetFixingDictionary(assetId) : null;
                var fixings    = fixingDict != null ?
                                 fixingsNeeded[assetId].ToDictionary(x => x, x => fixingDict.GetFixing(x))
                    : new Dictionary <DateTime, double>();
                var futuresSim = settings.ExpensiveFuturesSimulation &&
                                 (model.GetPriceCurve(assetId).CurveType == PriceCurveType.ICE || model.GetPriceCurve(assetId).CurveType == PriceCurveType.NYMEX);
                if (futuresSim)
                {
                    var fwdCurve = new Func <DateTime, double>(t =>
                    {
                        return(model.GetPriceCurve(assetId).GetPriceForDate(t));
                    });
                    var asset = new BlackFuturesCurve
                                (
                        startDate: originDate,
                        expiryDate: lastDate,
                        volSurface: surface,
                        forwardCurve: fwdCurve,
                        nTimeSteps: settings.NumberOfTimesteps,
                        name: Settings.FuturesMappingTable[assetId],
                        pastFixings: fixings,
                        futureSettingsProvider: _futureSettingsProvider
                                );
                    Engine.AddPathProcess(asset);
                }
                else
                {
                    var fwdCurve = new Func <double, double>(t =>
                    {
                        var c = model.GetPriceCurve(assetId);
                        var d = originDate.AddYearFraction(t, DayCountBasis.ACT365F);
                        if (c is PriceCurve pc)
                        {
                            d = d.AddPeriod(RollType.F, pc.SpotCalendar, pc.SpotLag);
                        }
                        else if (c is ContangoPriceCurve cc)
                        {
                            d = d.AddPeriod(RollType.F, cc.SpotCalendar, cc.SpotLag);
                        }
                        return(c.GetPriceForDate(d));
                    });

                    IATMVolSurface adjSurface  = null;
                    var            correlation = 0.0;

                    if (settings.ReportingCurrency != model.GetPriceCurve(assetId).Currency)
                    {
                        var fxAdjPair    = settings.ReportingCurrency + "/" + model.GetPriceCurve(assetId).Currency;
                        var fxAdjPairInv = model.GetPriceCurve(assetId).Currency + "/" + settings.ReportingCurrency;
                        if (!(model.FundingModel.GetVolSurface(fxAdjPair) is IATMVolSurface adjSurface2))
                        {
                            throw new Exception($"Vol surface for fx pair {fxAdjPair} could not be cast to IATMVolSurface");
                        }
                        adjSurface = adjSurface2;
                        if (model.CorrelationMatrix != null)
                        {
                            if (model.CorrelationMatrix.TryGetCorrelation(fxAdjPair, assetId, out var correl))
                            {
                                correlation = correl;
                            }
                            else if (model.CorrelationMatrix.TryGetCorrelation(fxAdjPairInv, assetId, out var correl2))
                            {
                                correlation = -correl2;
                            }
                        }
                    }

                    if (settings.McModelType == McModelType.LocalVol)
                    {
                        var asset = new LVSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: assetId,
                            pastFixings: fixings,
                            fxAdjustSurface: adjSurface,
                            fxAssetCorrelation: correlation
                                    );
                        Engine.AddPathProcess(asset);
                    }
                    else if (settings.McModelType == McModelType.TurboSkew)
                    {
                        var asset = new TurboSkewSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: assetId,
                            pastFixings: fixings,
                            fxAdjustSurface: adjSurface,
                            fxAssetCorrelation: correlation
                                    );
                        Engine.AddPathProcess(asset);
                    }
                    else
                    {
                        var asset = new BlackSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: assetId,
                            pastFixings: fixings,
                            fxAdjustSurface: adjSurface,
                            fxAssetCorrelation: correlation
                                    );
                        Engine.AddPathProcess(asset);
                    }
                    if (settings.AveragePathCorrection)
                    {
                        corrections.Add(assetId, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(assetId)
                        {
                            CompactMode = settings.CompactMemoryMode
                        }, surface, fwdCurve, assetId, fixings, adjSurface, correlation));
                    }
                }
            }

            //fx pairs
            var pairsAdded = new List <string>();
            var fxPairs    = portfolio.FxPairs(model).Concat(fxAssetsToAdd);
            var payoutCcys = portfolio.Instruments.Select(i => i.Currency);

            if (payoutCcys.Any(p => p != settings.ReportingCurrency))
            {
                var ccysToAdd  = payoutCcys.Where(p => p != settings.ReportingCurrency).Distinct();
                var pairsToAdd = ccysToAdd.Select(c => $"{c.Ccy}/{settings.ReportingCurrency}");
                fxPairs = fxPairs.Concat(pairsToAdd).Distinct();
            }
            foreach (var fxPair in fxPairs)
            {
                var fxPairName = fxPair;
                var pair       = fxPairName.FxPairFromString(_currencyProvider, _calendarProvider);

                if (pairsAdded.Contains(pair.ToString()))
                {
                    continue;
                }

                if (!(model.FundingModel.VolSurfaces[fxPairName] is IATMVolSurface surface))
                {
                    throw new Exception($"Vol surface for fx pair {fxPairName} could not be cast to IATMVolSurface");
                }

                var fwdCurve = new Func <double, double>(t =>
                {
                    var date     = originDate.AddYearFraction(t, DayCountBasis.ACT365F);
                    var spotDate = pair.SpotDate(date);
                    return(model.FundingModel.GetFxRate(spotDate, fxPairName));
                });

                pairsAdded.Add(pair.ToString());

                if (settings.McModelType == McModelType.LocalVol)
                {
                    var asset = new LVSingleAsset
                                (
                        startDate: originDate,
                        expiryDate: lastDate,
                        volSurface: surface,
                        forwardCurve: fwdCurve,
                        nTimeSteps: settings.NumberOfTimesteps,
                        name: fxPairName
                                );
                    Engine.AddPathProcess(asset);

                    if (settings.AveragePathCorrection)
                    {
                        corrections.Add(fxPairName, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(fxPairName)
                        {
                            CompactMode = settings.CompactMemoryMode
                        }, surface, fwdCurve, fxPairName));
                    }
                }
                else if (settings.McModelType == McModelType.TurboSkew)
                {
                    if (fxPairName.Substring(fxPairName.Length - 3, 3) != settings.ReportingCurrency)
                    {//needs to be drift-adjusted
                        var fxAdjPair = settings.ReportingCurrency + "/" + fxPairName.Substring(fxPairName.Length - 3, 3);
                        if (!(model.FundingModel.VolSurfaces[fxAdjPair] is IATMVolSurface adjSurface))
                        {
                            throw new Exception($"Vol surface for fx pair {fxAdjPair} could not be cast to IATMVolSurface");
                        }
                        var correlation = fxPair == fxAdjPair ? -1.0 : 0.0;
                        if (correlation != -1.0 && model.CorrelationMatrix != null)
                        {
                            if (model.CorrelationMatrix.TryGetCorrelation(fxAdjPair, fxPair, out var correl))
                            {
                                correlation = correl;
                            }
                        }

                        var asset = new TurboSkewSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: fxPairName,
                            fxAdjustSurface: adjSurface,
                            fxAssetCorrelation: correlation
                                    );
                        Engine.AddPathProcess(asset);

                        if (settings.AveragePathCorrection)
                        {
                            corrections.Add(fxPairName, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(fxPairName)
                            {
                                CompactMode = settings.CompactMemoryMode
                            }, surface, fwdCurve, fxPairName, null, adjSurface, correlation));
                        }
                    }
                    else
                    {
                        var asset = new TurboSkewSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: fxPairName
                                    );
                        Engine.AddPathProcess(asset);

                        if (settings.AveragePathCorrection)
                        {
                            corrections.Add(fxPairName, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(fxPairName)
                            {
                                CompactMode = settings.CompactMemoryMode
                            }, surface, fwdCurve, fxPairName));
                        }
                    }
                }
                else
                {
                    if (fxPairName.Substring(fxPairName.Length - 3, 3) != settings.ReportingCurrency)
                    {//needs to be drift-adjusted
                        var fxAdjPair = settings.ReportingCurrency + "/" + fxPairName.Substring(fxPairName.Length - 3, 3);
                        if (!(model.FundingModel.VolSurfaces[fxAdjPair] is IATMVolSurface adjSurface))
                        {
                            throw new Exception($"Vol surface for fx pair {fxAdjPair} could not be cast to IATMVolSurface");
                        }
                        var correlation = fxPair == fxAdjPair ? -1.0 : 0.0;
                        if (correlation != -1.0 && model.CorrelationMatrix != null)
                        {
                            if (model.CorrelationMatrix.TryGetCorrelation(fxAdjPair, fxPair, out var correl))
                            {
                                correlation = correl;
                            }
                        }

                        var asset = new BlackSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: fxPairName,
                            fxAdjustSurface: adjSurface,
                            fxAssetCorrelation: correlation
                                    );
                        Engine.AddPathProcess(asset);

                        if (settings.AveragePathCorrection)
                        {
                            corrections.Add(fxPairName, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(fxPairName)
                            {
                                CompactMode = settings.CompactMemoryMode
                            }, surface, fwdCurve, fxPairName, null, adjSurface, correlation));
                        }
                    }
                    else
                    {
                        var asset = new BlackSingleAsset
                                    (
                            startDate: originDate,
                            expiryDate: lastDate,
                            volSurface: surface,
                            forwardCurve: fwdCurve,
                            nTimeSteps: settings.NumberOfTimesteps,
                            name: fxPairName
                                    );
                        Engine.AddPathProcess(asset);

                        if (settings.AveragePathCorrection)
                        {
                            corrections.Add(fxPairName, new SimpleAveragePathCorrector(new SimpleAveragePathCalculator(fxPairName)
                            {
                                CompactMode = settings.CompactMemoryMode
                            }, surface, fwdCurve, fxPairName));
                        }
                    }
                }
            }
            //apply path correctin
            if (settings.AveragePathCorrection && corrections.Any())
            {
                Engine.IncrementDepth();
                foreach (var pc in corrections)
                {
                    Engine.AddPathProcess(pc.Value.PathCalc);
                }
                Engine.IncrementDepth();
                foreach (var pc in corrections)
                {
                    Engine.AddPathProcess(pc.Value);
                }
            }

            //payoffs
            Engine.IncrementDepth();
            _payoffs = assetInstruments.ToDictionary(x => x.TradeId, y => new AssetPathPayoff(y, _currencyProvider, _calendarProvider, settings.ReportingCurrency));
            if (!settings.AvoidRegressionForBackPricing && _payoffs.Any(x => x.Value.Regressors != null))
            {
                var regressorsToAdd = _payoffs.Where(x => x.Value.Regressors != null)
                                      .SelectMany(x => x.Value.Regressors)
                                      .Distinct();

                foreach (var regressor in regressorsToAdd)
                {
                    Engine.AddPathProcess(regressor);
                    foreach (var payoff in _payoffs.Where(x => x.Value.Regressors != null))
                    {
                        if (payoff.Value.Regressors.Any(x => x == regressor))
                        {
                            payoff.Value.SetRegressor(regressor);
                        }
                    }
                }

                Engine.IncrementDepth();
            }
            foreach (var product in _payoffs)
            {
                if (settings.AvoidRegressionForBackPricing && (product.Value.AssetInstrument is BackPricingOption || product.Value.AssetInstrument is MultiPeriodBackpricingOption))
                {
                    product.Value.VanillaModel = VanillaModel;
                }

                Engine.AddPathProcess(product.Value);
            }

            var metricsNeedRegression = new[] { BaseMetric.PFE, BaseMetric.KVA, BaseMetric.CVA, BaseMetric.FVA, BaseMetric.EPE };

            //Need to calculate PFE
            if (settings.CreditSettings != null && settings.CreditSettings.ExposureDates != null && settings.ReportingCurrency != null && metricsNeedRegression.Contains(settings.CreditSettings.Metric))//setup for PFE, etc
            {
                Engine.IncrementDepth();

                switch (settings.CreditSettings.PfeRegressorType)
                {
                case PFERegressorType.MultiLinear:
                    _regressor = new LinearPortfolioValueRegressor(settings.CreditSettings.ExposureDates,
                                                                   _payoffs.Values.ToArray(), settings);
                    break;

                case PFERegressorType.MonoLinear:
                    _regressor = new MonoIndexRegressor(settings.CreditSettings.ExposureDates,
                                                        _payoffs.Values.ToArray(), settings, true);
                    break;
                }
                Engine.AddPathProcess(_regressor);
            }

            //Need to calculate expected capital
            if (settings.CreditSettings != null && settings.CreditSettings.ExposureDates != null && settings.ReportingCurrency != null && settings.CreditSettings.Metric == BaseMetric.ExpectedCapital)
            {
                Engine.IncrementDepth();
                _capitalCalc = new ExpectedCapitalCalculator(Portfolio, settings.CreditSettings.CounterpartyRiskWeighting, settings.CreditSettings.AssetIdToHedgeGroupMap, settings.ReportingCurrency, VanillaModel, settings.CreditSettings.ExposureDates);
                Engine.AddPathProcess(_capitalCalc);
            }

            Engine.SetupFeatures();
        }
Exemplo n.º 17
0
 public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILoggerFactory loggerFactory)
     : this(calendarProvider, fileName, loggerFactory.CreateLogger <CurrenciesFromJson>())
 {
 }
Exemplo n.º 18
0
 private static AsianSwap GetAsianSwap(this TO_AsianSwap transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) => new AsianSwap
 {
     TradeId            = transportObject.TradeId,
     Notional           = transportObject.Notional,
     Direction          = transportObject.Direction,
     AverageStartDate   = transportObject.AverageStartDate,
     AverageEndDate     = transportObject.AverageEndDate,
     FixingDates        = transportObject.FixingDates,
     FixingCalendar     = calendarProvider.GetCalendarSafe(transportObject.FixingCalendar),
     PaymentCalendar    = calendarProvider.GetCalendarSafe(transportObject.PaymentCalendar),
     SpotLag            = new Frequency(transportObject.SpotLag),
     SpotLagRollType    = transportObject.SpotLagRollType,
     PaymentLag         = new Frequency(transportObject.PaymentLag),
     PaymentLagRollType = transportObject.PaymentLagRollType,
     PaymentDate        = transportObject.PaymentDate,
     PaymentCurrency    = currencyProvider.GetCurrencySafe(transportObject.PaymentCurrency),
     AssetFixingId      = transportObject.AssetFixingId,
     AssetId            = transportObject.AssetId,
     DiscountCurve      = transportObject.DiscountCurve,
     FxConversionType   = transportObject.FxConversionType,
     FxFixingDates      = transportObject.FxFixingDates,
     FxFixingId         = transportObject.FxFixingId,
     Strike             = transportObject.Strike,
     Counterparty       = transportObject.Counterparty,
     HedgingSet         = transportObject.HedgingSet,
     PortfolioName      = transportObject.PortfolioName,
 };
Exemplo n.º 19
0
 public FundingModel(TO_FundingModel transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) :
     this(transportObject.BuildDate, transportObject.Curves.ToDictionary(x => x.Key, x => new IrCurve(x.Value, currencyProvider)), currencyProvider, calendarProvider)
 {
     VolSurfaces = transportObject.VolSurfaces.ToDictionary(x => x.Key, x => x.Value.GetVolSurface(currencyProvider));
     SetupFx(new FxMatrix(transportObject.FxMatrix, currencyProvider, calendarProvider));
 }
Exemplo n.º 20
0
 public SyncService(ICalendarProvider sourceProvider, ICalendarProvider destinationProvider)
 {
     _sourceProvider = sourceProvider;
     _destinationProvider = destinationProvider;
 }
Exemplo n.º 21
0
 public ChargeRequestPublicDateHandler(ICalendarProvider calendarProvider)
 {
     _calendarProvider = calendarProvider;
 }
Exemplo n.º 22
0
        public BasisPriceCurve(TO_BasisPriceCurve transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
        {
            Instruments = transportObject.Instruments
                          .Select(x => (IAssetInstrument)InstrumentFactory.GetInstrument(x, currencyProvider, calendarProvider))
                          .ToList();

            Pillars       = transportObject.Pillars;
            DiscountCurve = new IrCurve(transportObject.DiscountCurve, currencyProvider);
            //need to re-link via the active model
            Curve        = PriceCurveFactory.GetPriceCurve(transportObject.Curve, currencyProvider, calendarProvider);
            BaseCurve    = PriceCurveFactory.GetPriceCurve(transportObject.BaseCurve, currencyProvider, calendarProvider);
            Name         = transportObject.Name;
            AssetId      = transportObject.AssetId;
            BuildDate    = transportObject.BuildDate;
            PillarLabels = transportObject.PillarLabels;
            Currency     = currencyProvider.GetCurrencySafe(transportObject.Currency);
            SpotCalendar = calendarProvider.GetCalendarSafe(transportObject.SpotCalendar);
            if (transportObject.SpotLag != null)
            {
                SpotLag = new Frequency(transportObject.SpotLag);
            }
            CurveType = transportObject.CurveType;
        }
Exemplo n.º 23
0
 public FxVanillaOption(ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
 {
     _currencyProvider = currencyProvider;
     _calendarProvider = calendarProvider;
 }
Exemplo n.º 24
0
        public static IInstrument GetInstrument(this TO_Instrument transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
        {
            if (transportObject.AssetInstrumentType != AssetInstrumentType.None)
            {
                switch (transportObject.AssetInstrumentType)
                {
                case AssetInstrumentType.AsianSwap:
                    return(transportObject.AsianSwap.GetAsianSwap(currencyProvider, calendarProvider));

                case AssetInstrumentType.AsianSwapStrip:
                    return(new AsianSwapStrip
                    {
                        TradeId = transportObject.AsianSwapStrip.TradeId,
                        Counterparty = transportObject.AsianSwapStrip.Counterparty,
                        PortfolioName = transportObject.AsianSwapStrip.PortfolioName,
                        Swaplets = transportObject.AsianSwapStrip.Swaplets.Select(x => x.GetAsianSwap(currencyProvider, calendarProvider)).ToArray(),
                        HedgingSet = transportObject.AsianSwapStrip.HedgingSet,
                    });

                case AssetInstrumentType.AsianOption:
                    var ao = (AsianOption)GetAsianSwap(transportObject.AsianOption, currencyProvider, calendarProvider);
                    ao.CallPut = transportObject.AsianOption.CallPut;
                    return(ao);

                case AssetInstrumentType.Forward:
                    return(transportObject.Forward.GetForward(currencyProvider, calendarProvider));
                }
            }
            else
            {
                switch (transportObject.FundingInstrumentType)
                {
                }
            }

            throw new Exception("Unable to re-constitute object");
        }
Exemplo n.º 25
0
 public Currency(ICalendarProvider calendarProvider) => _calendarProvider = calendarProvider;
Exemplo n.º 26
0
 public static Portfolio GetPortfolio(this TO_Portfolio transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) => new Portfolio
 {
     PortfolioName = transportObject.PortfolioName,
     Instruments   = transportObject.Instruments.Select(x => x.GetInstrument(currencyProvider, calendarProvider)).ToList()
 };
Exemplo n.º 27
0
 public AssetFxModel(TO_AssetFxModel transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider)
     : this(transportObject.BuildDate, new FundingModel(transportObject.FundingModel, currencyProvider, calendarProvider))
 {
     _assetCurves      = transportObject.AssetCurves.ToDictionary(x => x.Key, x => x.Value.GetPriceCurve(currencyProvider, calendarProvider));
     _assetVols        = transportObject.AssetVols.ToDictionary(x => new VolSurfaceKey(x.Key, currencyProvider), y => VolSurfaceFactory.GetVolSurface(y.Value, currencyProvider));
     _fixings          = transportObject.Fixings?.ToDictionary(x => x.Key, x => (IFixingDictionary) new FixingDictionary(x.Value)) ?? new Dictionary <string, IFixingDictionary>();
     CorrelationMatrix = transportObject.CorrelationMatrix == null?null:CorrelationMatrixFactory.GetCorrelationMatrix(transportObject.CorrelationMatrix);
 }
Exemplo n.º 28
0
 private static Forward GetForward(this TO_Forward transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) => new Forward
 {
     TradeId          = transportObject.TradeId,
     Notional         = transportObject.Notional,
     Direction        = transportObject.Direction,
     ExpiryDate       = transportObject.ExpiryDate,
     FixingCalendar   = calendarProvider.GetCalendarSafe(transportObject.FixingCalendar),
     PaymentCalendar  = calendarProvider.GetCalendarSafe(transportObject.PaymentCalendar),
     SpotLag          = new Frequency(transportObject.SpotLag),
     PaymentLag       = new Frequency(transportObject.PaymentLag),
     Strike           = transportObject.Strike,
     AssetId          = transportObject.AssetId,
     PaymentCurrency  = currencyProvider.GetCurrencySafe(transportObject.PaymentCurrency),
     FxFixingId       = transportObject.FxFixingId,
     DiscountCurve    = transportObject.DiscountCurve,
     PaymentDate      = transportObject.PaymentDate,
     Counterparty     = transportObject.Counterparty,
     FxConversionType = transportObject.FxConversionType,
     HedgingSet       = transportObject.HedgingSet,
     PortfolioName    = transportObject.PortfolioName,
 };
Exemplo n.º 29
0
 public FutureSettings(ICalendarProvider calendarProvider) => _calendarProvider = calendarProvider;
Exemplo n.º 30
0
 public FxMatrix(TO_FxMatrix transportObject, ICurrencyProvider currencyProvider, ICalendarProvider calendarProvider) : this(currencyProvider)
 {
     BaseCurrency = currencyProvider.GetCurrency(transportObject.BaseCurrency);
     BuildDate    = transportObject.BuildDate;
     if (transportObject.SpotRates != null)
     {
         SpotRates = transportObject.SpotRates.ToDictionary(x => currencyProvider.GetCurrency(x.Key), y => y.Value);
     }
     if (transportObject.DiscountCurveMap != null)
     {
         DiscountCurveMap = transportObject.DiscountCurveMap.ToDictionary(x => currencyProvider.GetCurrency(x.Key), y => y.Value);
     }
     if (transportObject.FxPairDefinitions != null)
     {
         FxPairDefinitions = transportObject.FxPairDefinitions.Select(x => new FxPair(x, currencyProvider, calendarProvider)).ToList();
     }
 }
Exemplo n.º 31
0
 public CurrencyConverter(ICalendarProvider calendarProvider) => _calendarProvider = calendarProvider;