Beispiel #1
0
        public static bool IsImplementedProductType(ProductTypeSimpleEnum productType)
        {
            var isValid = false;

            switch (productType)
            {
            case ProductTypeSimpleEnum.InterestRateSwap:
            case ProductTypeSimpleEnum.AssetSwap:
            case ProductTypeSimpleEnum.CrossCurrencySwap:
            case ProductTypeSimpleEnum.FRA:
            case ProductTypeSimpleEnum.FxSpot:
            case ProductTypeSimpleEnum.FxForward:
            case ProductTypeSimpleEnum.FxSwap:
            case ProductTypeSimpleEnum.BulletPayment:
            case ProductTypeSimpleEnum.TermDeposit:
            case ProductTypeSimpleEnum.CapFloor:
            case ProductTypeSimpleEnum.InterestRateSwaption:
            case ProductTypeSimpleEnum.FxOption:
            case ProductTypeSimpleEnum.BondTransaction:
            case ProductTypeSimpleEnum.EquityTransaction:
            case ProductTypeSimpleEnum.FutureTransaction:
            case ProductTypeSimpleEnum.PropertyTransaction:
            case ProductTypeSimpleEnum.CommodityForward:
                isValid = true;
                break;
            }
            return(isValid);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FxSingleLegPricer"/> class.  All the cashfloews must be signed.
 /// </summary>
 /// <param name="fxLeg">The fxLeg.</param>
 /// <param name="baseParty">The the base party.</param>
 /// <param name="productType">THe product type: This should only be FxSpot or FxForward.</param>
 public FxSingleLegPricer(FxSingleLeg fxLeg, string baseParty, ProductTypeSimpleEnum productType)
 {
     Multiplier        = 1.0m;
     OrderedPartyNames = new List <string>();
     Id              = fxLeg.id;
     AnalyticsModel  = new FxLegAnalytic();
     ProductType     = productType;
     ExchangeRate    = fxLeg.exchangeRate;
     HybridValuation = true;
     //Get the currency.
     PaymentCurrencies = new List <string>();
     Currency1         = fxLeg.exchangedCurrency1.paymentAmount.currency;
     Currency2         = fxLeg.exchangedCurrency2.paymentAmount.currency;
     if (!PaymentCurrencies.Contains(Currency1.Value))
     {
         PaymentCurrencies.Add(Currency1.Value);
     }
     if (!PaymentCurrencies.Contains(Currency2.Value))
     {
         PaymentCurrencies.Add(Currency2.Value);
     }
     //Set the default discount curve name.
     Currency1DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(Currency1.Value, true);
     //Set the default discount curve name.
     Currency2DiscountCurveName = CurveNameHelpers.GetDiscountCurveName(Currency2.Value, true);
     //TODO
     //Set the appropraiet cross
     //if the quotebasis is : Currency1PerCurrency2 the currency curve is: currency1-currency2
     if (ExchangeRate.quotedCurrencyPair.quoteBasis == QuoteBasisEnum.Currency2PerCurrency1)
     {
         FxIndexCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(Currency1.Value,
                                                                        Currency2.Value);
     }            //Otherwise it is Currency2-Currency1
     else
     {
         FxIndexCurveName = MarketEnvironmentHelper.ResolveFxCurveNames(Currency2.Value,
                                                                        Currency1.Value);
     }
     if (fxLeg.nonDeliverableSettlement != null)//TODO Not implemented yet.
     {
         IsNonDeliverableForward             = true;
         SettlementCurrency                  = fxLeg.nonDeliverableSettlement.settlementCurrency;
         SettlementCurrencyDiscountCurveName = CurveNameHelpers.GetDiscountCurveName(SettlementCurrency.Value, true);
     }
     //Build the coupons and principal exchanges.
     Payments = PriceableInstrumentsFactory.CreatePriceableFxLegPayment(baseParty, fxLeg);
     //TODO: add extra cashflowss.
     RiskMaturityDate = fxLeg.Items1ElementName[0] == Items1ChoiceType.valueDate ? fxLeg.Items1[0] : LastDate();
 }
Beispiel #3
0
        private static void LoadFPMLTrades(
            ILogger logger,
            ICoreCache client,
            Assembly assembly,
            string sourceSystem)
        {
            logger.LogDebug("Loading FPML trades...");
            Dictionary <string, string> chosenFiles = ResourceHelper.GetResources(assembly, ResourcePath + "." + sourceSystem, "xml");

            if (chosenFiles.Count == 0)
            {
                throw new InvalidOperationException(String.Format("No trades found!"));
            }

            // load gwml-to-fpml mappings
            //EnumMaps enumMaps = client.LoadObject<EnumMaps>("Orion.Configuration.GwmlEnumMaps");
            //GwmlFpmlEnumMap gwmlFpmlEnumMap = new GwmlFpmlEnumMap(enumMaps);
            foreach (KeyValuePair <string, string> file in chosenFiles)
            {
                string fpmlText = file.Value;
                // convert gwml
                //var fpmlDoc = XmlSerializerHelper.DeserializeFromString<DataDocument>(fpmlText);
                var tradeConfirmed = XmlSerializerHelper.DeserializeFromString <RequestConfirmation>(fpmlText);
                var trade          = tradeConfirmed.trade;
                //Converter imp = new Converter(gwmlFpmlEnumMap);
                var tradeProps = new NamedValueSet();
                tradeProps.Set(TradeProp.AsAtDate, DateTime.Today);
                tradeProps.Set(TradeProp.TradeSource, sourceSystem);
                // Document fpmlDoc = imp.ToFpml(gwmlDoc, tradeProps);
                // get trade properties
                //Trade trade = (Trade)(((DataDocument)fpmlDoc).Items[0]);
                ProductTypeSimpleEnum productType = ProductTypeSimpleScheme.ParseEnumString(trade.Item.Items[0].ToString());//TODO fix this
                DateTime tradeDate = trade.tradeHeader.tradeDate.Value;
                // now we can set the actual item name correctly
                string fpmlTradeItemName = $"{sourceSystem}.Trade.{productType}.{trade.id}";
                //gwmlDocItemName = String.Format("{0}.GWML.{1}.{2}", sourceSystem, productType, trade.id);
                tradeProps.Set(TradeProp.TradeDate, tradeDate);
                tradeProps.Set(TradeProp.TradeId, trade.id);
                tradeProps.Set(TradeProp.ProductType, ProductTypeSimpleScheme.GetEnumString(productType));
                tradeProps.Set(TradeProp.TradeState, TradeState.Verified.ToString());
                client.SaveObject(trade, fpmlTradeItemName, tradeProps, false, TimeSpan.FromDays(30));
            } // foreach file
            logger.LogDebug("Loaded {0} FPML trades.", chosenFiles.Count);
        }
Beispiel #4
0
        /// <summary>
        /// This method is used to calculate a PCE (closed form) for various products
        /// </summary>
        /// <param name="product">String representing valid product name (see enum)</param>
        /// <param name="time">Time horizon (in days) for PCE calculation. Point for which PCE is calculated, relative to reporting time</param>
        /// <param name="boughtsold"></param>
        /// <param name="cashPhys"></param>
        /// <param name="tenor"></param>
        /// <param name="maturity">Time (in days) to maturity of contract</param>
        /// <param name="irVol">IR volatility</param>
        /// <param name="fxVol">FX volatility</param>
        /// <param name="intRate">interest rate</param>
        /// <param name="fraPayment"></param>
        /// <param name="ci">Confidence level. Scales volatility to obtain desired level of risk measurement</param>
        /// <param name="reversion">Reversion rate. Factor controlling future dispersion of rates</param>
        /// <returns>PCE at time horizon</returns>
        public static double Value(ProductTypeSimpleEnum product,
                                   double time,
                                   string boughtsold,
                                   string cashPhys,
                                   double tenor,
                                   double maturity,
                                   double irVol,
                                   double fxVol,
                                   double intRate,
                                   string fraPayment,
                                   double ci,
                                   double reversion)
        {
            double functionReturnValue;

            switch (product)
            {
            case ProductTypeSimpleEnum.FxSwap:
                functionReturnValue = AltFwdFxpce(maturity, time, ci, fxVol, reversion, intRate);
                break;

            case ProductTypeSimpleEnum.FxForward:     //fx forward
                functionReturnValue = AltFwdFxpce(maturity, time, ci, fxVol, reversion, intRate);
                break;

            case ProductTypeSimpleEnum.FxOption:     //fx option
                functionReturnValue = AltFXOptPCE(boughtsold, maturity, time, ci, fxVol, reversion, intRate);
                break;

            case ProductTypeSimpleEnum.InterestRateSwap:
                functionReturnValue = AltInterestRateSwapPCE(intRate, tenor, time, ci, irVol, reversion);
                break;

            //interest rate option
            case ProductTypeSimpleEnum.CapFloor:
                functionReturnValue = AltInterestRateOptPCE(boughtsold, intRate, tenor, time, ci, irVol, reversion);
                break;

            case ProductTypeSimpleEnum.CrossCurrencySwap:     //cross currency swap
                functionReturnValue = AltCrossCurrencySwapPCE(intRate, tenor, time, ci, irVol, fxVol, reversion, 0);
                break;

            case ProductTypeSimpleEnum.InterestRateSwaption:     //swaption
                functionReturnValue = AltSwaptionPCE(boughtsold, cashPhys, intRate, maturity, tenor, time, ci, irVol, reversion);
                break;

            case ProductTypeSimpleEnum.BondOption:     //bond option
                functionReturnValue = AltBondOptionPCE(boughtsold, cashPhys, intRate, maturity, tenor, time, ci, irVol, reversion);
                break;

            case ProductTypeSimpleEnum.FRA:     //forward rate agreement
                functionReturnValue = AltFrapce(fraPayment, intRate, maturity, tenor, time, ci, irVol, reversion);
                break;

            //case ProductTypeSimpleEnum.Repo: //repo
            //functionReturnValue = AltRepoPCE(intRate, tenor, maturity, time, ci, irVol, reversion);
            //break;
            case ProductTypeSimpleEnum.BondTransaction:     //bond
                functionReturnValue = AltBondPCE(boughtsold);
                break;

            //case ProductTypeSimpleEnum.Loan: //loan
            //    functionReturnValue = AltBondPCE("Bought");
            //    break;
            default:
                throw new NotSupportedException(product + " not found as a product");
            }
            return(functionReturnValue);
        }
Beispiel #5
0
        /// <summary>
        /// to build the PCE and principal profile, and give the max value
        /// extended to handle loans
        /// </summary>
        /// <param name="ppl"></param>
        /// <param name="pce">Pce profile</param>
        /// <param name="rxmPce">Max pce value</param>
        /// <param name="productType"></param>
        /// <param name="ci"></param>
        /// <param name="product"></param>
        /// <param name="boughtsold"></param>
        /// <param name="cashPhys"></param>
        /// <param name="tenor"></param>
        /// <param name="maturity"></param>
        /// <param name="fraPayment"></param>
        /// <param name="reversion"></param>
        /// <param name="intRate"></param>
        /// <param name="irVol"></param>
        /// <param name="fxVol"></param>
        /// <param name="tabRows"></param>
        /// <param name="ptype"></param>
        /// <param name="months"></param>
        public static void ProfilePce(double[] ppl,
                                      out double[] pce,
                                      out double rxmPce,
                                      int productType,
                                      double ci,
                                      ProductTypeSimpleEnum product,
                                      string boughtsold,
                                      string cashPhys,
                                      double tenor,
                                      double maturity,
                                      string fraPayment,
                                      double reversion,
                                      double intRate,
                                      double irVol,
                                      double fxVol,
                                      int tabRows,
                                      string ptype,
                                      DateMonths months)
        {
            pce    = new double[months.Totalmonths + 1];
            rxmPce = 0.0;
            // results stay in arrays
            int    i;
            double expi;

            if ((ptype != "N/A") &&
                (tabRows >= 2))
            {
                // product can have a profile, and table has more than one row..
                // build profile based on Ptype

                if (ptype == "Swap")
                {
                    // swap type profile
                    // per period df based on initial interest rate
                    double df = Math.Pow((1 + intRate), (-1 / 12));
                    // Initialise total
                    double cumSum = 0;

                    // step backwards from maturity date to start date
                    //*****
                    //***** Profile will be calculated over the term of the TradeBase ie [0, MaxMonths]
                    //***** but will be placed forward in time if this is a forward start TradeBase ie [DelayMonths, Totalmonths]
                    //*****
                    for (i = months.Maxmonths; i >= 1; i += -1)
                    {
                        // sigma sqrt t
                        double sst = irVol * Math.Pow(((1 - Math.Exp(-2 * reversion * i / 12)) / (2 * reversion)), 0.5);
                        // use approximation
                        // DeltaR = IntRate * CI * Sst
                        double deltaR = intRate * (Math.Exp(ci * sst) - 1);
                        cumSum = cumSum * df + ppl[i + months.DelayMonths] / 12;
                        expi   = cumSum * deltaR;
                        if (expi > rxmPce)
                        {
                            rxmPce = expi;
                        }
                        pce[i + months.DelayMonths] = expi;
                    }
                }
                else if (ptype == "LOAN")
                {
                    // loan type profile
                    for (i = months.Totalmonths; i >= months.DelayMonths; i += -1)
                    {
                        pce[i] = ppl[i];
                        if (pce[i] > rxmPce)
                        {
                            rxmPce = pce[i];
                        }
                    }
                }
                else
                {
                    throw new Exception("Attempt to build PCE profile- nonexisting product: " + ptype);
                }
            }
            else
            {
                // product either cannot or does not have a principal profile
                // use closed form PCE calcs
                //*****
                //***** Profile will be calculated over the term of the TradeBase ie [0, MaxMonths]
                //***** but will be placed forward in time if this is a forward start TradeBase ie [DelayMonths, Months.Totalmonths]
                //*****
                for (i = months.Maxmonths; i >= 1; i += -1)
                {
                    // use midpoint of month
                    double t1  = (i - 0.5) / 12.0 * 365.0;
                    double tt1 = t1;
                    // average exposure
                    expi = Value(product, tt1, boughtsold, cashPhys, tenor, maturity, irVol, fxVol, intRate, fraPayment, ci, reversion);
                    expi = expi * ppl[i + months.DelayMonths];

                    if (expi > rxmPce)
                    {
                        rxmPce = expi;
                    }
                    pce[i + months.DelayMonths] = expi;
                }
            }
        }
Beispiel #6
0
        protected SwapPricer(ILogger logger, ICoreCache cache, String nameSpace,
                             List <Pair <IBusinessCalendar, IBusinessCalendar> > legCalendars,
                             Swap swapFpML, string basePartyReference,
                             ProductTypeSimpleEnum productType, Boolean forecastRateInterpolation)
        {
            Multiplier = 1.0m;
            if (swapFpML == null)
            {
                return;
            }
            BusinessCentersResolver.ResolveBusinessCenters(swapFpML);
            ForecastRateInterpolation = forecastRateInterpolation;
            //Get the effective date
            AdjustableDate adjustableEffectiveDate = XsdClassesFieldResolver.CalculationPeriodDatesGetEffectiveDate(swapFpML.swapStream[0].calculationPeriodDates);

            EffectiveDate = adjustableEffectiveDate.unadjustedDate.Value;
            //We make the assumption that the termination date is the same for all legs.
            AdjustableDate adjustableTerminationDate = XsdClassesFieldResolver.CalculationPeriodDatesGetTerminationDate(swapFpML.swapStream[0].calculationPeriodDates);
            var            paymentCalendar           = BusinessCenterHelper.ToBusinessCalendar(cache, adjustableTerminationDate.dateAdjustments.businessCenters, nameSpace);

            TerminationDate  = AdjustedDateHelper.ToAdjustedDate(paymentCalendar, adjustableTerminationDate);
            RiskMaturityDate = TerminationDate;
            //EffectiveDate is not set;
            ProductType       = productType;
            PaymentCurrencies = new List <string>();
            //Resolve the payer
            var legs = swapFpML.swapStream.Length;

            if (legs == 0)
            {
                return;
            }
            var flag  = false;
            var index = 0;

            if (legCalendars != null && legCalendars.Count == legs)
            {
                flag = true;
            }
            foreach (var swapStream in swapFpML.swapStream)
            {
                bool payerIsBase = basePartyReference == swapStream.payerPartyReference.href;//TODO add in the calendar functionality.
                //Set the id of the first stream.
                PriceableInterestRateStream leg = flag ? new PriceableInterestRateStream(logger, cache, nameSpace, payerIsBase, swapStream, ForecastRateInterpolation, legCalendars[index].First, legCalendars[index].Second)
                    : new PriceableInterestRateStream(logger, cache, nameSpace, payerIsBase, swapStream, ForecastRateInterpolation, null, null);
                Legs.Add(leg);
                //Add the currencies for the trade pricer.
                if (!PaymentCurrencies.Contains(leg.Currency.Value))
                {
                    PaymentCurrencies.Add(leg.Currency.Value);
                }
                index++;
            }
            if (swapFpML.additionalPayment != null)
            {
                AdditionalPayments = PriceableInstrumentsFactory.CreatePriceablePayments(basePartyReference, swapFpML.additionalPayment, null);
                foreach (var payment in swapFpML.additionalPayment)
                {
                    if (!PaymentCurrencies.Contains(payment.paymentAmount.currency.Value))
                    {
                        PaymentCurrencies.Add(payment.paymentAmount.currency.Value);
                    }
                }
            }
        }
Beispiel #7
0
 protected SwapPricer(ILogger logger, ICoreCache cache, String nameSpace,
                      List <Pair <IBusinessCalendar, IBusinessCalendar> > legCalendars,
                      Swap swapFpML, string basePartyReference, ProductTypeSimpleEnum productType)
     : this(logger, cache, nameSpace, legCalendars, swapFpML, basePartyReference, productType, false)
 {
 }