예제 #1
0
 //public bool IsValidName(string name)
 //{
 //    using (LoanPriceEntities context = new LoanPriceEntities())
 //    {
 //        int count = context.CreditRatings.Where(s => s. == name).Count();
 //        if (count == 0)
 //            return true;
 //        else
 //            return false;
 //    }
 //}
 public string SaveRating(CreditRating rating)
 {
     using (LoanPriceEntities context = new LoanPriceEntities())
     {
         if (rating.ID <= 0)
         {
             //if (context.CreditRatings.Where(s => s.CreditAgency == rating.CreditAgency).Count() == 0)
             //{
             context.AddToCreditRatings(rating);
             context.SaveChanges();
             return("Credit Rating is added successfully");
             //}
             //else
             //    return "Entry of the same Currency is already exists.";
         }
         else
         {
             //if (context.Currencies.Where(s => s.Currancy == currency.Currancy && s.ID != currency.ID).Count() == 0)
             //{
             context.CreditRatings.Attach(rating);
             context.ObjectStateManager.ChangeObjectState(rating, System.Data.EntityState.Modified);
             context.SaveChanges();
             return("Credit Rating is Updated successfully");
             //}
             //else
             //    return "Entry of the same Currency is already exists.";
         }
     }
 }
예제 #2
0
 //DeepCopy
 public void DeepCopy(CustomerOrder from)
 {
     CustomerID = from.CustomerID;
     Rating     = from.Rating;
     AddressInfo.DeepCopy(from.AddressInfo);
     Orders.AddRange(from.Orders);
 }
예제 #3
0
 //default constructor
 public CustomerOrder()
 {
     CustomerID  = String.Empty;
     Rating      = XXsd2CodeSample.CreditRating.Good;
     AddressInfo = new Address();
     Orders      = new List <XXsd2CodeSample.CommonElements.OrderItem>();
 }
예제 #4
0
        /// <summary>
        /// Prepare for valuation.
        /// </summary>
        public override void PreValue(PriceFactorList factors)
        {
            base.PreValue(factors);

            SetModelParameters(fItems);

            PreValueDeals(fItems, factors);

            CallableStructuredDeal deal = (CallableStructuredDeal)Deal;

            // Set volatility price factors if they have been registered by model or underlying deals
            InterestVol.TryGet <IInterestRateVol>(factors, deal.Forecast_Rate_Cap_Volatility, fForecastCurrency, out fInterestRateVol);
            InterestVol.TryGet <IInterestYieldVol>(factors, deal.Forecast_Rate_Swaption_Volatility, fForecastCurrency, out fInterestYieldVol);

            bool needRating   = Respect_Default == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);
            bool needSurvival = Use_Survival_Probability == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);

            if (needRating)
            {
                fCreditRating = factors.Get <CreditRating>(deal.Issuer);
                fRecoveryRate = factors.Get <RecoveryRate>(InterestRateUtils.GetRateId(deal.Recovery_Rate, deal.Issuer));
            }

            if (needSurvival)
            {
                fSurvivalProb = factors.GetInterface <ISurvivalProb>(string.IsNullOrEmpty(deal.Survival_Probability) ? deal.Issuer : deal.Survival_Probability);
            }
        }
        public override int GetHashCode()
        {
            var hashCode = 486394590;

            hashCode = hashCode * -1521134295 + BuyerID.GetHashCode();
            hashCode = hashCode * -1521134295 + CreditRating.GetHashCode();
            return(hashCode);
        }
예제 #6
0
 public async Task <ActionResult> Create([Bind(Include = "CreditRatingID,Description")] CreditRating creditRating)
 {
     if (ModelState.IsValid)
     {
         await creditRatingRepository.CreateAsync(creditRating);
     }
     return(RedirectToAction("Index"));
 }
 public IQueryable<Supplier> GetSupplierByCriteria(int preferred, int active, CreditRating creditRating)
 {
     IQueryable<Supplier> customers = new List<Supplier>().AsQueryable();
     
     customers = rep.GetAll().Where(s => s.ActiveFlag == 1 && 
                                         s.PreferedSupplier == preferred && 
                                         s.CreditRating == (int) creditRating);
     
     return customers;
 }
예제 #8
0
        public async Task <ActionResult> Delete(int id)
        {
            CreditRating creditRating = await creditRatingRepository.FindCreditRatingByIDAsync(id);

            if (creditRating == null)
            {
                return(HttpNotFound());
            }
            return(View(creditRating));
        }
예제 #9
0
 /// <summary>
 /// Return the time of default for the underlying obligor. Allows derived valuation models to
 /// support realized default.
 /// </summary>
 protected void DefaultTime(Vector vout, CreditRating creditRating)
 {
     if (creditRating == null)
     {
         vout.Assign(CreditRating.TimeOfDefault.Never);
     }
     else
     {
         creditRating.DefaultTime(vout);
     }
 }
        /// <summary>
        /// Sets defaultDate to valueDate on the first call for which t >= defaultTime.
        /// </summary>
        /// <remarks>Assumes that defaultDate was initialized to a large date value.</remarks>
        protected static void UpdateDefaultDate(CreditRating creditRating, double valueDate, double t, Vector defaultDate)
        {
            using (var cache = Vector.CacheLike(defaultDate))
            {
                // Get time of default
                Vector defaultTime = cache.Get();
                creditRating.DefaultTime(defaultTime);

                defaultDate.AssignConditional(defaultTime > t, defaultDate, VectorMath.Min(defaultDate, valueDate));
            }
        }
예제 #11
0
        public void LoanApplicationValueChanged(int loanAmount, int loanTerm, CreditRating creditRating)
        {
            var loanApplication = new LoanApplication
                                  	{
                                  		Amount = loanAmount,
                                  		Term = loanTerm,
                                  		CreditRating = creditRating
                                  	};

            _applicationController.PublishMessage(new LoanApplicationUpdatedMessage(loanApplication));
        }
예제 #12
0
        /// <inheritdoc />
        protected override void GetDefaultTime(Vector defaultTime, PriceFactorList factors)
        {
            CreditRating cr = GetCreditRating(factors);

            if (cr != null)
            {
                cr.DefaultTime(defaultTime);
                return;
            }

            base.GetDefaultTime(defaultTime, factors);
        }
예제 #13
0
 public void Delete(int id)
 {
     using (LoanPriceEntities context = new LoanPriceEntities())
     {
         CreditRating group = context.CreditRatings.FirstOrDefault(c => c.ID == id);
         if (group != null)
         {
             context.CreditRatings.DeleteObject(group);
             context.SaveChanges();
         }
     }
 }
