Example #1
0
        public static async Task Execute
        (
            CreateLoanAgreementInfo model,
            ILoanAgreementAggregateRepository loanAgreementRepo,
            IFinancierAggregateRepository financierRepo,
            IUnitOfWork unitOfWork
        )
        {
            if (await loanAgreementRepo.Exists(model.Id))
            {
                throw new InvalidOperationException($"This loan agreement already exists!");
            }

            string    errMsg    = $"Unable to create loan agreement info, a financier with id {model.FinancierId} could not be found!";
            Financier financier = await financierRepo.GetByIdAsync(model.FinancierId) ?? throw new InvalidOperationException(errMsg);

            LoanAgreement loanAgreement = new LoanAgreement
                                          (
                new EconomicEvent(model.Id, EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(financier.Id),
                LoanAmount.Create(model.LoanAmount),
                InterestRate.Create(model.InterestRate),
                LoanDate.Create(model.LoanDate),
                MaturityDate.Create(model.MaturityDate),
                PaymentsPerYear.Create(model.PaymentsPerYear),
                model.UserId
                                          );

            await loanAgreementRepo.AddAsync(loanAgreement);

            await unitOfWork.Commit();
        }
Example #2
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (LodgementDate != null)
         {
             hashCode = hashCode * 59 + LodgementDate.GetHashCode();
         }
         if (MaturityDate != null)
         {
             hashCode = hashCode * 59 + MaturityDate.GetHashCode();
         }
         if (MaturityAmount != null)
         {
             hashCode = hashCode * 59 + MaturityAmount.GetHashCode();
         }
         if (MaturityCurrency != null)
         {
             hashCode = hashCode * 59 + MaturityCurrency.GetHashCode();
         }
         if (MaturityInstructions != null)
         {
             hashCode = hashCode * 59 + MaturityInstructions.GetHashCode();
         }
         return(hashCode);
     }
 }
Example #3
0
        public async Task ShouldInsert_LoanAgreementAndLoanPymt_UsingLoanAgreementAggregate()
        {
            LoanAgreement agreement = new LoanAgreement
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(new Guid("b49471a0-5c1e-4a4d-97e7-288fb0f6338a")),
                LoanAmount.Create(175000),
                InterestRate.Create(.0675),
                LoanDate.Create(new DateTime(2021, 11, 5)),
                MaturityDate.Create(new DateTime(2022, 11, 5)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            LoanPayment loanPayment = new LoanPayment
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashDisbursementForLoanPayment),
                agreement,
                PaymentNumber.Create(1),
                PaymentDueDate.Create(new DateTime(2021, 12, 5)),
                LoanPrincipalAmount.Create(14135),
                LoanInterestAmount.Create(984),
                LoanPrincipalRemaining.Create(160862),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            agreement.AddLoanPayment(loanPayment);
            await _loanAgreementRepo.AddAsync(agreement);

            await _unitOfWork.Commit();

            var result = await _loanAgreementRepo.Exists(agreement.Id);

            Assert.True(result);    //TODO Test navigation to LoanPayment
        }
