public void OnT1Selected(bool isOn) { if (isOn) { selectedTData = T1Date; } }
public void OnT3Selected(bool isOn) { if (isOn) { selectedTData = T3Date; } }
/// <summary> /// Returns the known reset rate if necessary, either via user-specified known rate or rate fixings file. Returns null if either reset rate is not necessary or not found. /// </summary> private static double?GetKnownResetRate(TDate baseDate, TDate resetDate, TDate paymentDate, YesNo useKnownRate, double knownRate, string rateFixing, RateFixingsProvider rateFixingsProvider, Deal deal) { double?knownResetRate = null; if (paymentDate >= baseDate && resetDate <= baseDate) { if (useKnownRate == YesNo.Yes) { knownResetRate = knownRate; } else if (!string.IsNullOrWhiteSpace(rateFixing) && rateFixingsProvider != null) { // Try get realized reset rate from Rate fixing file. DateTime[] missingDates = { DateTime.FromOADate(resetDate) }; var fixings = CashflowsFixingsHelper.GetRateFixings(rateFixing, missingDates, rateFixingsProvider, baseDate, deal); if (fixings != null && fixings.Length != 0 && !double.IsNaN(fixings[0])) { knownResetRate = fixings[0]; } } } return(knownResetRate); }
public void OnT2Selected(bool isOn) { if (isOn) { selectedTData = T2Date; } }
static void Main(string[] args) { DateTime today = DateTime.Today; string[] f = Convert.ToString(today).Split(' '); string[] s = f[0].Split('.'); int date = int.Parse(s[0]); int month = int.Parse(s[1]); int year = int.Parse(s[2]); Console.WriteLine($"Сегодняшняя дата: {date}.{month}.{year}\n"); TDate myDate = InputTDate(); DateTime new_day = new DateTime(myDate.Year, myDate.Month, myDate.Day); int result = DateTime.Compare(today, new_day); Console.Write("\nСравнение показало, что "); if (result > 0) { Console.WriteLine("вы опоздали"); } else { Console.WriteLine("дата наступит через дней: {0}", Check(myDate, date, month, year)); } //Console.WriteLine("\nНапоминалка!"); WriteTDate(myDate); }
protected void Calendar1_SelectionChanged(object sender, EventArgs e) { String[] split1; try { PDate = Calendar1.SelectedDate.ToString("dd/MM/yyyy"); split1 = PDate.Split('-'); txtd1.Text = split1[0]; txtm1.Text = split1[1]; txty1.Text = split1[2]; TDate = DateTime.Now.ToString("dd/MM/yyyy"); String[] split3 = TDate.Split('-'); txtd3.Text = split3[0]; txtm3.Text = split3[1]; txty3.Text = split3[2]; if (int.Parse(txty1.Text) > int.Parse(txty3.Text)) { cvday0.Enabled = false; cvmonth0.Enabled = false; } if (int.Parse(txtm1.Text) > int.Parse(txtm3.Text)) { cvday0.Enabled = false; } } catch (Exception err) { lblmsg.Text = err.Message; } }
public void TestRegExReplace() { var tstr = new TVariable("") { regex_pattern = new Regex(@"(\S+)а,\s*(\S+)"), regex_replace = "район $2 города $1ы" }; tstr.Set("Москва, ЦАО"); Assert.AreEqual("район ЦАО города Москвы", tstr.value); var tnumeric = new TNumeric("") { regex_pattern = new Regex(@"(\d)(\d)(\d)"), regex_replace = "$2$3$1" }; ((TVariable)tnumeric).Set("123"); Assert.AreEqual(231f, tnumeric.value); var tdate = new TDate("") { regex_pattern = new Regex(@".* (\d{4}) года за (\d) месяц"), regex_replace = "1.$2.$1", format = "d.M.yyyy", lastday = true }; tdate.Set("отчёт 2020 года за 2 месяц"); Assert.AreEqual(new DateTime(2020, 2, 29), tdate.value); }
public BankAccount(string fullName, decimal accountBalance, string customTime) { FullName = fullName; Balance = new TMoney(accountBalance.ToString()); CreationTime = new TDate(customTime); AccountNumber = nextID; ++nextID; }
public void BuildTurret(TDate turretData) { this.turretData = turretData; isUpgraded = false; turretGo = GameObject.Instantiate(turretData.turretPrefab, transform.position, Quaternion.identity); GameObject effect = GameObject.Instantiate(buildEffect, transform.position, Quaternion.identity); Destroy(effect, 1.5f); }
public void DestroyTurret() { Destroy(turretGo); isUpgraded = false; turretGo = null; turretData = null; GameObject effect = GameObject.Instantiate(buildEffect, transform.position, Quaternion.identity); Destroy(effect, 1.5f); }
public void TestTDateWithDateValue() { var tdate = new TDate("DATE"); tdate.Set(new DateTime(2001, 11, 22)); Assert.AreEqual(new DateTime(2001, 11, 22), tdate.value); tdate = new TDate("DATE") { lastday = true }; tdate.Set(new DateTime(2001, 11, 22)); Assert.AreEqual(new DateTime(2001, 11, DateTime.DaysInMonth(2001, 11)), tdate.value); }
static void Main(string[] args) { var path = Environment.CurrentDirectory + "\\" + "file.txt"; Console.WriteLine(path); StreamReader reader = new StreamReader(path); var input = reader.ReadToEnd().Split('\n'); reader.Close(); int fileYear = int.Parse(input[0]); int fileMonth = int.Parse(input[1]); int fileDay = int.Parse(input[2]); int fileHour = int.Parse(input[3]); int fileMinute = int.Parse(input[4]); DateTime new_day = new DateTime(fileYear, fileMonth, fileDay); DateTime today = DateTime.Today; string[] f = Convert.ToString(today).Split(' '); string[] s = f[0].Split('.'); int date = int.Parse(s[0]); int month = int.Parse(s[1]); int year = int.Parse(s[2]); Console.WriteLine($"Сегодняшняя дата: {date}.{month}.{year}\n"); TDate myDate = InputTDate(); //DateTime new_day = new DateTime(myDate.Year, myDate.Month, myDate.Day); int result = DateTime.Compare(today, new_day); Console.Write("\nСравнение показало, что "); if (result > 0) { Console.WriteLine("вы опоздали"); } else { Console.WriteLine("дата наступит через дней: {0}", Check(myDate, date, month, year)); } Console.WriteLine("\nНапоминалка!"); WriteTDate(myDate); }
public void TestTDate() { var tdate = new TDate("DATE"); tdate.Set("22.11.2001"); Assert.AreEqual(new DateTime(2001, 11, 22), tdate.value); tdate = new TDate("DATE") { lastday = true }; tdate.Set("01.02.2004"); Assert.AreEqual(new DateTime(2004, 2, 29), tdate.value); tdate = new TDate("DATE") { format = "yyyy.dd.MM" }; tdate.Set("2005.15.05"); Assert.AreEqual(new DateTime(2005, 5, 15), tdate.value); }
public static Dictionary <string, TVariable> getVariables() { Dictionary <string, TVariable> data = new Dictionary <string, TVariable>(); var tvariable = new TVariable("FIO"); tvariable.Set("Ivanov Ivan Ivanovich"); data.Add(tvariable.name, tvariable); var tnumeric = new TNumeric("SUMMA"); tnumeric.Set(12.3456f); data.Add(tnumeric.name, tnumeric); var tdate = new TDate("DATE"); tdate.Set("22.11.2001"); data.Add(tdate.name, tdate); return(data); }
static void WriteTDate(TDate data) { string hour, minute; if (data.Hour < 10) { hour = "0" + Convert.ToString(data.Hour); } else { hour = Convert.ToString(data.Hour); } if (data.Minute < 10) { minute = "0" + Convert.ToString(data.Minute); } else { minute = Convert.ToString(data.Minute); } Console.WriteLine($"Дата: {data.Day} {data.MonthName} {data.Year}г.\nВремя: {hour}:{minute}"); }
public void TestRegEx() { var tstr = new TVariable("") { regex_pattern = new Regex("(\\S+) округа города (\\S+)"), regex_group = 2 }; tstr.Set("Центрального округа города Москвы"); Assert.AreEqual("Москвы", tstr.value); tstr.Set("Не подходящий условию текст"); Assert.AreEqual("", tstr.value); tstr.regex_group = 4; tstr.Set("Центрального округа города Москвы"); Assert.AreEqual("", tstr.value); var tnumeric = new TNumeric("") { regex_pattern = new Regex("Итого (\\S+)р.") }; ((TVariable)tnumeric).Set("Итого 800,45р. начислено"); Assert.AreEqual(800.45f, tnumeric.value); var tdate = new TDate("") { regex_pattern = new Regex("основан (.*) год"), format = "dd MMMM yyyy" }; ((TVariable)tdate).Set("Санкт-Петербург был основан 27 мая 1703 года"); Assert.AreEqual(new DateTime(1703, 05, 27), tdate.value); }
/// <summary> /// Gets the next reset date. /// </summary> /// <remarks>Treat the horizon as truncating the lending.</remarks> public override TDate GetNextResetDate(TDate currentResetDate) { return(Reset_Frequency > 0.0 ? Math.Min(DateAdjuster.Add(currentResetDate, Period.ValueToTerm(Reset_Frequency), GetHolidayCalendar()), EndDate()) : DateAdjuster.Add(Effective_Date, Investment_Horizon)); }
/// <summary> /// Calculate the dates and years fractions not specified on the deal and get any known rates. /// </summary> public void Prepare(double baseDate, RateFixingsProvider rateFixings) { // Calculates various date properties of the deal and cache them. var deal = (FloatingInterestCashflowInterpolatedDeal)Deal; var accrualCalendars = deal.GetAccrualHolidayCalendars(); var rateCalendars = deal.GetRateHolidayCalendars(); fPaymentDate = deal.Payment_Date; if (deal.Accrual_Year_Fraction > 0.0) { fAccrualYearFraction = deal.Accrual_Year_Fraction; } else { fAccrualYearFraction = CalcUtils.DayCountFraction(deal.Accrual_Start_Date, deal.Accrual_End_Date, deal.Accrual_Day_Count, accrualCalendars); } fKnownResetRate1 = null; fKnownResetRate2 = null; if (deal.HasRate1()) { if (deal.Rate_1_End_Date > 0.0) { fRate1EndDate = deal.Rate_1_End_Date; } else { fRate1EndDate = DateAdjuster.Add(deal.Rate_Start_Date, deal.Rate_1_Tenor, 1, rateCalendars, true, deal.Rate_Adjustment_Method, deal.Rate_Sticky_Month_End == YesNo.Yes).ToOADate(); } if (deal.Rate_1_Year_Fraction > 0.0) { fRate1YearFraction = deal.Rate_1_Year_Fraction; } else { fRate1YearFraction = CalcUtils.DayCountFraction(deal.Rate_Start_Date, fRate1EndDate, deal.Rate_Day_Count, rateCalendars, deal.Rate_1_Tenor); } fKnownResetRate1 = GetKnownResetRate(baseDate, deal.Reset_Date, fPaymentDate, deal.Use_Known_Rate_1, deal.Known_Rate_1, deal.Rate_1_Fixing, rateFixings, deal); } if (deal.HasRate2()) { if (deal.Rate_2_End_Date > 0.0) { fRate2EndDate = deal.Rate_2_End_Date; } else { fRate2EndDate = DateAdjuster.Add(deal.Rate_Start_Date, deal.Rate_2_Tenor, 1, rateCalendars, true, deal.Rate_Adjustment_Method, deal.Rate_Sticky_Month_End == YesNo.Yes).ToOADate(); } if (deal.Rate_2_Year_Fraction > 0.0) { fRate2YearFraction = deal.Rate_2_Year_Fraction; } else { fRate2YearFraction = CalcUtils.DayCountFraction(deal.Rate_Start_Date, fRate2EndDate, deal.Rate_Day_Count, rateCalendars, deal.Rate_2_Tenor); } fKnownResetRate2 = GetKnownResetRate(baseDate, deal.Reset_Date, fPaymentDate, deal.Use_Known_Rate_2, deal.Known_Rate_2, deal.Rate_2_Fixing, rateFixings, deal); } }
/// <summary> /// A payment made to a supplier needs to be reversed. /// It's done by creating and posting a set of matching "negatives" - /// In the simplest case this is a single credit note matching an invoice /// but it could be more complex. These negative documents are payed using /// a standard call to PostAPPayments. /// /// After the reversal, I'll also create and post new copies of all /// the invoices / credit notes that made up the original payment. /// </summary> /// <param name="ALedgerNumber"></param> /// <param name="APaymentNumber"></param> public void ReversePayment(Int32 ALedgerNumber, Int32 APaymentNumber) { AccountsPayableTDS TempDS = TRemote.MFinance.AP.WebConnectors.LoadAPPayment(ALedgerNumber, APaymentNumber); if (TempDS.AApPayment.Rows.Count == 0) // Invalid Payment number? { MessageBox.Show(Catalog.GetString("The referenced payment Connot be loaded."), Catalog.GetString("Error")); return; } TempDS.AApDocument.DefaultView.Sort = AApDocumentTable.GetApDocumentIdDBName(); // // First I'll check that the amounts add up: // Decimal PaidDocumentsTotal = 0.0m; foreach (AApDocumentPaymentRow PaymentRow in TempDS.AApDocumentPayment.Rows) { Int32 DocIdx = TempDS.AApDocument.DefaultView.Find(PaymentRow.ApDocumentId); AApDocumentRow DocumentRow = TempDS.AApDocument[DocIdx]; if (DocumentRow.CreditNoteFlag) { PaidDocumentsTotal -= DocumentRow.TotalAmount; } else { PaidDocumentsTotal += DocumentRow.TotalAmount; } } // // If this is a partial payment, I can't deal with that here... // if (PaidDocumentsTotal != TempDS.AApPayment[0].Amount) { String ErrorMsg = String.Format(Catalog.GetString( "This Payment cannot be reversed automatically because the total amount of the referenced documents ({0:n2} {1}) differs from the amount in the payment ({2:n2} {3})."), PaidDocumentsTotal, TempDS.AApSupplier[0].CurrencyCode, TempDS.AApPayment[0].Amount, TempDS.AApSupplier[0].CurrencyCode); MessageBox.Show(ErrorMsg, Catalog.GetString("Reverse Payment"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Find out if this payment was already reversed, // because if it was, perhaps the user doesn't really want to // reverse it again? this.Cursor = Cursors.WaitCursor; if (TRemote.MFinance.AP.WebConnectors.WasThisPaymentReversed(ALedgerNumber, APaymentNumber)) { this.Cursor = Cursors.Default; MessageBox.Show(Catalog.GetString("Cannot reverse Payment - there is already a matching reverse transaction."), Catalog.GetString("Reverse Payment"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.Cursor = Cursors.Default; // // Ask the user to confirm reversal of this payment // String PaymentMsg = Catalog.GetString("Do you want to reverse this payment?"); PaymentMsg += ("\r\n" + String.Format("Payment made {0} to {1}\r\n\r\nRelated invoices:", TDate.DateTimeToLongDateString2(TempDS.AApPayment[0].PaymentDate.Value), TempDS.PPartner[0].PartnerShortName)); foreach (AApDocumentPaymentRow PaymentRow in TempDS.AApDocumentPayment.Rows) { Int32 DocIdx = TempDS.AApDocument.DefaultView.Find(PaymentRow.ApDocumentId); AApDocumentRow DocumentRow = TempDS.AApDocument[DocIdx]; PaymentMsg += ("\r\n" + String.Format(" {2} ({3}) {0:n2} {1}", DocumentRow.TotalAmount, TempDS.AApSupplier[0].CurrencyCode, DocumentRow.DocumentCode, DocumentRow.Reference)); } PaymentMsg += ("\r\n\r\n" + String.Format("Total payment {0:n2} {1}", TempDS.AApPayment[0].Amount, TempDS.AApSupplier[0].CurrencyCode)); DialogResult YesNo = MessageBox.Show(PaymentMsg, Catalog.GetString("Reverse Payment"), MessageBoxButtons.YesNo); if (YesNo == DialogResult.No) { return; } TDlgGLEnterDateEffective dateEffectiveDialog = new TDlgGLEnterDateEffective( ALedgerNumber, Catalog.GetString("Select posting date"), Catalog.GetString("The date effective for the reversal") + ":"); if (dateEffectiveDialog.ShowDialog() != DialogResult.OK) { MessageBox.Show(Catalog.GetString("Reversal was cancelled."), Catalog.GetString("Reverse Payment"), MessageBoxButtons.OK, MessageBoxIcon.Error); return; } DateTime PostingDate = dateEffectiveDialog.SelectedDate; TVerificationResultCollection Verifications; this.Cursor = Cursors.WaitCursor; if (TRemote.MFinance.AP.WebConnectors.ReversePayment(ALedgerNumber, APaymentNumber, PostingDate, out Verifications)) { this.Cursor = Cursors.Default; // TODO: print reports on successfully posted batch MessageBox.Show(Catalog.GetString("The AP payment has been reversed."), Catalog.GetString("Reverse Payment")); TFormsMessage broadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcAPTransactionChanged); broadcastMessage.SetMessageDataAPTransaction(String.Empty); TFormsList.GFormsList.BroadcastFormMessage(broadcastMessage); } else { this.Cursor = Cursors.Default; string ErrorMessages = String.Empty; foreach (TVerificationResult verif in Verifications) { ErrorMessages += "[" + verif.ResultContext + "] " + verif.ResultTextCaption + ": " + verif.ResultText + Environment.NewLine; } System.Windows.Forms.MessageBox.Show(ErrorMessages, Catalog.GetString("Reverse Payment Failed")); } }
/// <summary> /// Set the expiry of the deal. /// </summary> /// <remarks>Note that this method is only to be used by bootstrapper. Code is not supposed to change the deal properties programmatically.</remarks> public void SetExpiryDate(TDate expiry) { Expiry_Date = expiry; }
/// <summary> /// Returns the specified find results page. /// /// @comment Pages can be requested in any order! /// /// </summary> /// <param name="APage">Page to return</param> /// <param name="APageSize">Number of records to return per page</param> /// <param name="ATotalRecords">The amount of rows found by the SELECT statement</param> /// <param name="ATotalPages">The number of pages that will be needed on client-side to /// hold all rows found by the SELECT statement</param> /// <returns>DataTable containing the find result records for the specified page /// </returns> public DataTable GetDataPagedResult(System.Int16 APage, System.Int16 APageSize, out System.Int32 ATotalRecords, out System.Int16 ATotalPages) { if (TLogging.DL >= 7) { Console.WriteLine(this.GetType().FullName + ".GetDataPagedResult called."); } DataTable ReturnValue = FPagedDataSetObject.GetData(APage, APageSize); if (FSearchTransactions) { foreach (DataRow Row in ReturnValue.Rows) { SetOutstandingAmount(Row); } } else { // searching for outstanding invoices on the main screen if (!FSearchSupplierOrInvoice) { foreach (DataRow Row in ReturnValue.Rows) { // calculate DateDue and DateDiscountUntil // add creditTerms to dateIssued to get DateDue if (Row["CreditTerms"].GetType() != typeof(DBNull)) { Row["DateDue"] = Convert.ToDateTime(Row["DateIssued"]).AddDays(Convert.ToInt16(Row["CreditTerms"])); } if (Row["DiscountDays"].GetType() != typeof(DBNull)) { Row["DateDiscountUntil"] = Convert.ToDateTime(Row["DateIssued"]).AddDays(Convert.ToInt16(Row["DiscountDays"])); } SetOutstandingAmount(Row); Row["DiscountMsg"] = "None"; Row["Selected"] = false; if (Row["DiscountPercentage"].GetType() == typeof(DBNull)) { Row["DiscountPercentage"] = 0; } if (Convert.ToDateTime(Row["DateDiscountUntil"]) > DateTime.Now) { Row["DiscountMsg"] = String.Format("{0:n0}% until {1}", Row["DiscountPercentage"], TDate.DateTimeToLongDateString2(Convert.ToDateTime(Row["DateDiscountUntil"]))); } else { Row["DiscountMsg"] = "Expired"; } } } } ATotalPages = FPagedDataSetObject.TotalPages; ATotalRecords = FPagedDataSetObject.TotalRecords; // TODO TAccountsPayableAggregate.ApplySecurity(ref ReturnValue); return(ReturnValue); }
static int Check(TDate data, int date, int month, int year) { int delta = 0; int[] nMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int delta_year = data.Year - year; int c = 1; //Console.WriteLine($"delta_year: {delta_year}"); if (delta_year >= 2) { if (data.Month >= month) { if (data.Day >= date) { delta += (data.Year - year) * 365; delta_year = 0; } else { delta += (data.Year - year - 1) * 365; delta_year = 1; } } else { delta += (data.Year - year - 1) * 365; delta_year = 1; } } // Console.WriteLine($"delta: {delta}"); if (delta_year == 1) { c = 1; foreach (int el in nMonths) { if (month == c) { delta += (el - date); } else if (month < c) { delta += el; } c++; } c = 1; foreach (int el in nMonths) { if (c < data.Month) { delta += el; } else if (c == data.Month) { delta += data.Day; } c++; } } if (delta_year == 0) { foreach (int el in nMonths) { if (month == c) { delta += (el - date); } else if (month < c && c < data.Month) { delta += el; } else if (c == data.Month) { delta += data.Day; } c++; } } return(delta); }
/// <summary> /// This method Adjusts the bond price vector by taking the default into account give the default time vector. /// </summary> public static void AdjustForDefault(double baseDate, double valueDate, Vector bondPrice, TDate expiryDate, bool respectDefault, Vector underlyingIsAlive, Vector historicalRecovery, Vector defaultTime, IInterestRate discountRate, RecoveryRate recoveryRate) { // Adjust the bond price for default: check scenario by scenario for defaults, overwriting bondPrice as necessary if (!respectDefault) { return; } double currentTime = CalcUtils.DaysToYears(valueDate - baseDate); double tExpiry = CalcUtils.DaysToYears(expiryDate - baseDate); BondOptionValuation.AdjustBondValueForDefault(1.0, tExpiry, bondPrice, underlyingIsAlive, historicalRecovery, defaultTime, currentTime, discountRate, recoveryRate); }
protected TVariable getVar(XElement xml, bool dynamic) { var name = xml.Attribute("name")?.Value ?? throw new NullReferenceException("Variable attribute 'name' can't be null!"); var ctype = xml.Attribute("type")?.Value ?? "string"; TVariable variable; switch (ctype) { case "numeric": variable = new TNumeric(name); break; case "date": variable = new TDate(name); break; default: variable = new TVariable(name); break; } variable.x = Int32.Parse(xml.Attribute("X")?.Value ?? throw new NullReferenceException("Variable attribute 'X' can't be null!")); if (!dynamic) { variable.y = Int32.Parse(xml.Attribute("Y")?.Value ?? throw new NullReferenceException("Variable attribute 'Y' can't be null!")); } variable.dynamic = dynamic; if (variable is TNumeric tnumeric) { var function = xml.Attribute("function"); if (function != null) { tnumeric.function = TNumeric.getFuncByString(function.Value); } } if (variable is TDate tdate) { var lastday = xml.Attribute("lastday"); var language = xml.Attribute("language"); var format = xml.Attribute("format"); if (lastday != null) { tdate.lastday = Boolean.Parse(lastday.Value); } if (language != null) { tdate.language = language.Value; } if (format != null) { tdate.format = format.Value; } } var regex_pattern = xml.Attribute("regex_pattern"); if (regex_pattern != null) { variable.regex_pattern = new Regex(regex_pattern.Value, RegexOptions.Compiled); var regex_group = xml.Attribute("regex_group"); variable.regex_group = int.Parse(regex_group?.Value ?? "1"); } return(variable); }
/// <summary> /// Return an enumeration of the contract periods for this deal. /// </summary> public IEnumerable <ContractPeriod> GetContractPeriods(TDate start, TDate end) { yield return(new ContractPeriod(start, end)); }
/// <summary> /// Generic Deal Valuation - derived objects override the ValueFn() method. /// </summary> public override void Value(ValuationResults valuationResults, PriceFactorList factors, BaseTimeGrid baseTimes) { PreValue(factors); var deal = (CalendarSpreadOption)Deal; var tgi = new TimeGridIterator(fT); PVProfiles result = valuationResults.Profile; CashAccumulators accumulator = valuationResults.Cash; fTimeToSettlement = CalcUtils.DaysToYears(deal.Settlement_Date - factors.BaseDate); fPeriodEnd1 = CalcUtils.DaysToYears(deal.Period_End_1 - factors.BaseDate); fPeriodEnd2 = CalcUtils.DaysToYears(deal.Period_End_2 - factors.BaseDate); // The time to expiry is the time to the end of the first expiring contract. fTimeToExpiry = CalcUtils.DaysToYears(deal.Period_End_1 - factors.BaseDate); using (var cache = Vector.Cache(factors.NumScenarios)) { EnergySpreadOptionPricer pricer1 = GetEnergyOptionPricer(fForwardSample, fReferencePrice1, fReferenceVol1, factors.BaseDate, fPeriodEnd1, deal.Period_Start_1, deal.Period_End_1, deal.Realized_Average_1, deal.Realized_Average_Date_1, cache); EnergySpreadOptionPricer pricer2 = GetEnergyOptionPricer(fForwardSample, fReferencePrice2, fReferenceVol2, factors.BaseDate, fPeriodEnd2, deal.Period_Start_2, deal.Period_End_2, deal.Realized_Average_2, deal.Realized_Average_Date_2, cache); Vector pv = cache.Get(); Vector realizedPrice1 = cache.Get(); Vector realizedPrice2 = cache.Get(); Vector unrealizedPrice1 = cache.Get(); Vector unrealizedPrice2 = cache.Get(); Vector vol1 = cache.Get(); Vector vol2 = cache.Get(); Vector correlation = cache.Get(); Vector discountFactor = cache.Get(); // Calculate correlation between forward prices for two different (dereferenced) maturities (e.g. Apr2012 and Jan2013). TDate forwardDate1 = fReferencePrice1.GetPriceDate(deal.Period_End_1, 0); TDate forwardDate2 = fReferencePrice2.GetPriceDate(deal.Period_End_2, 0); fCorrelations.GetValue(correlation, tgi.T, forwardDate1, forwardDate2); while (tgi.Next()) { pv.Clear(); if (tgi.T <= fTimeToExpiry) { // Get unrealised reference forward prices (which also age the pricer to time t and update the realized average at time t) pricer1.GetUnrealizedPrice(tgi.T, unrealizedPrice1); pricer2.GetUnrealizedPrice(tgi.T, unrealizedPrice2); // Get the realized averages for both reference prices. pricer1.GetRealizedPrice(realizedPrice1); pricer2.GetRealizedPrice(realizedPrice2); int numSamples1 = pricer1.GetNumSamples(); int numRealizedSamples1 = pricer1.GetNumRealizedSamples(); int numUnrealizedSamples1 = pricer1.GetNumUnrealizedSamples(); int numSamples2 = pricer2.GetNumSamples(); int numRealizedSamples2 = pricer2.GetNumRealizedSamples(); int numUnrealizedSamples2 = pricer2.GetNumUnrealizedSamples(); // Modify the strike Vector kStar = cache.Get(deal.Strike_Price - realizedPrice1 * numRealizedSamples1 / numSamples1 + realizedPrice2 * numRealizedSamples2 / numSamples2); Vector refPriceStar1 = cache.Get(unrealizedPrice1 * numUnrealizedSamples1 / numSamples1); Vector refPriceStar2 = cache.Get(unrealizedPrice2 * numUnrealizedSamples2 / numSamples2); // Get ATM volatilities of the forward price at different maturities (given as time in years with respect to base date). pricer1.GetVol(tgi.T, unrealizedPrice2, vol1); pricer2.GetVol(tgi.T, unrealizedPrice1, vol2); // value is intrinsic - pricing with volatility 0 and realized price if there are no future sample. if (numUnrealizedSamples1 == 0) { vol1.Clear(); } // value is intrinsic - pricing with volatility 0 and realized price if there are no future sample. if (numUnrealizedSamples2 == 0) { vol2.Clear(); } // CSO pricing: exp(-rT) * E{max(F1(T) - F2(T) - K, 0)} // For the European CSO, we set multiplier1 = sign, multiplier2 = -sign, constant = -sign * strike, // where sign = +1 for a call and -1 for a put in the SpreadOptionBS function. double rootTime = Math.Sqrt(fTimeToExpiry - tgi.T); Vector volStar1 = cache.Get(vol1 * rootTime); Vector volStar2 = cache.Get(vol2 * rootTime); PricingFunctions.SpreadOptionBS(pv, fCallPutSign, -fCallPutSign, cache.Get(-fCallPutSign * kStar), fCallPutSign, refPriceStar1, refPriceStar2, kStar, volStar1, volStar2, correlation); // The option itself cannot be worth less than zero (for long positions). // However, due to that the Bjerksund & Stensland is a type of non-optimal exercise, it is possible to end up with negative PV via // its pricing formula. pv.AssignMax(pv, 0.0); // Discount payment made at settlement date pv.MultiplyBy(fScale * fDiscountRate.Get(tgi.T, fTimeToSettlement)); } // Cash settlement at settlement date if (tgi.T == fTimeToSettlement && accumulator != null && !accumulator.Ignore) { accumulator.Accumulate(fFxPayoffRate, tgi.Date, pv); } result.AppendVector(tgi.Date, pv * fFxPayoffRate.Get(tgi.T)); } result.Complete(fT); } }
/// <summary> /// Returns the energy option pricer. /// </summary> protected virtual EnergySpreadOptionPricer GetEnergyOptionPricer(ForwardPriceSample forwardSample, IReferencePrice referencePrice, ReferenceVol referenceVol, double baseDate, double tExpiry, double periodStart, double periodEnd, double realisedAverage, TDate realisedAverageDate, VectorScopedCache.Scope cache) { // Price samples List <TDate> priceSamples = forwardSample.GetSamplesList(periodStart, periodEnd).ToList(); return(new EnergySpreadOptionPricer( baseDate, tExpiry, priceSamples, forwardSample.Offset, realisedAverage, realisedAverageDate, referencePrice, referenceVol, fFxRate, fPriceFactorFxRate, fFxPayoffRate, cache)); }
public override void ExecuteExport(object obj) { GlobalClass.ReportName = "Goods Received Detail"; GlobalClass.ReportParams = string.Format("From Date : {0} To {1}", FDate.ToString("MM/dd/yyyy"), TDate.ToString("MM/dd/yyyy")); wExportFormat ef = new wExportFormat(Report); ef.ShowDialog(); }
public override void ExecutePrint(object obj) { GlobalClass.ReportName = "Goods Received Detail"; GlobalClass.ReportParams = string.Format("From Date : {0} To {1}", FDate.ToString("MM/dd/yyyy"), TDate.ToString("MM/dd/yyyy")); Report.PrintSettings.PrintPageMargin = new Thickness(30); Report.PrintSettings.AllowColumnWidthFitToPrintPage = false; Report.PrintSettings.PrintPageOrientation = PrintOrientation.Landscape; Report.Print(); }
/// <summary> /// Gets the next reset date from the current reset date. /// </summary> /// <remarks>Current reset date is always the effective date and next reset date is therefore always the maturity date.</remarks> public override TDate GetNextResetDate(TDate effectiveDate) { return(Maturity_Date); }