예제 #14
0
        /// <summary>
        /// Prepare for valuation anything that is dependent upon the scenario.
        /// </summary>
        public override void PreValue(PriceFactorList factors)
        {
            base.PreValue(factors);

            CallableBondForward deal = (CallableBondForward)Deal;

            fInterestYieldVol = InterestVolBase.GetYieldVol(factors, deal.Yield_Volatility, fCurrency);

            fNeedsCreditRating = NeedCreditRating();
            fCreditRating      = NeedCreditRating() ? factors.Get <CreditRating>(deal.Issuer)                                                                               : null;
            fRecoveryRate      = NeedRecovery()     ? factors.Get <RecoveryRate>(string.IsNullOrEmpty(deal.Recovery_Rate) ? deal.Issuer : deal.Recovery_Rate)               : null;
            fSurvivalProb      = NeedSurvivalProb() ? factors.GetInterface <ISurvivalProb>(string.IsNullOrEmpty(deal.Survival_Probability) ? deal.Issuer : deal.Survival_Probability) : null;
        }
예제 #15
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public CreditValuationParameters(DealCreditBase deal, CreditBaseValuation valuation, PriceFactorList factors, VectorScopedCache.Scope cache)
        {
            DF          = DiscountRate.Get(factors, InterestRateUtils.GetRateId(deal.Discount_Rate, deal.Currency));
            X           = factors.GetInterface <IFxRate>(deal.Currency);
            SP          = factors.GetInterface <ISurvivalProb>(string.IsNullOrEmpty(deal.Survival_Probability) ? deal.Name : deal.Survival_Probability);
            RR          = null;
            CR          = null;
            DefaultTime = null;
            Weights     = null;
            NamesDefaultedBeforeBaseDate = null;

            if (valuation.Respect_Default == YesNo.Yes)
            {
                List <string> names = new List <string>();
                if (deal.ProtectionReferenceType() == DealCreditBase.ReferenceType.Single_Name)
                {
                    names.Add(deal.Name);
                    Weights = new double[] { 1.0 };
                }
                else
                {
                    IndexCDSPool indexCds = factors.Get <IndexCDSPool>(deal.Name);
                    Weights = new double[indexCds.Names.Count];
                    for (int i = 0; i < indexCds.Names.Count; ++i)
                    {
                        names.Add(indexCds.Names[i].Name);
                        Weights[i] = indexCds.Names[i].Weight;
                    }
                }

                if (valuation.RequiresRecoveryOnDefault())
                {
                    RR = new RecoveryRate[names.Count];
                    for (int i = 0; i < names.Count; ++i)
                    {
                        RR[i] = factors.Get <RecoveryRate>(string.IsNullOrEmpty(deal.Recovery_Rate) ? names[i] : deal.Recovery_Rate);
                    }
                }

                CR = new CreditRating[names.Count];
                NamesDefaultedBeforeBaseDate = new bool[names.Count];
                DefaultTime = new Vector[names.Count];
                for (int i = 0; i < names.Count; ++i)
                {
                    DefaultTime[i] = cache.Get();
                    CR[i]          = factors.Get <CreditRating>(names[i]);
                    NamesDefaultedBeforeBaseDate[i] = CreditRating.DefaultedBeforeBaseDate(CR[i], factors.BaseDate);
                    CR[i].DefaultTime(DefaultTime[i]);
                }
            }
        }
        /// <summary>
        /// Prepare for valuation anything that is dependent upon the scenario.
        /// </summary>
        /// <param name="factors">Price factors.</param>
        public override void PreValue(PriceFactorList factors)
        {
            base.PreValue(factors);

            IInflationCashflowListDeal deal = (IInflationCashflowListDeal)Deal;

            fIsDefaultNever  = !NeedCreditRating();
            fCreditRating    = NeedCreditRating()                      ? factors.Get <CreditRating>(deal.Issuer)                       : null;
            fRecoveryRate    = NeedRecoveryRate()                      ? factors.Get <RecoveryRate>(GetRecoveryRateID())               : null;
            fSurvivalProb    = NeedSurvivalProb()                      ? factors.GetInterface <ISurvivalProb>(GetSurvivalProbID())     : null;
            fInflationRate   = !string.IsNullOrEmpty(deal.Index)       ? factors.GetInterface <IInflationRate>(deal.Index)             : null;
            fRepoRate        = !string.IsNullOrEmpty(deal.Repo_Rate)   ? factors.GetInterface <IInterestRate>(deal.Repo_Rate)          : fDiscountRate;
            fIndexVolatility = deal is InflationOptionCashflowListDeal?factors.GetInterface <IPriceIndexVolatility>(GetPriceIndexVolatility()) : null;
        }
예제 #17
0
        /// <summary>
        /// Prepare for valuation anything that is dependent upon the scenario.
        /// </summary>
        /// <param name="factors">Price factors.</param>
        public override void PreValue(PriceFactorList factors)
        {
            base.PreValue(factors);

            BondOptionDeal deal = (BondOptionDeal)Deal;

            bool needRating   = Respect_Default == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);
            bool needSurvival = Use_Survival_Probability == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);
            bool needRecovery = needRating;

            fCreditRating = needRating ? factors.Get <CreditRating>(deal.Issuer) : null;
            fRecoveryRate = needRecovery ? factors.Get <RecoveryRate>(string.IsNullOrEmpty(deal.Recovery_Rate) ? deal.Issuer : deal.Recovery_Rate) : null;
            fSurvivalProb = needSurvival ? factors.GetInterface <ISurvivalProb>(string.IsNullOrEmpty(deal.Survival_Probability) ? deal.Issuer : deal.Survival_Probability) : null;
        }
예제 #18
0
파일: Vendor.cs 프로젝트: johaDev/CodegenCS
 public override int GetHashCode()
 {
     unchecked
     {
         int hash = 17;
         hash = hash * 23 + (AccountNumber == null ? 0 : AccountNumber.GetHashCode());
         hash = hash * 23 + (ActiveFlag == default(bool) ? 0 : ActiveFlag.GetHashCode());
         hash = hash * 23 + (BusinessEntityId == default(int) ? 0 : BusinessEntityId.GetHashCode());
         hash = hash * 23 + (CreditRating == default(byte) ? 0 : CreditRating.GetHashCode());
         hash = hash * 23 + (ModifiedDate == default(DateTime) ? 0 : ModifiedDate.GetHashCode());
         hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
         hash = hash * 23 + (PreferredVendorStatus == default(bool) ? 0 : PreferredVendorStatus.GetHashCode());
         hash = hash * 23 + (PurchasingWebServiceUrl == null ? 0 : PurchasingWebServiceUrl.GetHashCode());
         return(hash);
     }
 }
예제 #19
0
        public DecisionResponse GetDecision(CreditCardApplication application)
        {
            var decision = new DecisionResponse {
                Result = DecisionResult.Declined
            };

            if (application.HomeAddress.State == "OK")
            {
                decision.Result = DecisionResult.Declined;
                return(decision);
            }
            var creditReport = _creditService.CheckCreditHistory(new CreditCardApplication());

            var isQualified = CreditRating.FromScore(creditReport.CreditScore).Qualified;

            decision.Result = isQualified ? DecisionResult.Approved : DecisionResult.Declined;

            return(decision);
        }