Example #4
0
        private SortedDictionary <double, double> GetCashflows(DateTime evaluationDate)
        {
            SortedDictionary <double, double> cashflows = new SortedDictionary <double, double>();
            double yearFrac;

            if (IsForward)
            {
                DateTime prevCashflowDate = IssueDate;
                DateTime cashflowDate     = IssueDate.AddMonths(CouponGapMonth());
                while (cashflowDate < MaturityDate)
                {
                    yearFrac = (cashflowDate - evaluationDate).TotalDays / 365;
                    if (yearFrac > 0)
                    {
                        cashflows.Add(yearFrac, CouponRate * (cashflowDate - prevCashflowDate).TotalDays / 365);
                    }
                    prevCashflowDate = cashflowDate;
                    cashflowDate     = cashflowDate.AddMonths(CouponGapMonth());
                }

                yearFrac = (MaturityDate - evaluationDate).TotalDays / 365;
                if (yearFrac > 0)
                {
                    cashflows.Add((MaturityDate - evaluationDate).TotalDays / 365, CouponRate * (MaturityDate - prevCashflowDate).TotalDays / 365);
                }
            }
            else
            {
                DateTime prevCashflowDate = MaturityDate.AddMonths(-CouponGapMonth());
                DateTime cashflowDate     = MaturityDate;
                while (prevCashflowDate > IssueDate)
                {
                    yearFrac = (cashflowDate - evaluationDate).TotalDays / 365;
                    if (yearFrac > 0)
                    {
                        cashflows.Add(yearFrac, CouponRate * (cashflowDate - prevCashflowDate).TotalDays / 365);
                    }
                    cashflowDate     = prevCashflowDate;
                    prevCashflowDate = prevCashflowDate.AddMonths(-CouponGapMonth());
                }

                yearFrac = (IssueDate - evaluationDate).TotalDays / 365;
                if (yearFrac > 0)
                {
                    cashflows.Add((IssueDate - evaluationDate).TotalDays / 365, CouponRate * (IssueDate - cashflowDate).TotalDays / 365);
                }
            }

            // Add principal
            if (cashflows.Count != 0)
            {
                double lastYearFrac = cashflows.Keys.Max();
                cashflows[lastYearFrac] += 1;
            }

            return(cashflows);
        }
        public void ShouldReturn_NewLoanAgreement()
        {
            var       economicEvent = new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement);
            Financier financier     = GetFinancier();

            LoanAgreement agreement = new LoanAgreement
                                      (
                economicEvent,
                FinancierId.Create(financier.Id),
                LoanAmount.Create(10000),
                InterestRate.Create(.006),
                LoanDate.Create(new DateTime(2020, 12, 31)),
                MaturityDate.Create(new DateTime(2021, 12, 31)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            Assert.IsType <LoanAgreement>(agreement);
        }
Example #6
0
 public void Configure(EntityTypeBuilder <LoanAgreement> entity)
 {
     entity.ToTable("LoanAgreements", schema: "Finance");
     entity.HasKey(e => e.Id);
     entity.Property(p => p.Id).HasColumnType("UNIQUEIDENTIFIER").HasColumnName("LoanId");
     entity.HasOne(p => p.EconomicEvent).WithOne().HasForeignKey <LoanAgreement>(p => p.Id);
     entity.Property(p => p.FinancierId).HasColumnType("UNIQUEIDENTIFIER").HasColumnName("FinancierId");
     entity.Property(p => p.LoanAmount)
     .HasConversion(p => p.Value, p => LoanAmount.Create(p))
     .HasColumnType("DECIMAL(18,2)")
     .HasColumnName("LoanAmount")
     .IsRequired();
     entity.Property(p => p.InterestRate)
     .HasConversion(p => p.Value, p => InterestRate.Create(p))
     .HasColumnType("NUMERIC(9,6)")
     .HasColumnName("InterestRate")
     .IsRequired();
     entity.Property(p => p.LoanDate)
     .HasConversion(p => p.Value, p => LoanDate.Create(p))
     .HasColumnType("DATETIME2(0)")
     .HasColumnName("LoanDate")
     .IsRequired();
     entity.Property(p => p.MaturityDate)
     .HasConversion(p => p.Value, p => MaturityDate.Create(p))
     .HasColumnType("DATETIME2(0)")
     .HasColumnName("MaturityDate")
     .IsRequired();
     entity.Property(p => p.PaymentsPerYear)
     .HasConversion(p => p.Value, p => PaymentsPerYear.Create(p))
     .HasColumnType("INT")
     .HasColumnName("PymtsPerYear")
     .IsRequired();
     entity.Property(p => p.UserId)
     .HasConversion(p => p.Value, p => UserId.Create(p))
     .HasColumnType("UNIQUEIDENTIFIER")
     .HasColumnName("UserId")
     .IsRequired();
     entity.Property(e => e.CreatedDate)
     .HasColumnType("datetime2(7)")
     .ValueGeneratedOnAdd()
     .HasDefaultValueSql("sysdatetime()");
     entity.Property(e => e.LastModifiedDate).HasColumnType("datetime2(7)");
 }
Example #7
0
        public static async Task Execute
        (
            EditLoanAgreementInfo model,
            ILoanAgreementAggregateRepository loanAgreementRepo,
            IUnitOfWork unitOfWork
        )
        {
            string        errMsg        = $"Unable to locate loan agreement with LoanId '{model.Id}'!";
            LoanAgreement loanAgreement = await loanAgreementRepo.GetByIdAsync(model.Id) ?? throw new InvalidOperationException(errMsg);

            loanAgreement.UpdateLoanAmount(LoanAmount.Create(model.LoanAmount));
            loanAgreement.UpdateInterestRate(InterestRate.Create(model.InterestRate));
            loanAgreement.UpdateLoanDate(LoanDate.Create(model.LoanDate));
            loanAgreement.UpdateMaturityDate(MaturityDate.Create(model.MaturityDate));
            loanAgreement.UpdatePaymentsPerYear(PaymentsPerYear.Create(model.PaymentsPerYear));
            loanAgreement.UpdateUserId(model.UserId);
            loanAgreement.UpdateLastModifiedDate();

            await unitOfWork.Commit();
        }
        public void ShouldRaiseError_DefaultLoanDate()
        {
            var       economicEvent = new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement);
            Financier financier     = GetFinancier();

            Assert.Throws <ArgumentNullException>(() =>
            {
                new LoanAgreement
                (
                    economicEvent,
                    FinancierId.Create(financier.Id),
                    LoanAmount.Create(10000),
                    InterestRate.Create(.006),
                    LoanDate.Create(new DateTime()),
                    MaturityDate.Create(new DateTime(2021, 12, 31)),
                    PaymentsPerYear.Create(12),
                    UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                );
            });
        }
