public double FullPriceFromYield(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double yield, TradingMarket tradeingMarket, bool irregularPayment = false) { var remainingCfs = cashflows.Where(x => x.PaymentDate > valueDate).ToList(); if (!remainingCfs.Any()) { return(0.0); } var lastCouponPeriod = cashflows.Where(x => x.PaymentDate >= valueDate).ToList().Count == 1; if (tradeingMarket.Equals(TradingMarket.ChinaInterBank)) { if (lastCouponPeriod) { dayCount = new ModifiedAfb(); } } //if (remainingCfs.Count == 1) //{ // var cf = remainingCfs.Single(); // if (cf.PaymentDate <= new Term("1Y").Next(valueDate)) // { // return cf.PaymentAmount / (1.0 + yield * dayCount.CalcDayCountFraction(valueDate, cf.PaymentDate, cf.RefStartDate, cf.RefEndDate)); // } // else // { // return cf.PaymentAmount / Math.Pow(1.0 + yield, dayCount.CalcDayCountFraction(valueDate, cf.PaymentDate, cf.RefStartDate, cf.RefEndDate)); // } //} var npv = 0.0; var df = 1.0; var freq = frequency.CountPerYear(); foreach (var remainingCf in remainingCfs) { var dt = dayCount.CalcDayCountFraction(valueDate, remainingCf.PaymentDate, remainingCf.RefStartDate, remainingCf.RefEndDate); if (lastCouponPeriod) { df *= 1.0 / (1.0 + yield * dt); } else { df *= 1.0 / Math.Pow(1 + yield / freq, freq * dt); } npv += remainingCf.PaymentAmount * df; valueDate = remainingCf.PaymentDate; } return(npv); }
public double YieldFromFullPrice(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double fullPrice, TradingMarket tradingMarket, bool irregularPayment = false) { var remainingCfs = cashflows.Where(x => x.PaymentDate > valueDate).ToList(); if (!remainingCfs.Any()) { return(0.0); } try { var left = -0.999999; if (remainingCfs.Count == 1) { if (tradingMarket.Equals(TradingMarket.ChinaInterBank)) { dayCount = new ModifiedAfb(); } var timeToMaturity = dayCount.CalcDayCountFraction(valueDate, cashflows.Last().PaymentDate, remainingCfs.First().RefStartDate, remainingCfs.First().RefEndDate); left = -1.0 / timeToMaturity + 1e-6; } else { left = -1.0 * frequency.CountPerYear() + 1e-6; } var fcn = new SolveYtm(cashflows, dayCount, frequency, startDate, valueDate, fullPrice, tradingMarket, irregularPayment, this); //adjust left to avoid NaN var fLeft = fcn.F(left); var delta = 0.01; while (double.IsNaN(fLeft)) { var temp = fcn.F(left + delta); if (temp < 0.0) { break; } fLeft = temp; left += delta; } return(BrentZero.Solve(fcn, left, 1000000, 1e-12)); } catch (Exception ex) { throw new PricingBaseException("Bond yield does not converge " + ex.GetDetail()); } }
public SolveYtm(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double fullPrice, TradingMarket tradeingMarket, bool irregularPayment, IBondYieldPricer bondYieldPricer = null) { _cashflows = cashflows; _dayCount = dayCount; _frequency = frequency; _startDate = startDate; _valueDate = valueDate; _fullPrice = fullPrice; _tradeingMarket = tradeingMarket; _irregularPayment = irregularPayment; _bondYieldPricer = bondYieldPricer ?? new BondYieldPricer(); }
public double GetMacDuration(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double yield, TradingMarket tradingMarket) { var remainingCfs = cashflows.Where(x => x.PaymentDate > valueDate).ToList(); if (!remainingCfs.Any()) { return(0.0); } if (remainingCfs.Count == 1) { if (tradingMarket.Equals(TradingMarket.ChinaInterBank)) { dayCount = new ModifiedAfb(); } return(dayCount.CalcDayCountFraction(valueDate, remainingCfs[0].PaymentDate, remainingCfs.First().RefStartDate, remainingCfs.First().RefEndDate)); } var npv = 0.0; var timeWeightedNpv = 0.0; var df = 1.0; var freq = frequency.CountPerYear(); var totalT = 0.0; foreach (var remainingCf in remainingCfs) { var dt = dayCount.CalcDayCountFraction(valueDate, remainingCf.PaymentDate, remainingCf.RefStartDate, remainingCf.RefEndDate); df *= 1.0 / Math.Pow(1 + yield / freq, freq * dt); npv += remainingCf.PaymentAmount * df; totalT += dt; timeWeightedNpv += remainingCf.PaymentAmount * df * totalT; valueDate = remainingCf.PaymentDate; } return(timeWeightedNpv / npv); }
public static double GetModifiedDuration(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double yield, TradingMarket tradeingMarket, bool irregularPayment = false, IBondYieldPricer bondYieldPricer = null) { const double dy = 1e-4; if (bondYieldPricer == null) { bondYieldPricer = new BondYieldPricer(); } var priceUp = bondYieldPricer.FullPriceFromYield(cashflows, dayCount, frequency, startDate, valueDate, yield - dy, tradeingMarket, irregularPayment); var priceDown = bondYieldPricer.FullPriceFromYield(cashflows, dayCount, frequency, startDate, valueDate, yield + dy, tradeingMarket, irregularPayment); return((priceUp - priceDown) / dy / (priceDown + priceUp)); }
public double YieldFromFullPrice(Cashflow[] cashflows, IDayCount dayCount, Frequency frequency, Date startDate, Date valueDate, double fullPrice, TradingMarket tradingMarket, bool irregularPayment = false) { var remainingCfs = cashflows.Where(x => x.PaymentDate > valueDate).ToList(); if (!remainingCfs.Any()) { return(0.0); } try { var left = -0.999999; if (remainingCfs.Count == 1) { if (tradingMarket.Equals(TradingMarket.ChinaInterBank)) { dayCount = new ModifiedAfb(); } var timeToMaturity = dayCount.CalcDayCountFraction(valueDate, cashflows.Last().PaymentDate, remainingCfs.First().RefStartDate, remainingCfs.First().RefEndDate); left = -1.0 / timeToMaturity + double.Epsilon; } var fcn = new SolveYtm(cashflows, dayCount, frequency, startDate, valueDate, fullPrice, tradingMarket, irregularPayment, this); return(BrentZero.Solve(fcn, left, 1000000, 1e-12)); } catch (Exception ex) { throw new PricingBaseException("Bond yield does not converge " + ex.GetDetail()); } }
public async Task CrawlerDetail(HtmlDocument htmlDocument, String crawl, String detailAnchor) { //var listDetail = HttpContext.Session.GetObject<List<String>>(CT.DETAIL); var part = new List <String>(); if (part != null) { if (crawl != null) { foreach (var include in crawl.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { part.Add(include); } } //var url = detailAnchor; //using var httpClient = new HttpClient(); //var html = await httpClient.GetStringAsync(url); //var htmlDocument = new HtmlDocument(); //htmlDocument.LoadHtml(html); var playerProfile = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("playerprofile-itemblock")).FirstOrDefault(); //price var getImagePlayer = Url_image + playerProfile.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Contains("card-20-face-")) .FirstOrDefault() .Descendants("img") .FirstOrDefault() .Attributes["src"].Value; var getPlayer = unitOfWork.Player.GetFirstOrDefault(x => x.Face.Equals(getImagePlayer)); if (getPlayer.Nation == null) { getPlayer.Nation = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("playerprofile-hbar-ttl")).FirstOrDefault().Descendants("a").FirstOrDefault().InnerText; } if (playerProfile != null) { var priceObject = new TradingMarket(); var priceUpdate = playerProfile.Descendants("div").Where(node => node.GetAttributeValue("class", "") .Contains("priceupdate")) .ToList(); var xboxUpdate = priceUpdate[0].InnerText; var ps4Update = priceUpdate[1].InnerText; priceObject.Player = getPlayer.Id; priceObject.Xtime = xboxUpdate; priceObject.Ps4time = ps4Update; var priceProfile = playerProfile.Descendants("div").Where(node => node.GetAttributeValue("class", "") .Equals("playerprofile-price")) .ToList(); var xboxPrice = priceProfile[0].InnerText; var ps4Price = priceProfile[1].InnerText; priceObject.Xprice = Double.Parse(xboxPrice); priceObject.Ps4price = Double.Parse(ps4Price); unitOfWork.TradingMarket.Add(priceObject); } //skill var playerInfor = htmlDocument.DocumentNode.Descendants("p") .Where(node => node.GetAttributeValue("class", "") .Contains("ppdb-d")).ToList(); var skillPoint = playerInfor[0].InnerText; var weakFoot = playerInfor[1].InnerText; var age = playerInfor[2].InnerText; var height = playerInfor[3].InnerText; var weight = playerInfor[4].InnerText; var workrates = playerInfor[5].InnerText; var footed = playerInfor[6].InnerText; var player = getPlayer.Id; var skillObject = new SkillDetail() { Age = int.Parse(age), Player = player, Footed = footed, Height = height, Weight = weight, Skill = int.Parse(skillPoint), Weakfoot = int.Parse(weakFoot), Workrates = workrates }; unitOfWork.SkillDetail.Add(skillObject); //fight for the badge var badge = playerProfile.Descendants("div") .Where(node => node.GetAttributeValue("align", "") .Equals("center")).FirstOrDefault(); var yes = badge.Descendants("a").FirstOrDefault().InnerText; var no = badge.Descendants("a").Skip(1).Take(1).FirstOrDefault().InnerText; var getStats = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("col-2")).ToList(); //PacDetail var pacPoint = getStats[1].InnerText; var splitPacPoint = pacPoint.Replace("\n", ""); var getPacPointOnly = splitPacPoint.Where(x => char.IsDigit(x)).ToList(); var pacObject = new PacDetail(); // var item = getPacPointOnly[0].ToString(); pacObject.Pac = int.Parse(getPacPointOnly[0].ToString() + getPacPointOnly[1].ToString()); pacObject.Acc = int.Parse(getPacPointOnly[2].ToString() + getPacPointOnly[3].ToString()); pacObject.Speed = int.Parse(getPacPointOnly[4].ToString() + getPacPointOnly[5].ToString()); pacObject.Player = getPlayer.Id; unitOfWork.PacDetail.Add(pacObject); //ShoDetail var showPoint = getStats[2].InnerText; var splitShoPoint = showPoint.Replace("\n", ""); var getShoPointOnly = splitShoPoint.Where(x => char.IsDigit(x)).ToList(); var shoObject = new ShoDetail(); getShoPointOnly.RemoveRange(0, 2); shoObject.Pos = int.Parse(getShoPointOnly[0].ToString() + getShoPointOnly[1].ToString()); shoObject.Fin = int.Parse(getShoPointOnly[2].ToString() + getShoPointOnly[3].ToString()); shoObject.Sp = int.Parse(getShoPointOnly[4].ToString() + getShoPointOnly[5].ToString()); shoObject.Ls = int.Parse(getShoPointOnly[6].ToString() + getShoPointOnly[7].ToString()); shoObject.Volleys = int.Parse(getShoPointOnly[8].ToString() + getShoPointOnly[9].ToString()); shoObject.Pen = int.Parse(getShoPointOnly[10].ToString() + getShoPointOnly[11].ToString()); shoObject.Player = getPlayer.Id; unitOfWork.ShoDetail.Add(shoObject); //PasDetail var pasPoint = getStats[3].InnerText; var splitPasPoint = pasPoint.Replace("\n", ""); var getPasPointOnly = splitPasPoint.Where(x => char.IsDigit(x)).ToList(); var pasDetail = new PasDetail(); getPasPointOnly.RemoveRange(0, 2); pasDetail.Vision = int.Parse(getPasPointOnly[0].ToString() + getPasPointOnly[1].ToString()); pasDetail.Crossing = int.Parse(getPasPointOnly[2].ToString() + getPasPointOnly[3].ToString()); pasDetail.Fk = int.Parse(getPasPointOnly[4].ToString() + getPasPointOnly[5].ToString()); pasDetail.Sp = int.Parse(getPasPointOnly[6].ToString() + getPasPointOnly[7].ToString()); pasDetail.Lp = int.Parse(getPasPointOnly[8].ToString() + getPasPointOnly[9].ToString()); pasDetail.Curve = int.Parse(getPasPointOnly[10].ToString() + getPasPointOnly[11].ToString()); pasDetail.Player = getPlayer.Id; unitOfWork.PasDetail.Add(pasDetail); //PhyDetail var phyPoint = getStats[6].InnerText; var splitPhyPoint = phyPoint.Replace("\n", ""); var getPhyPointOnly = splitPhyPoint.Where(x => char.IsDigit(x)).ToList(); var phyDetail = new PhyDetail(); phyDetail.Jump = int.Parse(getPhyPointOnly[2].ToString() + getPhyPointOnly[3].ToString()); phyDetail.Stamina = int.Parse(getPhyPointOnly[4].ToString() + getPhyPointOnly[5].ToString()); phyDetail.Strength = int.Parse(getPhyPointOnly[6].ToString() + getPhyPointOnly[7].ToString()); phyDetail.Aggression = int.Parse(getPhyPointOnly[8].ToString() + getPhyPointOnly[9].ToString()); phyDetail.Player = getPlayer.Id; unitOfWork.PhyDetail.Add(phyDetail); //DefDetail var defPoint = getStats[5].InnerText; var splitDefPoint = defPoint.Replace("\n", ""); var getDefPointOnly = splitDefPoint.Where(x => char.IsDigit(x)).ToList(); var defDetail = new DefDetail(); getDefPointOnly.RemoveRange(0, 2); defDetail.Interception = int.Parse(getDefPointOnly[0].ToString() + getDefPointOnly[1].ToString()); defDetail.Ha = int.Parse(getDefPointOnly[2].ToString() + getDefPointOnly[3].ToString()); defDetail.Da = int.Parse(getDefPointOnly[4].ToString() + getDefPointOnly[5].ToString()); defDetail.Stand = int.Parse(getDefPointOnly[6].ToString() + getDefPointOnly[7].ToString()); defDetail.Slide = int.Parse(getDefPointOnly[8].ToString() + getDefPointOnly[9].ToString()); defDetail.Player = getPlayer.Id; unitOfWork.DefDetail.Add(defDetail); //DriDetail var driPoint = getStats[4].InnerText; var splitDriPoint = driPoint.Replace("\n", ""); var getDriPointOnly = splitDriPoint.Where(x => char.IsDigit(x)).ToList(); var driDetail = new DriDetail(); getDefPointOnly.RemoveRange(0, 2); driDetail.Agility = int.Parse(getDriPointOnly[0].ToString() + getDriPointOnly[1].ToString()); driDetail.Balance = int.Parse(getDriPointOnly[2].ToString() + getDriPointOnly[3].ToString()); driDetail.React = int.Parse(getDriPointOnly[4].ToString() + getDriPointOnly[5].ToString()); driDetail.Control = int.Parse(getDriPointOnly[6].ToString() + getDriPointOnly[7].ToString()); driDetail.Drib = int.Parse(getDriPointOnly[8].ToString() + getDriPointOnly[9].ToString()); driDetail.Composure = int.Parse(getDriPointOnly[10].ToString() + getDriPointOnly[11].ToString()); driDetail.Player = getPlayer.Id; unitOfWork.DriDetail.Add(driDetail); //Position var position = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("altpos-inner-l1")).ToList(); var positionPoint = htmlDocument.DocumentNode.Descendants("div") .Where(node => node.GetAttributeValue("class", "") .Equals("altpos-inner-l2")).ToList(); var positionObject = new Position(); positionObject.Cb = int.Parse(position[0].InnerText); positionObject.Cdm = int.Parse(position[1].InnerText); positionObject.Cm = int.Parse(position[2].InnerText); positionObject.Cam = int.Parse(position[3].InnerText); positionObject.Cf = int.Parse(position[4].InnerText); positionObject.St = int.Parse(position[5].InnerText); positionObject.Lw = int.Parse(position[6].InnerText); positionObject.Lf = int.Parse(position[7].InnerText); positionObject.Rf = int.Parse(position[8].InnerText); positionObject.Rw = int.Parse(position[9].InnerText); positionObject.Lm = int.Parse(position[10].InnerText); positionObject.Rm = int.Parse(position[11].InnerText); positionObject.Rb = int.Parse(position[12].InnerText); positionObject.Rwb = int.Parse(position[13].InnerText); positionObject.Lb = int.Parse(position[14].InnerText); positionObject.Lwb = int.Parse(position[15].InnerText); positionObject.Player = getPlayer.Id; unitOfWork.Position.Add(positionObject); unitOfWork.Save(); } }
/// <summary> /// 交易 /// </summary> /// <param name="action"> 動作(買/賣) </param> /// <param name="market"> 市場 (BTCUSDT, ETHUSDT, ETHBTC) </param> /// <returns></returns> public virtual (decimal balance, decimal CoinBalance1, decimal CoinBalance2) Trading(TradingAction action, TradingMarket market) { if (market == TradingMarket.Coin12Coin) { (Balance, CoinBalance1) = TradingAction(action, dataProvider.Current.Coin12CoinKline.Close, Balance, CoinBalance1); } if (market == TradingMarket.Coin22Coin) { (Balance, CoinBalance2) = TradingAction(action, dataProvider.Current.Coin22CoinKline.Close, Balance, CoinBalance2); } if (market == TradingMarket.Coin22Coin1) { (CoinBalance1, CoinBalance2) = TradingAction(action, dataProvider.Current.Coin22Coin1Kline.Close, CoinBalance1, CoinBalance2); } return(Balance, CoinBalance1, CoinBalance2); }
public Bond( string id, Date startDate, Date maturityDate, double notional, CurrencyCode currency, ICoupon coupon, ICalendar calendar, Frequency paymentFreq, Stub stub, IDayCount accrualDayCount, IDayCount paymentDayCount, BusinessDayConvention accrualBizDayRule, BusinessDayConvention paymentBizDayRule, DayGap settlementGap, TradingMarket bondTradingMarket, bool stickToEom = false, IRedemption redemption = null, Date firstPaymentDate = null, bool isZeroCouponBond = false, double issuePrice = double.NaN, double issueRate = double.NaN, AmortizationType amortionType = AmortizationType.None, Dictionary <Date, double> amortizationInDates = null, Dictionary <int, double> amortizationInIndex = null, bool renormalizeAfterAmoritzation = false, Dictionary <int, double> stepWiseCompensationRate = null, Dictionary <string, double> optionToCall = null, Dictionary <string, double> optionToPut = null, Dictionary <string, double> optionToAssPut = null, double settlementCoupon = double.NaN, bool roundCleanPrice = false ) { Id = id; StartDate = startDate; UnderlyingMaturityDate = maturityDate; Notional = notional; Currency = currency; Coupon = coupon; Calendar = calendar; PaymentFreq = paymentFreq; Stub = stub; AccrualDayCount = accrualDayCount; PaymentDayCount = paymentDayCount; AccrualBizDayRule = accrualBizDayRule; PaymentBizDayRule = paymentBizDayRule; SettlmentGap = settlementGap; _settlementCoupon = settlementCoupon; BondTradeingMarket = bondTradingMarket; FirstPaymentDate = firstPaymentDate; IsZeroCouponBond = isZeroCouponBond; IssuePrice = issuePrice; IssueRate = issueRate; StickToEom = stickToEom; StepWiseCompensationRate = stepWiseCompensationRate; RoundCleanPrice = roundCleanPrice; OptionToCall = optionToCall; OptionToPut = optionToPut; OptionToAssPut = optionToAssPut; Tenor = string.Format("{0},{1}", (int)(UnderlyingMaturityDate - StartDate), "D"); IrregularPayment = false; if (Coupon is CustomizedCoupon) { } else { List <Date> tmpDate; if (FirstPaymentDate == null) { var schedule = new Schedule(StartDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, AccrualBizDayRule); tmpDate = schedule.ToList(); _isRegualDate = schedule.IsRegular; } else { var schedule = new Schedule(FirstPaymentDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, AccrualBizDayRule); var regAccruals = schedule.ToList(); tmpDate = new List <Date> { StartDate }; tmpDate.AddRange(regAccruals); IrregularPayment = false; _isRegualDate = new List <bool> { IrregularPayment }; _isRegualDate.AddRange(schedule.IsRegular); } if (tmpDate.Count > 2) { if (PaymentBizDayRule.Adjust(calendar, tmpDate[tmpDate.Count - 2]).Equals(tmpDate.Last())) { tmpDate.RemoveAt(tmpDate.Count - 2); _isRegualDate.RemoveAt(_isRegualDate.Count - 2); } } Accruals = new Schedule(tmpDate); if (FirstPaymentDate == null) { PaymentSchedule = new Schedule( new Schedule(StartDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, PaymentBizDayRule).Skip(1)); } else { PaymentSchedule = new Schedule( new Schedule(FirstPaymentDate, UnderlyingMaturityDate, PaymentFreq.GetTerm(), Stub, Calendar, PaymentBizDayRule)); } } if (Accruals.Count() != PaymentSchedule.Count() + 1) { throw new PricingLibraryException("Bond's number of accrual periods do not match number of payments"); } AmortizationType = amortionType; AmortizationInDates = amortizationInDates; AmortizationInIndex = amortizationInIndex; RenormalizeAfterAmoritzation = renormalizeAfterAmoritzation; IAmortization amortization; if (AmortizationInDates != null) { amortization = new Amortization(amortizationInDates, RenormalizeAfterAmoritzation); } else if (AmortizationInIndex != null) { amortization = new Amortization(ToAmortizationSchedule(PaymentSchedule.ToArray(), AmortizationInIndex), RenormalizeAfterAmoritzation); } else { //EqualPrincipal or EqualPrincipalAndInterest will be calculated later amortization = new Amortization(); } Amoritzation = amortization; _mortgageCalculator = new MortgageCalculator(new Psa(0.0), new Sda(0.0)); Redemption = redemption ?? new Redemption(1.0, RedemptionType.None); //Redemption = redemption ?? new Redemption(1.0, PriceQuoteType.Clean); if (PaymentFreq == Frequency.None) { IrregularPayment = true; } else { for (var i = 0; i < Accruals.Count() - 1; ++i) { if (PaymentFreq.GetTerm().Next(Accruals.ToArray()[i]) != Accruals.ToArray()[i + 1]) { IrregularPayment = false; break; } } } _compensationRate = Accruals.Skip(1).Select(x => 0.0).ToArray(); if (stepWiseCompensationRate != null) { var compensationCoupons = new List <double>(); var arr = StepWiseCompensationRate.OrderBy(x => x.Key).Select(x => Tuple.Create(x.Key, x.Value)).ToArray(); for (var i = 0; i < Accruals.Count() - 1; ++i) { compensationCoupons.Add(i > 0 ? compensationCoupons[i - 1] : 0.0); var updateCoupon = arr.FirstOrDefault(x => x.Item1 == (i + 1)); var compensationCoupon = updateCoupon != null ? updateCoupon.Item2 : 0.0; compensationCoupons[i] += compensationCoupon; } _compensationRate = compensationCoupons.ToArray(); } }