예제 #20
0
        /// <summary>
        /// Prepare for valuation anything that is dependent upon the scenario.
        /// </summary>
        public override void PreValue(PriceFactorList factors)
        {
            base.PreValue(factors);

            CFListBaseDeal <TCashflowList> deal = (CFListBaseDeal <TCashflowList>)fDeal;

            if (string.IsNullOrEmpty(fDeal.GetIssuer()))
            {
                return;
            }

            if (UseSurvivalProbability())
            {
                fSurvivalProb = factors.GetInterface <ISurvivalProb>(string.IsNullOrEmpty(deal.GetSurvivalProbability()) ? deal.GetIssuer() : deal.GetSurvivalProbability());
            }

            if (RespectDefault())
            {
                fRecoveryRate = factors.Get <RecoveryRate>(InterestRateUtils.GetRateId(deal.GetRecoveryRate(), deal.GetIssuer()));
                fCreditRating = factors.Get <CreditRating>(deal.GetIssuer());
            }
        }
예제 #21
0
 /// <summary>
 /// Resets the StateManager to the default state. Use this when
 /// the player's session needs to be reset. The StateManger is
 /// set up for a "fresh" playthrough.
 /// </summary>
 public static void resetToDefaultState()
 {
     cashOnHand = DefaultState.cashOnHand;
     loanList.Clear();
     income.Clear();
     nextID             = DefaultState.nextID;
     timesEntered       = DefaultState.timesEntered;
     totalFloorsVisited = DefaultState.totalFloorsVisited;
     currentFloor       = DefaultState.currentFloor;
     scoreChangeFactor  = DefaultState.scoreChangeFactor;
     lastCreditScore    = 0;
     creditScore        = DefaultState.creditScore;
     paymentStreak      = DefaultState.paymentStreak;
     cashOnEntrance     = DefaultState.cashOnEntrance;
     sawEntryTutorial   = DefaultState.sawEntryTutorial;
     inStoryTutorial    = DefaultState.inStoryTutorial;
     destroyAllSingletons();
     pauseAvailable     = DefaultState.pauseAvailable;
     playerDead         = DefaultState.playerDead;
     playerWon          = DefaultState.playerWon;
     startedFromDungeon = DefaultState.startedFromDungeon;
     currentRating      = FairCredit;
 }
예제 #22
0
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            CreditRating creditRating = (CreditRating)Enum.Parse(typeof(CreditRating), value.ToString());

            switch (creditRating)
            {
            case CreditRating.Superior:
                return(Strings.CreditRating_Superior);

            case CreditRating.Excellent:
                return(Strings.CreditRating_Excellent);

            case CreditRating.AboveAverage:
                return(Strings.CreditRating_AboveAverage);

            case CreditRating.Average:
                return(Strings.CreditRating_Average);

            case CreditRating.BelowAverage:
                return(Strings.CreditRating_BelowAverage);
            }
            return(value);
        }
예제 #23
0
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var dict = new Dictionary <CreditRating, double>();

        while (reader.Read())
        {
            if (reader.TokenType == JsonToken.PropertyName)
            {
                string readerValue = reader.Value.ToString();
                var    cr          = new CreditRating(readerValue);
                if (reader.Read() && reader.TokenType == JsonToken.Float)
                {
                    var val = Convert.ToDouble(reader.Value);
                    dict.Add(cr, val);
                }
            }
            if (reader.TokenType == JsonToken.EndObject)
            {
                return(dict);
            }
        }
        return(dict);
    }
예제 #24
0
        /// <summary>
        /// Vector valuation function.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator         tgi         = new TimeGridIterator(fT);
            PVProfiles               result      = valuationResults.Profile;
            CashAccumulators         accumulator = valuationResults.Cash;
            DealCreditLinkedNoteBase deal        = (DealCreditLinkedNoteBase)fDeal;

            ISurvivalProb SP = GetSurvivalProbability(factors);
            RecoveryRate  RR = GetRecoveryRate(factors);
            CreditRating  CR = GetCreditRating(factors);

            double tEffective    = CalcUtils.DaysToYears(deal.Effective_Date - factors.BaseDate);
            double scale         = (deal.Buy_Sell == BuySell.Buy) ? +deal.Notional_Amount : -deal.Notional_Amount;
            double purchasePrice = Percentage.PercentagePoint * deal.Price;
            double couponRate    = (deal.Coupon_Type == InterestRateType.Fixed) ? Percentage.PercentagePoint * deal.Coupon_Rate : 0.0;
            double couponSpread  = (deal.Coupon_Type == InterestRateType.Fixed) ? 0.0 : BasisPoint.BasisPointValue * deal.Coupon_Spread;
            double indexTenor    = (deal.Index_Tenor > 0.0) ? deal.Index_Tenor : deal.Coupon_Interval;

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                bool[] hasDefaulted       = (Respect_Default == YesNo.Yes) ? new bool[factors.NumScenarios] : null;
                Vector defaultTime        = (Respect_Default == YesNo.Yes) ? cache.Get() : null;
                Vector historicalRecovery = (Respect_Default == YesNo.Yes) ? cache.GetClear() : null;

                if (hasDefaulted != null && CR != null)
                {
                    DefaultTime(defaultTime, CR);
                }

                Vector npv      = cache.Get();
                Vector cash     = cache.Get();
                Vector pStart   = cache.Get();
                Vector pEnd     = cache.Get();
                Vector amount   = cache.Get();
                Vector recovery = cache.Get();
                Vector dfLast   = cache.Get();
                Vector df       = cache.Get();

                cash.Clear();
                var defaultedBeforeTheBaseDate = Respect_Default == YesNo.Yes &&
                                                 CreditRating.DefaultedBeforeBaseDate(CR, factors.BaseDate);
                while (tgi.Next())
                {
                    if (defaultedBeforeTheBaseDate)
                    {
                        npv.Clear();
                        result.AppendVector(tgi.Date, npv);
                        break;
                    }

                    if (!deal.Principal_Guaranteed && Respect_Default == YesNo.Yes)
                    {
                        RealizedRecoveryRate(recovery, RR, tgi.T);
                    }

                    // Assume defaults are rare and start by valuing under all scenarios without realized defaults

                    // Value of principal repayment
                    SurvivalProbability(pEnd, factors, SP, tgi.T, fT.fLast);
                    fDiscountRate.GetValue(dfLast, tgi.T, fT.fLast);
                    if (deal.Principal_Guaranteed)
                    {
                        npv.Assign(dfLast);
                    }
                    else
                    {
                        npv.Assign(dfLast * pEnd);
                    }
                    if (accumulator != null && tgi.T == fT.fLast)
                    {
                        cash.Assign(npv);
                    }

                    // Value of coupons
                    for (int i = PayDates.Count - 1; i >= 0 && tgi.Date <= PayDates[i]; --i)
                    {
                        double tPay      = CalcUtils.DaysToYears(PayDates[i] - factors.BaseDate);
                        double tReset    = CalcUtils.DaysToYears(ResetDates[i] - factors.BaseDate);
                        double tPrevious = Math.Max(tgi.T, tReset);
                        SurvivalProbability(pStart, factors, SP, tgi.T, tPrevious);

                        if (deal.Coupon_Type == InterestRateType.Floating)
                        {
                            // Forecast a coupon, add the spread
                            InterestRateUtils.LiborRate(amount, fForecastRate, tgi.T, tReset, tReset, tReset + indexTenor, deal.Index_Day_Count);
                            amount.Add(couponSpread);
                            amount.MultiplyBy(Accruals[i]);
                        }
                        else
                        {
                            // Fixed coupon
                            amount.Assign(couponRate * Accruals[i]);
                        }

                        // The value of the coupon if no default
                        npv.Add(amount * fDiscountRate.Get(tgi.T, tPay) * pEnd);
                        if (accumulator != null && tgi.T == tPay)
                        {
                            cash.Assign(amount);
                        }

                        // The recovery value on default - assume guaranteed principal paid at end, recovery paid immediately
                        if (!deal.Principal_Guaranteed)
                        {
                            npv.Add(fDiscountRate.Get(tgi.T, 0.5 * (tPay + tPrevious)) * (pStart - pEnd) * PricingRecoveryRate(SP));
                        }

                        pEnd.DestructiveAssign(pStart);
                    }

                    // Now check for realized default scenario by scenario, overwriting NPV and cash as appropriate
                    if (Respect_Default == YesNo.Yes && defaultTime != null)
                    {
                        if (tgi.T < tEffective)
                        {
                            fDiscountRate.GetValue(df, tgi.T, tEffective);
                        }

                        for (int i = 0; i < npv.Count; ++i)
                        {
                            if (defaultTime[i] > tgi.T)
                            {
                                continue;
                            }

                            if (deal.Principal_Guaranteed)
                            {
                                npv[i] = dfLast[i];   // full principal paid at maturity
                            }
                            else
                            {
                                if (!hasDefaulted[i])
                                {
                                    historicalRecovery[i] = recovery[i];   // record the historical recovery rate
                                }
                                if (tgi.T < tEffective)
                                {
                                    npv[i] = df[i] * historicalRecovery[i];   // The discounted recovery value of the principal will be paid out on the effective date
                                }
                                else if (tgi.T == tEffective || !hasDefaulted[i])
                                {
                                    npv[i] = historicalRecovery[i];           // The full recovery amount is paid out
                                }
                                else
                                {
                                    npv[i] = 0.0;                             // default is in the past but we are after effective date; settlement has already occurred.
                                }
                            }

                            hasDefaulted[i] = true;
                        }
                    }

                    // Value of purchase price
                    if (tgi.T < tEffective)
                    {
                        npv.Add(-purchasePrice * fDiscountRate.Get(tgi.T, tEffective));
                    }
                    else if (tgi.T == tEffective)
                    {
                        npv.Add(-purchasePrice);
                        if (accumulator != null)
                        {
                            cash.Add(-purchasePrice);
                        }
                    }

                    result.AppendVector(tgi.Date, scale * npv * fFxRate.Get(tgi.T));
                    if (accumulator != null)
                    {
                        accumulator.Accumulate(fFxRate, tgi.Date, scale * cash);
                    }
                }

                // After maturity
                result.Complete(fT);
            }
        }