Example #9
0
        public async Task ShouldInsert_LoanAgreement_UsingLoanAgreementRepo()
        {
            LoanAgreement agreement = new LoanAgreement
                                      (
                new EconomicEvent(Guid.NewGuid(), EventType.CashReceiptFromLoanAgreement),
                FinancierId.Create(new Guid("b49471a0-5c1e-4a4d-97e7-288fb0f6338a")),
                LoanAmount.Create(175000),
                InterestRate.Create(.0675),
                LoanDate.Create(new DateTime(2021, 11, 5)),
                MaturityDate.Create(new DateTime(2022, 11, 5)),
                PaymentsPerYear.Create(12),
                UserId.Create(new Guid("660bb318-649e-470d-9d2b-693bfb0b2744"))
                                      );

            await _loanAgreementRepo.AddAsync(agreement);

            await _unitOfWork.Commit();

            var result = await _loanAgreementRepo.Exists(agreement.Id);

            Assert.True(result);
        }
Example #10
0
        /// <summary>
        /// Returns true if BankingTermDepositAccount instances are equal
        /// </summary>
        /// <param name="other">Instance of BankingTermDepositAccount to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(BankingTermDepositAccount other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     LodgementDate == other.LodgementDate ||
                     LodgementDate != null &&
                     LodgementDate.Equals(other.LodgementDate)
                     ) &&
                 (
                     MaturityDate == other.MaturityDate ||
                     MaturityDate != null &&
                     MaturityDate.Equals(other.MaturityDate)
                 ) &&
                 (
                     MaturityAmount == other.MaturityAmount ||
                     MaturityAmount != null &&
                     MaturityAmount.Equals(other.MaturityAmount)
                 ) &&
                 (
                     MaturityCurrency == other.MaturityCurrency ||
                     MaturityCurrency != null &&
                     MaturityCurrency.Equals(other.MaturityCurrency)
                 ) &&
                 (
                     MaturityInstructions == other.MaturityInstructions ||
                     MaturityInstructions != null &&
                     MaturityInstructions.Equals(other.MaturityInstructions)
                 ));
        }
Example #11
0
        public string GenerateExplanation()
        {
            var explanationBuilder = new System.Text.StringBuilder();

            explanationBuilder.Append(string.Format("{0} payable within {1} {2} payment{3}", AccountTitle,
                                                    LoanTerms, ModeOfPayment,
                                                    LoanTerms > 1 ? "s" : ""));

            explanationBuilder.AppendLine(string.Format(" due date on {0}", MaturityDate.ToLongDateString()));

            if (CoMakers.Any())
            {
                var comakers = from comaker in CoMakers
                               where !string.IsNullOrEmpty(comaker.MemberCode)
                               select comaker;
                if (comakers.Any())
                {
                    explanationBuilder.AppendLine(string.Format("Co-makers: {0}", string.Join(", ", comakers)));
                }
            }

            return(explanationBuilder.ToString());
        }
 public string ToCsv()
 {
     return($"F,{Symbol},{ExchangeId},{PE.ToInvariantString()},{AverageVolume.ToInvariantString()},{FiftyTwoWeekHigh.ToInvariantString()}," +
            $"{FiftyTwoWeekLow.ToInvariantString()},{CalendarYearHigh.ToInvariantString()},{CalendarYearLow.ToInvariantString()},{DividendYield.ToInvariantString()}," +
            $"{DividendAmount.ToInvariantString()},{DividendRate.ToInvariantString()},{PayDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{ExDividendDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{CurrentYearEarningsPerShare.ToInvariantString()},{NextYearEarningsPerShare.ToInvariantString()},{FiveYearGrowthPercentage.ToInvariantString()}," +
            $"{FiscalYearEnd.ToInvariantString()},{CompanyName},{RootOptionSymbol},{PercentHeldByInstitutions.ToInvariantString()}," +
            $"{Beta.ToInvariantString()},{Leaps},{CurrentAssets.ToInvariantString()},{CurrentLiabilities.ToInvariantString()}," +
            $"{BalanceSheetDate.ToInvariantString(FundamentalDateTimeFormat)},{LongTermDebt.ToInvariantString()},{CommonSharesOutstanding.ToInvariantString()}," +
            $"{SplitFactor1},{SplitFactor2},{FormatCode},{Precision.ToInvariantString()},{SIC.ToInvariantString()}," +
            $"{HistoricalVolatility.ToInvariantString()},{SecurityType},{ListedMarket},{FiftyTwoWeekHighDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{FiftyTwoWeekLowDate.ToInvariantString(FundamentalDateTimeFormat)},{CalendarYearHighDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{CalendarYearLowDate.ToInvariantString(FundamentalDateTimeFormat)},{YearEndClose.ToInvariantString()},{MaturityDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{CouponRate.ToInvariantString()},{ExpirationDate.ToInvariantString(FundamentalDateTimeFormat)},{StrikePrice.ToInvariantString()}," +
            $"{NAICS.ToInvariantString()},{ExchangeRoot},{OptionsPremiumMultiplier.ToInvariantString()},{OptionsMultipleDeliverables.ToInvariantString()}," +
            $"{SessionOpenTime.ToInvariantString(FundamentalTimeSpanFormat)},{SessionCloseTime.ToInvariantString(FundamentalTimeSpanFormat)}," +
            $"{BaseCurrency},{ContractSize},{ContractMonths},{MinimumTickSize.ToInvariantString()},{FirstDeliveryDate.ToInvariantString(FundamentalDateTimeFormat)}," +
            $"{FIGI},{SecuritySubType.ToInvariantString()}");
 }
Example #13
0
 public override string ToString()
 {
     return(Isin + " (" + Currency + "|" + IssueDate.ToString(SHORT_DATE_FORMAT) + "|" + MaturityDate.ToString(SHORT_DATE_FORMAT) + "|" + Coupon + "|" + UnitSize + ")");
 }