예제 #25
0
 public static CreditRatingViewModel FromCreditRating(CreditRating creditRating)
 {
     return(new CreditRatingViewModel(creditRating));
 }
예제 #26
0
 public CreditRatingViewModel(CreditRating creditRating)
 {
     this.CreditRatingID = creditRating.CreditRatingID;
     this.Description    = creditRating.Description;
 }
예제 #27
0
 //default constructor
 public CustomerOrder()
 {
     CustomerID = String.Empty;
     Rating = XXsd2CodeSample.CreditRating.Good ;
     AddressInfo = new Address() ;
     Orders = new List<XXsd2CodeSample.CommonElements.OrderItem>() ;
 }
예제 #28
0
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            BondOptionDeal deal = (BondOptionDeal)Deal;

            double baseDate  = factors.BaseDate;
            double notional  = deal.Notional;
            double interval  = deal.Coupon_Interval;
            double buySign   = (deal.Buy_Sell == BuySell.Buy) ? +1 : -1;
            double paySign   = (deal.Option_Type == OptionType.Call) ? +1 : -1;
            double coupon    = Percentage.PercentagePoint * deal.Coupon_Rate;
            double tExpiry   = CalcUtils.DaysToYears(deal.Expiry_Date - baseDate);
            double tMaturity = CalcUtils.DaysToYears(deal.Bond_Maturity_Date - baseDate);

            IInterestYieldVol interestYieldVol = InterestVolBase.GetYieldVol(factors, deal.Yield_Volatility, fCurrency);

            if ((deal.Amortisation) != null && (deal.Amortisation.Count > 0))
            {
                notional = deal.Amortisation.GetPrincipal(notional, deal.Expiry_Date);
            }

            bool respectDefault = Respect_Default == YesNo.Yes && fCreditRating != null;

            using (IntraValuationDiagnosticsHelper.StartDeal(fIntraValuationDiagnosticsWriter, Deal))
            {
                using (var pricerCache = Vector.Cache(factors.NumScenarios))
                {
                    Vector defaultTime        = null;
                    Vector bondIsAlive        = null;
                    Vector historicalRecovery = null;

                    if (respectDefault)
                    {
                        defaultTime        = pricerCache.Get();
                        bondIsAlive        = pricerCache.Get(1.0);
                        historicalRecovery = pricerCache.GetClear();

                        fCreditRating.DefaultTime(defaultTime);
                    }

                    var defaultedBeforeBaseDate = respectDefault && CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);

                    VectorEngine.For(tgi, () =>
                    {
                        using (IntraValuationDiagnosticsHelper.StartValuation(fIntraValuationDiagnosticsWriter, tgi.Date))
                        {
                            using (var cache = Vector.Cache(factors.NumScenarios))
                            {
                                Vector optionValue      = cache.GetClear();
                                Vector stdDev           = cache.Get(); // Std.Dev of Price
                                Vector stdDevYield      = cache.Get(); //Std.Dev of Yield
                                Vector price            = cache.Get();
                                Vector yield            = cache.Get();
                                Vector macaulayDuration = cache.Get();
                                Vector bondValue        = cache.Get();
                                Vector df  = cache.Get();
                                Vector dfr = fRepoIsDiscount ? null : cache.Get();

                                if (defaultedBeforeBaseDate)
                                {
                                    result.AppendVector(tgi.Date, optionValue);
                                    return(LoopAction.Break);
                                }

                                // This BondPrice function returns the value of the bond cashflows after ExpiryDate, including accrual, discounted back to T.date
                                double accrual, cash;
                                PricingFunctions.BondPrice(bondValue, out accrual, out cash, baseDate, tgi.Date, deal.Expiry_Date, deal.Issue_Date, deal.Bond_Maturity_Date, notional, coupon, fPayDates, fAccruals, fDiscountRate, deal.Amortisation, fPrincipals, fFinalPrincipal, fSurvivalProb, +1.0);

                                // Now check scenario by scenario for defaults, overwriting bondValue as necessary
                                if (respectDefault)
                                {
                                    AdjustBondValueForDefault(notional, tExpiry, bondValue, bondIsAlive, historicalRecovery, defaultTime, tgi.T, fDiscountRate, fRecoveryRate);
                                }

                                // convert price and duration to forward (tExpiry) basis
                                if (tgi.Date == deal.Expiry_Date)
                                {
                                    optionValue.Assign(buySign * VectorMath.Max(0.0, paySign * (bondValue - notional * fStrike)));
                                    cashAccumulators.Accumulate(fFxRate, tgi.Date, optionValue);
                                }
                                else
                                {
                                    fDiscountRate.GetValue(df, tgi.T, tExpiry);

                                    if (fRepoIsDiscount)
                                    {
                                        dfr = df;
                                    }
                                    else
                                    {
                                        fRepoRate.GetValue(dfr, tgi.T, tExpiry);
                                    }

                                    // Need yield and duration to convert yield vol to price vol.
                                    PricingFunctions.BondForwardPriceAndAdjustedMacaulayDuration(price, macaulayDuration, tgi.T, tExpiry, tMaturity, coupon, interval, df, fDiscountRate, fSurvivalProb);
                                    PricingFunctions.BondYieldFromPrice(yield, tExpiry, tMaturity, coupon, interval, price);

                                    // Calculate Modified Duration from Macaulay Duration.
                                    Vector modifiedDuration = cache.GetClear();
                                    PricingFunctions.GetModifiedDuration(modifiedDuration, macaulayDuration, yield, interval);

                                    // Calculate Std.Dev of Yield and Price
                                    interestYieldVol.GetStdDev(stdDevYield, tgi.T, yield, fStrikeYield, tExpiry, tMaturity - tExpiry);
                                    stdDev.Assign(modifiedDuration * stdDevYield);

                                    if (interestYieldVol.GetDistributionType() == ProbabilityDistribution.Lognormal)
                                    {
                                        stdDev.MultiplyBy(yield);
                                    }

                                    price.AssignQuotient(bondValue, df);
                                    PricingFunctions.BlackFunction(optionValue, deal.Option_Type, price, notional * fStrike, stdDev);

                                    optionValue.MultiplyBy(buySign * dfr);

                                    if (fIntraValuationDiagnosticsWriter.Level > IntraValuationDiagnosticsLevel.None)
                                    {
                                        // Add Intra-valuation Diagnostics
                                        using (var volatilitiesAtDateStore = IntraValuationDiagnosticsHelper.CreateVolatilitiesAtDateStore(fIntraValuationDiagnosticsWriter, factors.NumScenarios))
                                            using (var volatilitiesYieldAtDateStore = IntraValuationDiagnosticsHelper.CreateVolatilitiesAtDateStore(fIntraValuationDiagnosticsWriter, factors.NumScenarios))
                                            {
                                                volatilitiesAtDateStore.Add(tgi.Date, tgi.TimeGrid.fEndDate, stdDev);
                                                volatilitiesYieldAtDateStore.Add(tgi.Date, tgi.TimeGrid.fEndDate, stdDevYield);
                                                IntraValuationDiagnosticsHelper.AddBondOptionProperties(fIntraValuationDiagnosticsWriter, price, dfr, bondValue, accrual,
                                                                                                        volatilitiesAtDateStore, volatilitiesYieldAtDateStore);
                                                IntraValuationDiagnosticsHelper.AddCashflowsPV(fIntraValuationDiagnosticsWriter, optionValue);
                                            }
                                    }
                                }

                                result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * optionValue);
                                return(LoopAction.Continue);
                            }
                        }
                    });
                }

                result.Complete(fT);
            }
        }