Example #14
0
        /// <summary>
        /// Gera um subset XML completo com as informacoes deste
        /// </summary>
        /// <returns></returns>
        public string ToXML()
        {
            string response = "";
            string xml      = "<trade>";

            xml += "<trade-date>" + TradeDate.ToString("yyyy-MM-dd") + "</trade-date>";
            xml += "<trade-id>" + TradeID + "</trade-id>";

            if ((DMASource != null && DMASource.Length > 0) &&
                (DMATrade != null && DMATrade.Length > 0) &&
                (DMATradeID != null && DMATradeID.Length > 0))
            {
                xml += "<dma>";
                xml += "<dma-source>" + DMASource + "</dma-source>";
                xml += "<dma-trader>" + DMATrade + "</dma-trader>";
                xml += "<dma-trade-id>" + DMATradeID + "</dma-trade-id>";
                xml += "</dma>";
            }
            //else
            //    xml += "<dma/>";

            xml += "<record-type>" + RecordType + "</record-type>";
            xml += "<product-id>" + ProductID + "</product-id>";
            xml += "<market-id>" + MarketID + "</market-id>";
            xml += "<serie>" + Serie + "</serie>";
            xml += "<maturity-date>" + MaturityDate.ToString("yyyy-MM-dd") + "</maturity-date>";
            xml += "<hedge-long-maturity>" + HedgeLongMaturity.ToString("yyyy-MM-dd") + "</hedge-long-maturity>";
            xml += "<trade-timestamp>" + TradeTimestamp.ToString("yyyy-MM-ddTHH:mm:ss") + "</trade-timestamp>";
            //xml += "<trade-timestamp>" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + "</trade-timestamp>";
            xml += "<negotiation-channel>" + NegotiationChannel + "</negotiation-channel>";
            xml += "<after-hours>" + AfterHours.ToString().ToLowerInvariant() + "</after-hours>";
            xml += "<orientation>" + Orientation + "</orientation>";
            xml += "<number-of-contracts>" + NumberOfContracts + "</number-of-contracts>";
            xml += "<price>" + Price.ToString(ciEn) + "</price>";

            if (OptionType != null && OptionType.Length > 0)
            {
                xml += "<option-type>" + OptionType + "</option-type>";
            }

            if (ValReference1 != 0)
            {
                xml += "<val-reference-1>" + ValReference1 + "</val-reference-1>";
            }

            if (ValReference2 != 0)
            {
                xml += "<val-reference-2>" + ValReference2 + "</val-reference-2>";
            }

            if (ValDelta != 0)
            {
                xml += "<val-delta>" + ValDelta + "</val-delta>";
            }

            response += xml;

            if (TradeDetails.Count > 0)
            {
                xml = "<additional-details>";
                foreach (TradeDetail detail in TradeDetails)
                {
                    xml += detail.ToXML();
                }
                xml += "</additional-details>";
            }
            else
            {
                xml = "<additional-details/>";
            }

            response += xml;

            xml  = "<buyer>";
            xml += "<buyer-code>{0}</buyer-code>";
            xml += "<buyer-name>{1}</buyer-name>";
            xml += "</buyer>";

            xml += "<broker>";
            xml += "<broker-code>{2}</broker-code>";
            xml += "<broker-name>{3}</broker-name>";
            xml += "</broker>";

            xml += "<seller>";
            xml += "<seller-code>{4}</seller-code>";
            xml += "<seller-name>{5}</seller-name>";
            xml += "</seller>";

            xml += "<trader>";
            xml += "<trader-code>{6}</trader-code>";
            xml += "<trader-name>{7}</trader-name>";
            xml += "</trader>";

            response += string.Format(xml,
                                      BuyerCode,
                                      BuyerName,
                                      BrokerCode,
                                      BrokerName,
                                      SellerCode,
                                      SellerName,
                                      TraderCode,
                                      TraderName);

            response += "</trade>";

            return(response);
        }