예제 #29
0
        /// <summary>
        /// Calculate a valuation profile for the deal for the current scenario.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            var deal = (CFListBaseDeal <TCashflowList>)fDeal;

            double baseDate = factors.BaseDate;

            var              tgi              = new TimeGridIterator(fT);
            PVProfiles       result           = valuationResults.Profile;
            CashAccumulators cashAccumulators = valuationResults.Cash;

            double endDate = deal.EndDate();

            using (IntraValuationDiagnosticsHelper.StartDeal(fIntraValuationDiagnosticsWriter, fDeal))
            {
                using (var outerCache = Vector.Cache(factors.NumScenarios))
                {
                    Vector defaultDate = fCreditRating != null?outerCache.Get(CalcUtils.DateTimeMaxValueAsDouble) : null;

                    var  defaultedBeforeBaseDate = CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);
                    bool collectCash             = ValueOnCashflowDates();

                    var saccrResult = SACCRResultFactory.Create(valuationResults, deal.GetDealReferenceProvider().DealReference,
                                                                () => new SACCROptionResult(factors.NumScenarios));

                    VectorEngine.For(tgi, () =>
                    {
                        using (var cache = Vector.Cache(factors.NumScenarios))
                        {
                            Vector pv   = cache.GetClear();
                            Vector cash = collectCash ? cache.GetClear() : null;

                            if (!defaultedBeforeBaseDate)
                            {
                                using (IntraValuationDiagnosticsHelper.StartCashflowsOnDate(fIntraValuationDiagnosticsWriter, tgi.Date))
                                {
                                    using (IntraValuationDiagnosticsHelper.StartCashflows(fIntraValuationDiagnosticsWriter, fFxRate, tgi.T, deal))
                                    {
                                        Value(pv, cash, baseDate, tgi.Date, saccrResult, fIntraValuationDiagnosticsWriter);
                                        IntraValuationDiagnosticsHelper.AddCashflowsPV(fIntraValuationDiagnosticsWriter, pv);
                                    }
                                }

                                if (fCreditRating != null)
                                {
                                    UpdateDefaultDate(fCreditRating, tgi.Date, tgi.T, defaultDate);
                                    GetDefaultValue(baseDate, tgi.Date, defaultDate, fRecoveryRate, pv, cash);
                                }
                            }

                            result.AppendVector(tgi.Date, pv * fFxRate.Get(tgi.T));

                            if (!cashAccumulators.Ignore && cash != null)
                            {
                                // Realise all value as cash on deal end date
                                if (tgi.Date == endDate)
                                {
                                    cash.Assign(pv);
                                }

                                cashAccumulators.Accumulate(fFxRate, tgi.Date, cash);
                            }
                        }
                    });

                    if (!cashAccumulators.Ignore && !collectCash)
                    {
                        CollectCashflows(cashAccumulators, baseDate, fT.fHorizon);

                        // Consolidate and net in order to avoid getting Net incoming and outgoing cashflows with the same payment date,
                        // e.g. for compounding swaps with both positive and negative rates.
                        cashAccumulators.ConsolidateAndNet(fCurrency, factors);
                    }

                    result.Complete(fT);
                }
            }
        }
예제 #30
0
        /// <summary>
        /// Calculate valuation profiles.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            TimeGridIterator tgi             = new TimeGridIterator(fT);
            PVProfiles       result          = valuationResults.Profile;
            CashAccumulators cashAccumulator = valuationResults.Cash;
            double           baseDate        = factors.BaseDate;

            CallableStructuredDeal deal = (CallableStructuredDeal)fDeal;

            int buySellSign = deal.Buy_Sell == BuySell.Buy ? +1 : -1;
            int callPutSign = deal.Option_Type == OptionType.Call ? 1 : -1;

            InterestRateOptionPricer optionPricer = CreateOptionPricer(factors);

            CalcUtils.CreateDealProfilesIfRequired(valuationResults, fItems, factors);

            bool needRating = Respect_Default == YesNo.Yes && !string.IsNullOrEmpty(deal.Issuer);

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                Vector exercised      = cache.GetClear(); // vector taking value 0 or 1 indicating exercise before tgi.date
                Vector exercisedToday = cache.Get();      // vector taking value 0 or 1 indicating exercise at tgi.date

                Vector optionPv = cache.Get();
                Vector pv       = cache.Get();
                Vector cash     = cache.Get();
                Vector settlementDateAtExercise = cache.GetClear();
                Vector defaultDate = needRating ? cache.Get(CalcUtils.DateTimeMaxValueAsDouble) : null;

                var defaultedBeforeBaseDate = needRating &&
                                              CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);

                while (tgi.Next())
                {
                    if (defaultedBeforeBaseDate)
                    {
                        pv.Clear();
                        result.AppendVector(tgi.Date, pv);
                        break;
                    }

                    if (needRating)
                    {
                        UpdateDefaultDate(fCreditRating, tgi.Date, tgi.T, defaultDate);
                    }

                    double val;
                    bool   allExercised = exercised.AllElementsTheSame(out val) && val == 1.0;

                    if (deal.Settlement_Style == SettlementType2.Physical)
                    {
                        // Calculate value of option (option value is zero after last exercise date)
                        if (!allExercised)
                        {
                            optionPricer.Value(baseDate, tgi.Date, optionPv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);
                        }

                        // Calculate value of underlying cashflows after settlementDateAtExercise
                        pv.Clear();
                        cash.Clear();
                        InterestRateOptionPricer.ValueDeals(fItems, pv, cash, baseDate, tgi.Date, settlementDateAtExercise, defaultDate, fDiscountRate, fForecastRate, fRepoRate, fInterestRateVol, fInterestYieldVol, fSurvivalProb, fRecoveryRate);
                        pv.MultiplyBy(callPutSign);
                        cash.MultiplyBy(callPutSign);

                        if (!allExercised)
                        {
                            // If exercised today the cashflow is the value of the option minus the value of the physically settled part
                            // Else if already exercised, cash is the unnderlying cash.
                            // Else (before exercise) there is no cash.
                            cash.AssignConditional(exercisedToday, optionPv - pv, exercised * cash);

                            // If already exercised, pv is the unnderlying pv.
                            // Else (before exercise or exercised today), pv is the option pv.
                            pv.AssignConditional(exercised, pv, optionPv);
                            pv.AssignConditional(exercisedToday, optionPv, pv);
                        }
                    }
                    else
                    {
                        if (allExercised)
                        {
                            // Already exercised on all scenarios
                            result.AppendZeroVector(tgi.Date);
                            continue;
                        }

                        if (deal.Settlement_Style == SettlementType2.Cash)
                        {
                            // Calculate value of option
                            optionPricer.Value(baseDate, tgi.Date, pv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);

                            // If exercised today then option pv is settled today, otherwise there is no cash
                            cash.AssignProduct(pv, exercisedToday);
                        }
                        else // Embedded option (callable or puttable)
                        {
                            // Calculate underlying value
                            pv.Clear();
                            cash.Clear();
                            InterestRateOptionPricer.ValueDeals(fItems, pv, cash, baseDate, tgi.Date, null, defaultDate, fDiscountRate, fForecastRate, fRepoRate, fInterestRateVol, fInterestYieldVol, fSurvivalProb, fRecoveryRate);

                            // Calculate value of option
                            optionPricer.Value(baseDate, tgi.Date, optionPv, exercised, exercisedToday, settlementDateAtExercise, defaultDate);

                            // Add or subtract value of embedded option
                            pv.AddProduct(-callPutSign, optionPv);

                            // Option payoff is Max(callPutSign * (underlyingPv - accruedInterest - discountedFee), 0)
                            // Callable/puttable payoff on exercise is
                            // underlyingPv - callPutSign * (callPutSign * (underlyingPv - accruedInterest - discountedFee))
                            // = accruedInterest + discountedFee

                            // Set pv and cash to zero if already exercised.
                            // If exercised today then the pv is settled today.
                            pv.AssignConditional(exercised, exercisedToday * pv, pv);
                            cash.AssignConditional(exercised, exercisedToday * pv, cash);
                        }
                    }

                    pv.MultiplyBy(buySellSign);
                    cash.MultiplyBy(buySellSign);
                    result.AppendVector(tgi.Date, fFxRate.Get(tgi.T) * pv);
                    cashAccumulator.Accumulate(fFxRate, tgi.Date, cash);
                }
            }

            result.Complete(fT);
        }
예제 #31
0
        /// <inheritdoc/>
        public string ToDelimitedString()
        {
            CultureInfo culture = CultureInfo.CurrentCulture;

            return(string.Format(
                       culture,
                       StringHelper.StringFormatSequence(0, 55, Configuration.FieldSeparator),
                       Id,
                       SetIdPv1.HasValue ? SetIdPv1.Value.ToString(culture) : null,
                       PatientClass?.ToDelimitedString(),
                       AssignedPatientLocation?.ToDelimitedString(),
                       AdmissionType?.ToDelimitedString(),
                       PreadmitNumber?.ToDelimitedString(),
                       PriorPatientLocation?.ToDelimitedString(),
                       AttendingDoctor != null ? string.Join(Configuration.FieldRepeatSeparator, AttendingDoctor.Select(x => x.ToDelimitedString())) : null,
                       ReferringDoctor != null ? string.Join(Configuration.FieldRepeatSeparator, ReferringDoctor.Select(x => x.ToDelimitedString())) : null,
                       ConsultingDoctor != null ? string.Join(Configuration.FieldRepeatSeparator, ConsultingDoctor.Select(x => x.ToDelimitedString())) : null,
                       HospitalService?.ToDelimitedString(),
                       TemporaryLocation?.ToDelimitedString(),
                       PreadmitTestIndicator?.ToDelimitedString(),
                       ReadmissionIndicator?.ToDelimitedString(),
                       AdmitSource?.ToDelimitedString(),
                       AmbulatoryStatus != null ? string.Join(Configuration.FieldRepeatSeparator, AmbulatoryStatus.Select(x => x.ToDelimitedString())) : null,
                       VipIndicator?.ToDelimitedString(),
                       AdmittingDoctor != null ? string.Join(Configuration.FieldRepeatSeparator, AdmittingDoctor.Select(x => x.ToDelimitedString())) : null,
                       PatientType?.ToDelimitedString(),
                       VisitNumber?.ToDelimitedString(),
                       FinancialClass != null ? string.Join(Configuration.FieldRepeatSeparator, FinancialClass.Select(x => x.ToDelimitedString())) : null,
                       ChargePriceIndicator?.ToDelimitedString(),
                       CourtesyCode?.ToDelimitedString(),
                       CreditRating?.ToDelimitedString(),
                       ContractCode != null ? string.Join(Configuration.FieldRepeatSeparator, ContractCode.Select(x => x.ToDelimitedString())) : null,
                       ContractEffectiveDate != null ? string.Join(Configuration.FieldRepeatSeparator, ContractEffectiveDate.Select(x => x.ToString(Consts.DateFormatPrecisionDay, culture))) : null,
                       ContractAmount != null ? string.Join(Configuration.FieldRepeatSeparator, ContractAmount.Select(x => x.ToString(Consts.NumericFormat, culture))) : null,
                       ContractPeriod != null ? string.Join(Configuration.FieldRepeatSeparator, ContractPeriod.Select(x => x.ToString(Consts.NumericFormat, culture))) : null,
                       InterestCode?.ToDelimitedString(),
                       TransferToBadDebtCode?.ToDelimitedString(),
                       TransferToBadDebtDate.HasValue ? TransferToBadDebtDate.Value.ToString(Consts.DateFormatPrecisionDay, culture) : null,
                       BadDebtAgencyCode?.ToDelimitedString(),
                       BadDebtTransferAmount.HasValue ? BadDebtTransferAmount.Value.ToString(Consts.NumericFormat, culture) : null,
                       BadDebtRecoveryAmount.HasValue ? BadDebtRecoveryAmount.Value.ToString(Consts.NumericFormat, culture) : null,
                       DeleteAccountIndicator?.ToDelimitedString(),
                       DeleteAccountDate.HasValue ? DeleteAccountDate.Value.ToString(Consts.DateFormatPrecisionDay, culture) : null,
                       DischargeDisposition?.ToDelimitedString(),
                       DischargedToLocation?.ToDelimitedString(),
                       DietType?.ToDelimitedString(),
                       ServicingFacility?.ToDelimitedString(),
                       BedStatus?.ToDelimitedString(),
                       AccountStatus?.ToDelimitedString(),
                       PendingLocation?.ToDelimitedString(),
                       PriorTemporaryLocation?.ToDelimitedString(),
                       AdmitDateTime.HasValue ? AdmitDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       DischargeDateTime.HasValue ? DischargeDateTime.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null,
                       CurrentPatientBalance.HasValue ? CurrentPatientBalance.Value.ToString(Consts.NumericFormat, culture) : null,
                       TotalCharges.HasValue ? TotalCharges.Value.ToString(Consts.NumericFormat, culture) : null,
                       TotalAdjustments.HasValue ? TotalAdjustments.Value.ToString(Consts.NumericFormat, culture) : null,
                       TotalPayments.HasValue ? TotalPayments.Value.ToString(Consts.NumericFormat, culture) : null,
                       AlternateVisitId != null ? string.Join(Configuration.FieldRepeatSeparator, AlternateVisitId.Select(x => x.ToDelimitedString())) : null,
                       VisitIndicator?.ToDelimitedString(),
                       OtherHealthcareProvider?.ToDelimitedString(),
                       ServiceEpisodeDescription,
                       ServiceEpisodeIdentifier?.ToDelimitedString()
                       ).TrimEnd(Configuration.FieldSeparator.ToCharArray()));
        }
예제 #32
0
        /// <summary>
        /// Value the deal.
        /// </summary>
        public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes)
        {
            PreValue(factors);

            CallableBondForward deal = (CallableBondForward)Deal;

            double baseDate       = factors.BaseDate;
            double settlementDate = deal.Settlement_Date;
            double tSettle        = CalcUtils.DaysToYears(settlementDate - baseDate);

            TimeGridIterator tgi = new TimeGridIterator(fT);

            PVProfiles      result  = valuationResults.Profile;
            AccruedInterest accrued = valuationResults.Results <AccruedInterest>();

            var intraValuationDiagnosticsWriter =
                IntraValuationDiagnosticsWriterFactory.GetOrCreate(IntraValuationDiagnosticsLevel.None);

            using (var outerCache = Vector.Cache(factors.NumScenarios))
            {
                // SwapOptionPricerObject is null when there are no valid exercise dates.
                SwaptionPricer.WorkingArrays arrays = fSwaptionPricer != null?fSwaptionPricer.PreValue(fDiscountRate, outerCache) : null;

                Vector tExercise = outerCache.Get(double.PositiveInfinity);                    // time of exercise
                int    numberScenariosExercised = 0;

                Vector defaultDate = fCreditRating != null?outerCache.Get(CalcUtils.DateTimeMaxValueAsDouble) : null;

                var defaultedBeforeBaseDate = fNeedsCreditRating &&
                                              CreditRating.DefaultedBeforeBaseDate(fCreditRating, baseDate);

                VectorEngine.For(tgi, () =>
                {
                    using (var cache = Vector.Cache(factors.NumScenarios))
                    {
                        Vector cash = cache.GetClear();
                        Vector pv   = cache.GetClear();

                        if (defaultedBeforeBaseDate || numberScenariosExercised == factors.NumScenarios)
                        {
                            // already defaulted before base date or All scenarios exercised
                            result.AppendVector(tgi.Date, pv);
                            return(LoopAction.Break);
                        }
                        else
                        {
                            // Value of the bond cashflows after the settlement.
                            fCashflowList.Value(pv, cash, null, baseDate, tgi.Date, null, fDiscountRate, fSurvivalProb, null,
                                                null, intraValuationDiagnosticsWriter, 0.0);

                            // Add the value of the principal and amortization cashflows.
                            fFixedCashflowList.Value(pv, cash, baseDate, tgi.Date, null, fDiscountRate, fSurvivalProb,
                                                     intraValuationDiagnosticsWriter, 0.0);

                            if (fSurvivalProb != null)
                            {
                                fRecoveryList.Value(pv, baseDate, tgi.Date, fDiscountRate, fSurvivalProb,
                                                    intraValuationDiagnosticsWriter);
                            }

                            if (fNeedsCreditRating)
                            {
                                UpdateDefaultDate(fCreditRating, tgi.Date, tgi.T, defaultDate);
                            }

                            // Add/subtract value of option
                            if (fSwaptionPricer != null)
                            {
                                using (var innerCache = Vector.Cache(factors.NumScenarios))
                                {
                                    Vector optionPv       = innerCache.Get();
                                    Vector exerciseStrike = innerCache.GetClear();    // strike of underlying at exercise
                                    Vector exerciseFee    = innerCache.GetClear();    // fee paid on exercise
                                    fSwaptionPricer.Value(optionPv, tgi.T, fDiscountRate, fInterestYieldVol, fSurvivalProb, arrays, tExercise,
                                                          exerciseStrike, exerciseFee, Early_Exercise_Today == YesNo.Yes, ref numberScenariosExercised);

                                    // Ignore optionality if in default.
                                    if (fNeedsCreditRating)
                                    {
                                        optionPv.AssignConditional(defaultDate > tgi.Date, optionPv, 0.0);
                                    }

                                    pv.Add(optionPv);
                                }
                            }

                            if (tgi.Date < settlementDate)
                            {
                                // Forward deal before settlement date
                                if (deal.Is_Defaultable == YesNo.No)
                                {
                                    pv.Assign((pv / fDiscountRate.Get(tgi.T, tSettle) - fSettlementAmount) * fRepoRate.Get(tgi.T, tSettle));
                                }
                                else
                                {
                                    pv.Subtract((fSettlementAmount - fAccrued) * fRepoRate.Get(tgi.T, tSettle) + fAccrued * fDiscountRate.Get(tgi.T, tSettle));   // discount accrued with bond rate; accrued interest must cancel
                                }
                            }
                            else if (tgi.Date == settlementDate)
                            {
                                // Forward deal at settlement date
                                pv.Subtract(fSettlementAmount);
                                cash.Subtract(fSettlementAmount);
                            }

                            if (deal.IsForward())
                            {
                                // Cash settled forward
                                if (tgi.Date == settlementDate)
                                {
                                    cash.Assign(pv);
                                }
                                else
                                {
                                    cash.Clear();
                                }
                            }
                            else if (tgi.Date >= settlementDate)
                            {
                                using (var innerCache = Vector.Cache(factors.NumScenarios))
                                {
                                    Vector afterExercise  = innerCache.Get(tExercise < tgi.T);
                                    Vector beforeExercise = innerCache.Get(tExercise > tgi.T);

                                    Vector exercisedToday = innerCache.GetClear();
                                    exercisedToday.Assign(afterExercise.Or(beforeExercise));
                                    exercisedToday.Assign(!exercisedToday);

                                    double callAmount = deal.Notional * Percentage.PercentagePoint * deal.Call_Prices.GetRate(tgi.Date);

                                    // Before exercise: pv is bondPV + optionPv and cash is bondCash.
                                    // On exercise: pv and cash are bondCash + callAmount.
                                    // After exercise: pv and cash are zero.
                                    cash.AssignConditional(exercisedToday, cash + callAmount, beforeExercise * cash);
                                    pv.AssignConditional(exercisedToday, cash, beforeExercise * pv);
                                }
                            }

                            // Apply leg sign to results
                            int buySellSign = deal.Buy_Sell == BuySell.Buy ? +1 : -1;
                            ApplySign(pv, cash, buySellSign);

                            if (fNeedsCreditRating)
                            {
                                Vector beforeExercise      = cache.Get(tExercise > tgi.T);
                                Vector modifiedDefaultDate = cache.Get();

                                // If default occurs after the call option has been exercise, default is irrelevant.
                                // If default occurs on the same date that the call option is exercised, the assumption
                                // is that the bond has been paid back in full, otherwise it wouldn''t be considered exercised.
                                modifiedDefaultDate.AssignConditional(beforeExercise, defaultDate, double.PositiveInfinity);
                                GetDefaultValue(baseDate, tgi.Date, modifiedDefaultDate, fRecoveryRate, pv, cash);
                            }

                            valuationResults.Cash.Accumulate(fFxRate, tgi.Date, cash);
                            result.AppendVector(tgi.Date, pv * fFxRate.Get(tgi.T));

                            if (accrued != null)
                            {
                                accrued.SetValue(tgi.Date, fCashflowList.CalculateAccrual(tgi.Date, accrued.AccrueFromToday, fDeal.GetHolidayCalendar()) * buySellSign);
                            }
                        }
                    }

                    return(LoopAction.Continue);
                });
            }

            result.Complete(fT);
        }
예제 #33
0
    /// <summary>
    /// Calculates the player's credit score.
    /// Used to apply bonuses/penalties to interest rates and maximum loans
    /// </summary>
    public static void calcCreditScore()
    {
        lastCreditScore = creditScore;
        int sharkPen   = 0;
        int oldestLoan = 0;

        foreach (Loan item in loanList)
        {
            if (item.age > oldestLoan)
            {
                oldestLoan = item.age;
            }
            if (item.type == LoanType.Payday)
            {
                sharkPen++;
            }
        }
        if (oldestLoan > 10)
        {
            creditScore -= scoreChangeFactor * (oldestLoan - 10);
        }
        creditScore -= sharkPen * scoreChangeFactor;
        if (totalLoans > 5)
        {
            creditScore -= scoreChangeFactor * 2;
        }
        if (totalDebt > 10000)
        {
            creditScore -= scoreChangeFactor * 8;
        }
        else if (totalDebt < 5000)
        {
            creditScore += scoreChangeFactor * 8;
        }
        creditScore += paymentStreak * scoreChangeFactor;
        if (averageIncome <= 0)
        {
            creditScore -= scoreChangeFactor * 10;
        }
        else if (averageIncome > totalDebt * 0.03)
        {
            creditScore += scoreChangeFactor * 15;
        }
        else
        {
            creditScore += scoreChangeFactor * 5;
        }

        // Excellent -------------
        if (creditScore > ExcellentCredit.max)
        {
            creditScore = ExcellentCredit.max;
        }
        if (creditScore >= ExcellentCredit.min && creditScore <= ExcellentCredit.max)
        {
            currentRating = ExcellentCredit;
            // Good ------------------
        }
        else if (creditScore >= GoodCredit.min && creditScore < GoodCredit.max)
        {
            currentRating = GoodCredit;
            // Fair ------------------
        }
        else if (creditScore >= FairCredit.min && creditScore < FairCredit.max)
        {
            currentRating = FairCredit;
            // Poor ------------------
        }
        else if (creditScore < PoorCredit.max && creditScore >= PoorCredit.min)
        {
            currentRating = PoorCredit;
            // WTF are you doing? ----
        }
        else if (creditScore < AbysmalCredit.max)
        {
            currentRating = AbysmalCredit;
        }
        if (creditScore < AbysmalCredit.min)
        {
            creditScore = AbysmalCredit.min;
        }

        rateAdjuster    = DefaultState.rateAdjuster * currentRating.rateModifier;
        maxLoanAdjuster = DefaultState.maxLoanAdjuster * currentRating.loanModifier;
        creditScore     = Mathf.Round(creditScore);
        Debug.Log($"Credit score for day {timesEntered}: {creditScore}, delta: {creditScore-lastCreditScore}");
        if (creditBarScript == null)
        {
            creditBarScript = GameObject.FindObjectOfType <CreditRating>();
            Debug.Log("it was nul");
        }
        creditBarScript.updateRatingBar();
    }
예제 #34
0
 //DeepCopy
 public void DeepCopy(CustomerOrder from)
 {
     CustomerID = from.CustomerID ;
     Rating = from.Rating ;
     AddressInfo.DeepCopy(from.AddressInfo) ;
     Orders.AddRange(from.Orders) ;
 }