Example #1
0
 public void CanAddNegativeMonths_FromDay31_ToDay30()
 {
     var dt = new Date(2000, 5, 31);
     var actual = dt.AddMonths(-1);
     var expected = new Date(2000, 4, 30);
     Assert.Equal(expected, actual);
 }
Example #2
0
 public void CanAddNegativeMonths_FromDay31_ToDay28()
 {
     var dt = new Date(2001, 3, 31);
     var actual = dt.AddMonths(-1);
     var expected = new Date(2001, 2, 28);
     Assert.Equal(expected, actual);
 }
Example #3
0
 public void CanAddNegativeMonths()
 {
     var dt = new Date(2000, 1, 1);
     var actual = dt.AddMonths(-1);
     var expected = new Date(1999, 12, 1);
     Assert.Equal(expected, actual);
 }
Example #4
0
        public void CanCompareDates()
        {
            Date d1 = new Date(2013, 4, 5);
            Date d2 = new Date(2013, 4, 5);
            Date d3 = new Date(2014, 4, 8);

            Assert.True(d1 == d2);
            Assert.True(d1 != d3);
            Assert.True(d1 <= d2);
            Assert.True(d1 >= d2);
            Assert.True(d1 < d1.AddDays(3));
            Assert.True(d1 < d1.AddMonths(4));
            Assert.True(d1 < d1.AddYears(5));
            Assert.True(d1 <= d1.AddDays(3));
            Assert.True(d1 <= d1.AddMonths(4));
            Assert.True(d1 <= d1.AddYears(5));
            Assert.True(d1 > d1.AddDays(-3));
            Assert.True(d1 > d1.AddMonths(-4));
            Assert.True(d1 > d1.AddYears(-5));
            Assert.True(d1 >= d1.AddDays(-3));
            Assert.True(d1 >= d1.AddMonths(-4));
            Assert.True(d1 >= d1.AddYears(-5));
        }
Example #5
0
        public void GenerateInstallment(double installment)
        {
            double resultInstallment = TotalValue / installment;

            for (int i = 0; i < installment; i++)
            {
                DateTime date = Date.AddMonths(i + 1);

                IPaymentService paymentInstallment = new Installment(date, resultInstallment);
                paymentInstallment.InterestValue(i + 1);

                AddInstallment(paymentInstallment);
            }
        }
Example #6
0
        private static Date Add(Date date, int length, SkipQuantumEnum quantum)
        {
            switch (quantum)
            {
            case SkipQuantumEnum.DAYS:
                return(date.AddDays(length));

            case SkipQuantumEnum.WEEKS:
                return(date.AddDays(length * 7));

            case SkipQuantumEnum.MONTHS:
                return(date.AddMonths(length));

            case SkipQuantumEnum.QUARTERS:
                return(date.AddMonths(length * 3));

            case SkipQuantumEnum.YEARS:
                return(date.AddYears(length));

            default:
                throw new NotSupportedException(String.Format("Unsupported option: {0}", quantum));
            }
        }
        public void TestDynamicCallFromString()
        {
            var source =
                @"Date exerciseDate = new Date(2017, 08, 28);
Share share = new Share(""AAA"", new Currency(""ZAR""));
double strike = 100.0;

public override List<Cashflow> GetCFs()
{
    double amount = Math.Max(0, Get(share, exerciseDate) - strike);
    return new List<Cashflow> { new Cashflow(exerciseDate, amount, share.Currency) };
}";
            // Make a product at runtime
            var runtimeProduct = RuntimeProduct.CreateFromString("MyEuropeanOption", source);

            // Setup an approriate simulation
            var shares = new[]
            {
                new Share("AAA", TestHelpers.ZAR)
            }; // One needs to know the index that will be required by the product to simulate it.
            var valueDate = new Date(2016, 08, 28);

            var divYield     = new[] { 0.02 };
            var vol          = new[] { 0.22 };
            var spotPrice    = new[] { 100.0 };
            var correlations = new[, ] {
                { 1.0 }
            };
            IDiscountingSource discountCurve = new DatesAndRates(TestHelpers.ZAR, valueDate,
                                                                 new[] { valueDate, valueDate.AddMonths(120) },
                                                                 new[] { 0.07, 0.07 });
            var rateForecastCurves = new IFloatingRateSource[0];

            var sim = new EquitySimulator(shares, spotPrice, vol, divYield,
                                          correlations, discountCurve, rateForecastCurves);

            // Value the runtime product
            Coordinator coordinator;

            coordinator = new Coordinator(sim, new List <Simulator>(), 100000);
            var valueRuntime = coordinator.Value(new[] { runtimeProduct }, valueDate);

            var exerciseDate = new Date(2017, 08, 28);
            var strike       = 100.0;
            var refValue     = BlackEtc.BlackScholes(PutOrCall.Call, strike, (exerciseDate - valueDate) / 365, spotPrice[0],
                                                     vol[0], 0.07, divYield[0]);

            Assert.AreEqual(refValue, valueRuntime, refValue * 0.03);
        }
Example #8
0
        public void InstallmentCalculation(int numberInstallments)
        {
            for (int i = 1; i <= numberInstallments; i++)
            {
                Date.AddMonths(i);
                int month = Date.Month;

                double value = TotalValue;
                value = value / numberInstallments;
                value = _paymentService.MonthlySimple(value, i);
                value = _paymentService.PaymentFee(value);

                Installments.Add(new Installment(Date.AddMonths(i), value));
            }
        }
Example #9
0
        public IList <DateTime> ToList()
        {
            if (Rounding != DateListIncrementRounding.None)
            {
                RoundDate();
            }

            var targetCount = Math.Abs(Count);

            var dateList = new List <DateTime>();

            do
            {
                var step = StepSize * dateList.Count;

                switch (Increment)
                {
                case DateListIncrement.Second:
                    dateList.Add(Date.AddSeconds(step));
                    break;

                case DateListIncrement.Minute:
                    dateList.Add(Date.AddMinutes(step));
                    break;

                case DateListIncrement.Hour:
                    dateList.Add(Date.AddHours(step));
                    break;

                case DateListIncrement.Day:
                    dateList.Add(Date.AddDays(step));
                    break;

                case DateListIncrement.Month:
                    dateList.Add(Date.AddMonths(step));
                    break;

                case DateListIncrement.Year:
                    dateList.Add(Date.AddYears(step));
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            } while (dateList.Count < targetCount);

            return(dateList);
        }
Example #10
0
        private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
        {
            if (e.VerticalVelocity > FlickVelocity)
            {
                SoundUtilities.Instance().Play(SoundType.Slipping);
                Date       = Date.AddMonths(1);
                CurrentDay = Date;
            }

            if (e.VerticalVelocity < -FlickVelocity)
            {
                SoundUtilities.Instance().Play(SoundType.Slipping);
                Date       = Date.AddMonths(-1);
                CurrentDay = Date;
            }
        }
Example #11
0
        public void ShouldAddMonths()
        {
            // Given
            const int value    = 10;
            var       date     = new Date(2016, 03, 30);
            var       dateTime = new DateTime(date.Year, date.Month, date.Day);

            // When
            var newDate     = date.AddMonths(value);
            var newDateTime = dateTime.AddMonths(value);

            // Then
            Assert.AreEqual(newDateTime.Year, newDate.Year);
            Assert.AreEqual(newDateTime.Month, newDate.Month);
            Assert.AreEqual(newDateTime.Day, newDate.Day);
        }
Example #12
0
        public void TestMultiHWAndFXToyCCIRS()
        {
            var valueDate   = new Date(2016, 9, 17);
            var zarRatesSim = new HullWhite1F(Currency.ZAR, 0.05, 0.01, 0.07, 0.07, valueDate);

            zarRatesSim.AddForecast(FloatingIndex.JIBAR3M);
            var usdRatesSim = new HullWhite1F(Currency.USD, 0.05, 0.01, 0.01, 0.01, valueDate);

            usdRatesSim.AddForecast(FloatingIndex.LIBOR3M);
            var eurRatesSim = new HullWhite1F(Currency.EUR, 0.05, 0.01, 0.005, 0.005, valueDate);

            eurRatesSim.AddForecast(FloatingIndex.EURIBOR3M);

            var currencyPairs = new[]
            { new CurrencyPair(Currency.USD, Currency.ZAR), new CurrencyPair(Currency.EUR, Currency.ZAR) };
            var spots        = new[] { 13.6, 15.0 };
            var vols         = new[] { 0.15, 0.15 };
            var correlations = new[, ]
            {
                { 1.0, 0.0 },
                { 0.0, 1.0 }
            };
            var model = new MultiHWAndFXToy(valueDate, Currency.ZAR, new[] { zarRatesSim, usdRatesSim, eurRatesSim },
                                            currencyPairs, spots, vols, correlations);

            var portfolio = new List <Product>();

            portfolio.Add(CreateFloatingLeg(Currency.ZAR, valueDate, -15e6, FloatingIndex.JIBAR3M, 7));
            portfolio.Add(CreateFloatingLeg(Currency.EUR, valueDate, +1e6, FloatingIndex.EURIBOR3M, 7));
            portfolio.Add(CreateFloatingLeg(Currency.ZAR, valueDate, 13e6, FloatingIndex.JIBAR3M, 13));
            portfolio.Add(CreateFloatingLeg(Currency.USD, valueDate, -1e6, FloatingIndex.EURIBOR3M, 13));
            portfolio.Add(IRSwap.CreateZARSwap(0.07, true, 20e6, valueDate, Tenor.Years(4)));

            var stepInMonths  = 1;
            var fwdValueDates = Enumerable.Range(1, 13 * 12 / stepInMonths)
                                .Select(i => valueDate.AddMonths(stepInMonths * i)).ToArray();
            var coord = new Coordinator(model, new List <Simulator>(), 1000);
            //coord.SetThreadedness(false);
            var epe = coord.EPE(portfolio.ToArray(), valueDate, fwdValueDates);

            Assert.AreEqual(1555002, epe[0], 5000);
            Assert.AreEqual(2170370, epe[87], 5000);
            Assert.AreEqual(0, epe[155], 5);

            //Debug.WriteToFile("c:\\dev\\quantsa\\temp\\epeTest_singlethread_10000.csv", epe);
        }
Example #13
0
        private void NextCommand()
        {
            Messenger.Default.Send(new SimpleMessage {
                Type = SimpleMessage.MessageType.NotInStatisticsView
            });

            if (mode == modes.days)
            {
                if (Date != DateTime.Today)
                {
                    Date = Date.AddDays(1);
                    Messenger.Default.Send(Date, "applicationToken");
                    Messenger.Default.Send(new SimpleMessage {
                        Type = SimpleMessage.MessageType.StopTimer
                    });
                }
                if (Date == DateTime.Today)
                {
                    Messenger.Default.Send(new SimpleMessage {
                        Type = SimpleMessage.MessageType.StartTimer
                    });
                }
                DateString = Date.ToShortDateString();
            }
            else if (mode == modes.months)
            {
                Date = Date.AddMonths(1);

                DateString = monthsString[Date.Month - 1];

                Messenger.Default.Send(Date, "applicationToken");
                Messenger.Default.Send(new SimpleMessage {
                    Type = SimpleMessage.MessageType.StopTimer
                });
            }
            else if (mode == modes.years)
            {
                Date       = Date.AddYears(1);
                DateString = Date.Year.ToString();
                Messenger.Default.Send(Date, "applicationToken");
                Messenger.Default.Send(new SimpleMessage {
                    Type = SimpleMessage.MessageType.StopTimer
                });
            }
        }
Example #14
0
        public override List <Cashflow> GetCFs()
        {
            double loanBalance = 40;           // Opening balance on startDate
            var    spread      = 0.035 + 0.02; // 350bp prime Jibar spread + 200bp deal spread

            var periodStartDate = dealStartDate;
            var periodEndDate   = dealStartDate.AddMonths(3);

            var cfs = new List <Cashflow>();

            // Generate the dividend cashflows.
            while (periodEndDate <= dealEndDate)
            {
                var observedRate = Get(jibar, periodStartDate);
                if (loanBalance < 1e-6)
                {
                    cfs.Add(new Cashflow(new Date(periodEndDate), 0, Currency.ZAR));
                }
                else
                {
                    loanBalance *= 1 + (observedRate + spread) * 0.25;
                    var loanReduction = 0.9 * nShares * Get(dividend, periodEndDate);
                    if (loanReduction > loanBalance)
                    {
                        cfs.Add(new Cashflow(new Date(periodEndDate), loanBalance, Currency.ZAR));
                    }
                    else
                    {
                        cfs.Add(new Cashflow(new Date(periodEndDate), loanReduction, Currency.ZAR));
                    }
                    loanBalance = Math.Max(0, loanBalance - loanReduction);
                }

                periodStartDate = new Date(periodEndDate);
                periodEndDate   = periodEndDate.AddMonths(3);
            }

            // Check if the loan is worth more than the shares.  If yes then there is a loss on the loan,
            // otherwise the loan can be repaid in full.
            var finalPayment = Math.Min(loanBalance, nShares * Get(share, dealEndDate));

            cfs.Add(new Cashflow(new Date(dealEndDate), finalPayment, Currency.ZAR));

            return(cfs);
        }
Example #15
0
        public void TestMultiHWAndFXToyCCIRS()
        {
            var valueDate   = new Date(2016, 9, 17);
            var zarRatesSim = new HullWhite1F(TestHelpers.ZAR, 0.05, 0.01, 0.07, 0.07);

            zarRatesSim.AddForecast(TestHelpers.Jibar3M);
            var usdRatesSim = new HullWhite1F(TestHelpers.USD, 0.05, 0.01, 0.01, 0.01);

            usdRatesSim.AddForecast(TestHelpers.Libor3M);
            var eurRatesSim = new HullWhite1F(TestHelpers.EUR, 0.05, 0.01, 0.005, 0.005);

            eurRatesSim.AddForecast(TestHelpers.Euribor3M);

            var currencyPairs = new[] { TestHelpers.USDZAR, TestHelpers.EURZAR };
            var spots         = new[] { 13.6, 15.0 };
            var vols          = new[] { 0.15, 0.15 };
            var correlations  = new[, ]
            {
                { 1.0, 0.0 },
                { 0.0, 1.0 }
            };
            var model = new MultiHWAndFXToy(valueDate, TestHelpers.ZAR, new[] { zarRatesSim, usdRatesSim, eurRatesSim },
                                            currencyPairs, spots, vols, correlations);

            var portfolio = new List <IProduct>
            {
                CreateFloatingLeg(TestHelpers.ZAR, valueDate, -15e6, TestHelpers.Jibar3M, 7),
                CreateFloatingLeg(TestHelpers.EUR, valueDate, +1e6, TestHelpers.Euribor3M, 7),
                CreateFloatingLeg(TestHelpers.ZAR, valueDate, 13e6, TestHelpers.Jibar3M, 13),
                CreateFloatingLeg(TestHelpers.USD, valueDate, -1e6, TestHelpers.Euribor3M, 13),
                TestHelpers.CreateZARSwap(0.07, true, 20e6, valueDate, Tenor.FromYears(4), TestHelpers.Jibar3M)
            };

            var stepInMonths  = 1;
            var fwdValueDates = Enumerable.Range(1, 13 * 12 / stepInMonths)
                                .Select(i => valueDate.AddMonths(stepInMonths * i)).ToArray();
            var coord = new Coordinator(model, new List <Simulator>(), 1000);
            //coord.SetThreadedness(false);
            var epe = coord.EPE(portfolio.ToArray(), valueDate, fwdValueDates);

            Assert.AreEqual(1489695, epe[0], 5000);
            Assert.AreEqual(2194183, epe[87], 5000);
            Assert.AreEqual(0, epe[155], 5);
            //QuantSA.Shared.Debug.Debug.WriteToFile("c:\\dev\\quantsa\\temp\\epeTest_singlethread_10000.csv", epe);
        }
Example #16
0
        private async void PreviousButton_Clicked(object sender, EventArgs e)
        {
            eventsView.Children.Clear();

            Date = Date.AddMonths(-1);

            var offset = Width + 50;
            var rect   = calendarGrid.Bounds.Offset(offset, calendarGrid.Bounds.Y);
            await calendarGrid.LayoutTo(rect, animationTimeout, Easing.CubicOut);

            FillGrid();

            rect = calendarGrid.Bounds.Offset(-offset * 2, calendarGrid.Bounds.Y);
            await calendarGrid.LayoutTo(rect, 50, Easing.CubicIn);

            rect = calendarGrid.Bounds.Offset(offset, calendarGrid.Bounds.Y);
            await calendarGrid.LayoutTo(rect, animationTimeout, Easing.CubicOut);

            OnDateChanged.Invoke(this, EventArgs.Empty);
        }
Example #17
0
        public void TestValuationCoordinator()
        {
            Date    exerciseDate = new Date(2017, 08, 28);
            string  shareCode    = "AAA";
            double  strike       = 100.0;
            Product p            = new EuropeanOption(new Share(shareCode, Currency.ZAR), strike, exerciseDate);

            Share[] shares    = new Share[] { new Share(shareCode, Currency.ZAR) };// One needs to know the index that will be required by the product to simulate it.
            Date    valueDate = new Date(2016, 08, 28);

            double[] divYield  = new double[] { 0.02 };
            double[] vol       = new double[] { 0.22 };
            double[] spotPrice = new double[] { 100.0 };
            double[,] correlations = new double[, ] {
                { 1.0 }
            };
            IDiscountingSource discountCurve = new DatesAndRates(Currency.ZAR, valueDate,
                                                                 new Date[] { valueDate, valueDate.AddMonths(120) },
                                                                 new double[] { 0.07, 0.07 });

            IFloatingRateSource[] rateForecastCurves = new IFloatingRateSource[0];

            EquitySimulator sim = new EquitySimulator(shares, spotPrice, vol, divYield,
                                                      correlations, discountCurve, rateForecastCurves);

            Coordinator coordinator = new Coordinator(sim, new List <Simulator>(), 10000);
            double      value       = coordinator.Value(new Product[] { p }, valueDate);
            double      refValue    = Formulae.BlackScholes(PutOrCall.Call, strike, (exerciseDate - valueDate) / 365.0, spotPrice[0],
                                                            vol[0], 0.07, divYield[0]);

            Assert.AreEqual(refValue, value, refValue * 0.05);
        }
Example #18
0
        // return the last day of month
        public static Date LastDayOfMonth(Date myDate)
        {
            Date FD = FirstDayOfMonth(myDate);

            return(FD.AddMonths(1).AddDays(-1));
        }
Example #19
0
 /// <summary>
 /// 加n月
 /// </summary>
 /// <returns></returns>
 public ChineseCalendar AddMonths(int months)
 {
     return(new ChineseCalendar(Date.AddMonths(months)));
 }
        public void TestProductWrapperEquityValuation()
        {
            Product product1 = new ProductWrapperEquitySample1();
            Product product2 = new ProductWrapperEquitySample2();

            // The model
            Date anchorDate = new Date(2016, 09, 30);

            Share[]  shares    = new Share[] { new Share("ALSI", Currency.ZAR), new Share("AAA", Currency.ZAR), new Share("BBB", Currency.ZAR) };
            double[] prices    = { 200, 50, 100 };
            double[] vols      = { 0.22, 0.52, 0.4 };
            double[] divYields = { 0.03, 0.0, 0.0 };
            double[,] correlations = { { 1.0, 0.5, 0.5 },
                                       { 0.5, 1.0, 0.5 },
                                       { 0.5, 0.5, 1.0 } };
            IDiscountingSource discountCurve = new DatesAndRates(Currency.ZAR, anchorDate,
                                                                 new Date[] { anchorDate, anchorDate.AddMonths(36) },
                                                                 new double[] { 0.07, 0.07 });
            EquitySimulator sim         = new EquitySimulator(shares, prices, vols, divYields, correlations, discountCurve, new IFloatingRateSource[0]);
            Coordinator     coordinator = new Coordinator(sim, new List <Simulator> {
            }, 40000);

            //Valuation
            double value1 = coordinator.Value(new Product[] { product1 }, anchorDate);
            double value2 = coordinator.Value(new Product[] { product2 }, anchorDate);

            Assert.AreEqual(value1, value2, value1 * 0.05);
        }
Example #21
0
        private void DetermineWhen(ref LexerToken tok, ref DateSpecifier specifier)
        {
            Date today = TimesCommon.Current.CurrentDate;

            specifier = specifier ?? new DateSpecifier();

            switch (tok.Kind)
            {
            case LexerTokenKindEnum.TOK_DATE:
                specifier = tok.Value.GetValue <DateSpecifier>();
                break;

            case LexerTokenKindEnum.TOK_INT:
            {
                int amount = tok.Value.GetValue <int>();
                int adjust = 0;

                tok = Lexer.PeekToken();
                LexerTokenKindEnum kind = tok.Kind;
                switch (kind)
                {
                case LexerTokenKindEnum.TOK_YEAR:
                case LexerTokenKindEnum.TOK_YEARS:
                case LexerTokenKindEnum.TOK_QUARTER:
                case LexerTokenKindEnum.TOK_QUARTERS:
                case LexerTokenKindEnum.TOK_MONTH:
                case LexerTokenKindEnum.TOK_MONTHS:
                case LexerTokenKindEnum.TOK_WEEK:
                case LexerTokenKindEnum.TOK_WEEKS:
                case LexerTokenKindEnum.TOK_DAY:
                case LexerTokenKindEnum.TOK_DAYS:
                    Lexer.NextToken();
                    tok = Lexer.NextToken();
                    switch (tok.Kind)
                    {
                    case LexerTokenKindEnum.TOK_AGO:
                        adjust = -1;
                        break;

                    case LexerTokenKindEnum.TOK_HENCE:
                        adjust = 1;
                        break;

                    default:
                        tok.Unexpected();
                        break;
                    }
                    break;

                default:
                    break;
                }

                Date when = today;

                switch (kind)
                {
                case LexerTokenKindEnum.TOK_YEAR:
                case LexerTokenKindEnum.TOK_YEARS:
                    when = when.AddYears(amount * adjust);
                    break;

                case LexerTokenKindEnum.TOK_QUARTER:
                case LexerTokenKindEnum.TOK_QUARTERS:
                    when = when.AddMonths(amount * 3 * adjust);
                    break;

                case LexerTokenKindEnum.TOK_MONTH:
                case LexerTokenKindEnum.TOK_MONTHS:
                    when = when.AddMonths(amount * adjust);
                    break;

                case LexerTokenKindEnum.TOK_WEEK:
                case LexerTokenKindEnum.TOK_WEEKS:
                    when = when.AddDays(amount * 7 * adjust);
                    break;

                case LexerTokenKindEnum.TOK_DAY:
                case LexerTokenKindEnum.TOK_DAYS:
                    when = when.AddDays(amount * adjust);
                    break;

                default:
                    if (amount > 31)
                    {
                        specifier.Year = amount;
                    }
                    else
                    {
                        specifier.Day = amount;
                    }
                    break;
                }

                if (adjust != 0)
                {
                    specifier = new DateSpecifier(when);
                }
                break;
            }

            case LexerTokenKindEnum.TOK_THIS:
            case LexerTokenKindEnum.TOK_NEXT:
            case LexerTokenKindEnum.TOK_LAST:
            {
                int adjust = 0;
                if (tok.Kind == LexerTokenKindEnum.TOK_NEXT)
                {
                    adjust = 1;
                }
                else if (tok.Kind == LexerTokenKindEnum.TOK_LAST)
                {
                    adjust = -1;
                }

                tok = Lexer.NextToken();
                switch (tok.Kind)
                {
                case LexerTokenKindEnum.TOK_A_MONTH:
                {
                    Date temp = new Date(today.Year, tok.Value.GetValue <int>(), 1);
                    temp      = temp.AddYears(adjust);
                    specifier = new DateSpecifier(temp.Year, (MonthEnum)temp.Month);
                    break;
                }

                case LexerTokenKindEnum.TOK_A_WDAY:
                {
                    Date temp = DateDuration.FindNearest(today, SkipQuantumEnum.WEEKS);
                    while (temp.DayOfWeek != tok.Value.GetValue <DayOfWeek>())
                    {
                        temp = temp.AddDays(1);
                    }
                    temp      = temp.AddDays(7 * adjust);
                    specifier = new DateSpecifier(temp);
                    break;
                }

                case LexerTokenKindEnum.TOK_YEAR:
                {
                    Date temp = today;
                    temp      = temp.AddYears(adjust);
                    specifier = new DateSpecifier(temp.Year);
                    break;
                }

                case LexerTokenKindEnum.TOK_QUARTER:
                {
                    Date baseDate = DateDuration.FindNearest(today, SkipQuantumEnum.QUARTERS);
                    Date temp     = default(Date);
                    if (adjust < 0)
                    {
                        temp = baseDate.AddMonths(3 * adjust);
                    }
                    else if (adjust == 0)
                    {
                        temp = baseDate.AddMonths(3);
                    }
                    else if (adjust > 0)
                    {
                        baseDate = baseDate.AddMonths(3 * adjust);
                        temp     = baseDate.AddMonths(3 * adjust);
                    }
                    specifier = new DateSpecifier(adjust < 0 ? temp : baseDate);
                    break;
                }

                case LexerTokenKindEnum.TOK_WEEK:
                {
                    Date baseDate = DateDuration.FindNearest(today, SkipQuantumEnum.WEEKS);
                    Date temp     = default(Date);
                    if (adjust < 0)
                    {
                        temp = baseDate.AddDays(7 * adjust);
                    }
                    else if (adjust == 0)
                    {
                        temp = baseDate.AddDays(7);
                    }
                    else if (adjust > 0)
                    {
                        baseDate = baseDate.AddDays(7 * adjust);
                        temp     = baseDate.AddDays(7 * adjust);
                    }
                    specifier = new DateSpecifier(adjust < 0 ? temp : baseDate);
                    break;
                }

                case LexerTokenKindEnum.TOK_DAY:
                {
                    Date temp = today;
                    temp      = temp.AddDays(adjust);
                    specifier = new DateSpecifier(temp);
                    break;
                }

                case LexerTokenKindEnum.TOK_MONTH:
                default:
                {
                    Date temp = today;
                    temp      = temp.AddMonths(adjust);
                    specifier = new DateSpecifier(temp.Year, (MonthEnum)temp.Month);
                    break;
                }
                }
                break;
            }

            case LexerTokenKindEnum.TOK_A_MONTH:
                specifier.Month = tok.Value.GetValue <MonthEnum>();
                tok             = Lexer.PeekToken();
                switch (tok.Kind)
                {
                case LexerTokenKindEnum.TOK_INT:
                    specifier.Year = tok.Value.GetValue <int>();
                    break;

                case LexerTokenKindEnum.END_REACHED:
                    break;

                default:
                    break;
                }
                break;

            case LexerTokenKindEnum.TOK_A_WDAY:
                specifier.WDay = tok.Value.GetValue <DayOfWeek>();
                break;

            case LexerTokenKindEnum.TOK_TODAY:
                specifier = new DateSpecifier(today);
                break;

            case LexerTokenKindEnum.TOK_TOMORROW:
                specifier = new DateSpecifier(today.AddDays(1));
                break;

            case LexerTokenKindEnum.TOK_YESTERDAY:
                specifier = new DateSpecifier(today.AddDays(-1));
                break;

            default:
                tok.Unexpected();
                break;
            }
        }
Example #22
0
 public static void Test_CalculatePrintNumber_02(Print print, string directory, Date date, int nb)
 {
     string traceFile = zPath.Combine(zPath.Combine(directory, @"Print\CalculatePrintDateNumber"), string.Format("Print_{0}_Number.txt", print.Name));
     Trace.WriteLine("print {0} frequency {1} calculate number from date {2:dd-MM-yyyy} nb {3} trace file \"{4}\"", print.Name, print.Frequency, date, nb, zPath.GetFileName(traceFile));
     //Trace.CurrentTrace.DisableBaseLog();
     //Trace.CurrentTrace.DisableTraceView = true;
     //Trace.CurrentTrace.AddTraceFile(traceFile, LogOptions.RazLogFile);
     Trace.CurrentTrace.AddOnWrite("Test_CalculatePrintNumber_02", WriteToFile.Create(traceFile, FileOption.RazFile).Write);
     try
     {
         Trace.WriteLine("print {0} frequency {1} calculate number from date {2:dd-MM-yyyy} nb {3}", print.Name, print.Frequency, date, nb);
         Trace.WriteLine();
         if (print.Frequency == PrintFrequency.Daily)
         {
             for (int i = 0; i < nb; i++)
             {
                 PrintIssue issue = print.NewPrintIssue(date);
                 int number = issue.PrintNumber;
                 Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                 date = date.AddDays(1);
             }
         }
         else if (print.Frequency == PrintFrequency.Weekly)
         {
             for (int i = 0; i < nb; i++)
             {
                 PrintIssue issue = print.NewPrintIssue(date);
                 int number = issue.PrintNumber;
                 Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                 date = date.AddDays(7);
             }
         }
         else if (print.Frequency == PrintFrequency.Monthly)
         {
             for (int i = 0; i < nb; i++)
             {
                 PrintIssue issue = print.NewPrintIssue(date);
                 int number = issue.PrintNumber;
                 Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                 date = date.AddMonths(1);
             }
         }
         else if (print.Frequency == PrintFrequency.Bimonthly || print.Frequency == PrintFrequency.Quarterly)
         {
             int lastNumber = 0;
             for (int i = 0; i < nb; )
             {
                 PrintIssue issue = print.NewPrintIssue(date);
                 int number = issue.PrintNumber;
                 if (number != lastNumber)
                 {
                     Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                     lastNumber = number;
                     i++;
                 }
                 date = date.AddMonths(1);
             }
         }
     }
     finally
     {
         //Trace.CurrentTrace.EnableBaseLog();
         //Trace.CurrentTrace.RemoveTraceFile(traceFile);
         Trace.CurrentTrace.RemoveOnWrite("Test_CalculatePrintNumber_02");
         Trace.CurrentTrace.DisableViewer = false;
     }
 }
Example #23
0
        public void TestIndexOnlyProvidedOnce()
        {
            Date    exerciseDate = new Date(2017, 08, 28);
            string  shareCode    = "AAA";
            double  strike       = 100.0;
            Product p            = new EuropeanOption(new Share(shareCode, Currency.ZAR), strike, exerciseDate);

            Share[] shares    = new Share[] { new Share("AAA", Currency.ZAR) };// One needs to know the index that will be required by the product to simulate it.
            Date    valueDate = new Date(2016, 08, 28);

            double[] divYield  = new double[] { 0.02 };
            double[] vol       = new double[] { 0.22 };
            double[] spotPrice = new double[] { 100.0 };
            double[,] correlations = new double[, ] {
                { 1.0 }
            };
            IDiscountingSource discountCurve = new DatesAndRates(Currency.ZAR, valueDate,
                                                                 new Date[] { valueDate, valueDate.AddMonths(120) },
                                                                 new double[] { 0.07, 0.07 });

            IFloatingRateSource[] rateForecastCurves = new IFloatingRateSource[0];

            EquitySimulator sim = new EquitySimulator(shares, spotPrice, vol, divYield,
                                                      correlations, discountCurve, rateForecastCurves);

            Coordinator coordinator = new Coordinator(sim, new List <Simulator>()
            {
                sim
            }, 1000);

            double value = coordinator.Value(new Product[] { p }, valueDate);
        }
Example #24
0
 public void CanAddPositiveMonths()
 {
     var dt = new Date(2000, 1, 1);
     var actual = dt.AddMonths(1);
     var expected = new Date(2000, 2, 1);
     Assert.Equal(expected, actual);
 }
Example #25
0
 public void CanAddPositiveMonths_FromDay31_ToDay29()
 {
     var dt = new Date(2000, 1, 31);
     var actual = dt.AddMonths(1);
     var expected = new Date(2000, 2, 29);
     Assert.Equal(expected, actual);
 }
Example #26
0
        private FloatLeg CreateFloatingLeg(Currency ccy, Date startDate, double notional, FloatingIndex index, int tenorYears)
        {
            int quarters = tenorYears * 4;

            Date[]          paymentDates     = Enumerable.Range(1, quarters).Select(i => startDate.AddMonths(3 * i)).ToArray();
            Date[]          resetDates       = Enumerable.Range(0, quarters).Select(i => startDate.AddMonths(3 * i)).ToArray();
            double[]        notionals        = Vector.Ones(quarters).Multiply(notional);
            double[]        spreads          = Vector.Zeros(quarters);
            double[]        accrualFractions = Vector.Ones(quarters).Multiply(0.25);
            FloatingIndex[] floatingIndices  = Enumerable.Range(1, quarters).Select(i => index).ToArray();
            FloatLeg        leg = new FloatLeg(ccy, paymentDates, notionals, resetDates, floatingIndices, spreads, accrualFractions);

            return(leg);
        }
Example #27
0
 // Calculate the final repay date of stir
 private void CalcNotionalRepayDate()
 {
     NotionalRepayDate = IMMDate.AddMonths(3);
 }
 /// <summary>
 /// Helper function to make a depo
 /// </summary>
 private Product MakeDepo(Date anchorDate, double rate, int months)
 {
     return(new CashLeg(new Date[] { anchorDate, anchorDate.AddMonths(months) },
                        new double[] { -1.0, 1.0 * (1 + rate * months / 12.0) },
                        new Currency[] { Currency.ZAR, Currency.ZAR }));
 }
Example #29
0
        public void TestMultiHWAndFXToyCCIRSAltConstructor()
        {
            var valueDate = new Date(2016, 9, 17);
            var spots     = new List <double> {
                13.6, 15.0
            };
            var vols = new List <double> {
                0.15, 0.15
            };
            var correlations = new[, ]
            {
                { 1.0, 0.0 },
                { 0.0, 1.0 }
            };
            // ZAR HW specs
            IDiscountingSource zarCurve = new DatesAndRates(Currency.ZAR, valueDate,
                                                            new[] { valueDate, valueDate.AddMonths(240) },
                                                            new[] { 0.07, 0.07 });
            var zarHWParams = new HWParams {
                vol = 0.01, meanReversionSpeed = 0.05
            };
            var zarRequiredIndices = new List <FloatingIndex> {
                FloatingIndex.JIBAR3M
            };

            // Lists to be populated for other currencies
            var otherCcys               = new List <Currency>();
            var otherCcyCurves          = new List <IDiscountingSource>();
            var otherCcyHwParams        = new List <HWParams>();
            var otherCcyRequiredIndices = new List <List <FloatingIndex> >();

            // USD HW specs
            otherCcys.Add(Currency.USD);
            otherCcyCurves.Add(new DatesAndRates(Currency.USD, valueDate, new[] { valueDate, valueDate.AddMonths(240) },
                                                 new[] { 0.01, 0.01 }));
            otherCcyHwParams.Add(new HWParams {
                vol = 0.01, meanReversionSpeed = 0.05
            });
            otherCcyRequiredIndices.Add(new List <FloatingIndex> {
                FloatingIndex.LIBOR3M
            });

            // EUR HW specs
            otherCcys.Add(Currency.EUR);
            otherCcyCurves.Add(new DatesAndRates(Currency.EUR, valueDate, new[] { valueDate, valueDate.AddMonths(240) },
                                                 new[] { 0.005, 0.005 }));
            otherCcyHwParams.Add(new HWParams {
                vol = 0.01, meanReversionSpeed = 0.05
            });
            otherCcyRequiredIndices.Add(new List <FloatingIndex> {
                FloatingIndex.EURIBOR3M
            });

            // Construct the model
            var model = new MultiHWAndFXToy(valueDate, zarCurve, zarRequiredIndices, zarHWParams,
                                            otherCcys, spots, vols, otherCcyCurves, otherCcyRequiredIndices, otherCcyHwParams, correlations);

            var portfolio = new List <Product>();

            portfolio.Add(CreateFloatingLeg(Currency.ZAR, valueDate, -15e6, FloatingIndex.JIBAR3M, 7));
            portfolio.Add(CreateFloatingLeg(Currency.EUR, valueDate, +1e6, FloatingIndex.EURIBOR3M, 7));
            portfolio.Add(CreateFloatingLeg(Currency.ZAR, valueDate, 13e6, FloatingIndex.JIBAR3M, 13));
            portfolio.Add(CreateFloatingLeg(Currency.USD, valueDate, -1e6, FloatingIndex.EURIBOR3M, 13));
            portfolio.Add(IRSwap.CreateZARSwap(0.07, true, 20e6, valueDate, Tenor.Years(4)));

            var stepInMonths  = 1;
            var fwdValueDates = Enumerable.Range(1, 13 * 12 / stepInMonths)
                                .Select(i => valueDate.AddMonths(stepInMonths * i)).ToArray();
            var coord = new Coordinator(model, new List <Simulator>(), 1000);
            //coord.SetThreadedness(false);
            var epe = coord.EPE(portfolio.ToArray(), valueDate, fwdValueDates);

            Assert.AreEqual(1555002, epe[0], 5000);
            Assert.AreEqual(2170370, epe[87], 5000);
            Assert.AreEqual(0, epe[155], 5);

            //Debug.WriteToFile("c:\\dev\\quantsa\\temp\\epeTest_2.csv", epe);
        }
Example #30
0
        /// <summary>
        /// This routine finds the average of the index and the volatility between PaymentStart and PaymentEnd.
        /// AveFrequency determines the daily averaging frequency
        /// e.g.AveFrequency =  1 finds average of daily values;
        /// AveFrequency =  7 finds average of weekly values etc.
        /// PaymentEnd is not included in the averaging calculation.
        /// It is assumed that PaymentStart and PaymentEnd have already been adjusted to be business days
        /// Each AverageDate is calculated by adding on the correct number of business days
        /// PaymentRateSet is the sum of the rates that have already been fixed in the period.
        /// This is added onto the sum of the forward rates and the average calculated by dividing
        /// the total sum by the number of averaging points in the period
        /// Holidays:	Index Start is appropriate working day for the Average Date
        ///             Index Set is two working days prior to this Index Start
        ///             Index End is the appropriate working day following addition of the tenor
        /// </summary>
        /// <param name="valueDate"></param>
        /// <param name="discountCurve"></param>
        /// <param name="indexCurve"></param>
        /// <param name="paymentStart"></param>
        /// <param name="paymentEnd"></param>
        /// <param name="indexDaycount"></param>
        /// <param name="indexTenor"></param>
        /// <param name="indexCoupon"></param>
        /// <param name="paymentRateSet"></param>
        /// <param name="indexRateSet"></param>
        /// <param name="averagingFrequency"></param>
        /// <param name="averagePreset"></param>
        /// <param name="indexCity"></param>
        /// <param name="convention"></param>
        /// <param name="volatilityMargin"></param>
        /// <param name="indexVolatility"></param>
        /// <returns></returns>
        public static Double? GetAverageRate(DateTime valueDate, IRateCurve discountCurve,
            IRateCurve indexCurve, DateTime paymentStart, DateTime paymentEnd, int indexDaycount, int indexTenor, int indexCoupon,
            double paymentRateSet, double indexRateSet, int averagingFrequency,
            int averagePreset, long indexCity, int convention, double volatilityMargin,
            IVolatilitySurface indexVolatility)
        {
            long indexSet, indexStart, indexEnd;
            double sumRate = 0.0;
            double sumVol = 0.0;
            double firstVol = 0.0;
            var averageDate = paymentStart;
            int numAvePoints = 0;
            if (indexCurve is null)
                return null;
            //Do simple approximation i.e. divide the sum of the start and end values by two 
            if (averagingFrequency <= 0)
            {

                DateTime Ave_Index_Start, Ave_Index_End;
                //Calculate the fixing date for the start date of the period
                long firstSet = AddWorkDays(PaymentStart, Ave_Preset, Index_City, CHoliday::PRECEEDING);
                //Calculate the fixing date for the end date of the period
                long lastSet = AddWorkDays(PaymentEnd, Ave_Preset, Index_City, CHoliday::PRECEEDING);
                if (valueDate >= lastSet)
                {
                    IndexVolatility = 0.0;
                    return Payment_Rateset / 2.0; //Both the start and the end rates have been fixed
                }

                double firstRate;
                if (valueDate < firstSet)
                {
                    Index_Start = PaymentStart;
                    Date Ave_Index_Start = Index_Start;
                    Date Ave_Index_End = Ave_Index_Start.AddMonths(ConvertToMonths(Index_Tenor));
                    Index_End = GoodDay(Ave_Index_End.GetJulian(), Index_City, Convention);
                    long Index_Tenor_Days = (long) (Index_End - Index_Start);
                    long IndexExpiry = (long) (firstSet - Value_Date);

                    firstRate = _GetIndex(Value_Date, firstSet, Index_Start, Index_End, Index_Tenor,
                        Index_Daycount, Index_Coupon, Index_Coupon, *pIndexCurve, Index_Rateset);
                    // SAJ 25/9/96  Added Volatility margin to volatility to allow for bumping
                    firstVol = GetVolatility(CapsVolName, SwaptVolName, IndexExpiry, Index_Tenor_Days, 0.0) +
                               VolatilityMargin;
                    // SAJ 25/9/96	Added following lines for convexity effect
                    double Weight, AdjForward;
                    GetModifiedForward(Value_Date, PaymentEnd, firstSet, Index_Start, Index_End,
                        Index_Tenor, Index_Coupon, Index_Daycount,
                        *pIndexCurve, firstRate, firstVol, Weight, AdjForward);
                    firstRate = Weight * firstRate + (1 - Weight) * AdjForward;
                    // SAJ 25/9/96 End
                }
                else
                {
                    firstRate = Payment_Rateset;
                    firstVol = 0.0;
                }

                Index_Start = PaymentEnd;
                Ave_Index_Start = Index_Start;
                Ave_Index_End = Ave_Index_Start.AddMonths(ConvertToMonths(Index_Tenor));
                Index_End = GoodDay(Ave_Index_End.GetJulian(), Index_City, Convention);
                long Index_Tenor_Days = (long) (Index_End - Index_Start);
                long IndexExpiry = (long) (lastSet - Value_Date);
                double lastRate = _GetIndex(Value_Date, lastSet, Index_Start, Index_End, Index_Tenor,
                    Index_Daycount, Index_Coupon, Index_Coupon, *pIndexCurve, Index_Rateset);
                // SAJ 25/9/96  Added Volatility margin to volatility to allow for bumping
                double LastVol = GetVolatility(CapsVolName, SwaptVolName, IndexExpiry, Index_Tenor_Days, 0.0) +
                                 VolatilityMargin;
                // SAJ 25/9/96	Added following lines for convexity effect
                double Weight, AdjForward;
                GetModifiedForward(Value_Date, PaymentEnd, lastSet, Index_Start, Index_End,
                    Index_Tenor, Index_Coupon, Index_Daycount,
                    *pIndexCurve, lastRate, LastVol, Weight, AdjForward);
                lastRate = Weight * lastRate + (1 - Weight) * AdjForward;
                // SAJ 25/9/96 End
                IndexVolatility = (firstVol + LastVol) / 2.0 + VolatilityMargin;
                return (firstRate + lastRate) / 2.0;
            }

            //Check if already into the averaging loop or the period is historical
            if (valueDate > PaymentStart)
            {
                sumRate = Payment_Rateset;
                sumVol = 0.0;
            }

            //Begin the averaging loop
            while (averageDate < PaymentEnd)
            {
                //Calculate the index setting date
                Index_Set = AddWorkDays(AverageDate, Ave_Preset, Index_City, CHoliday::PRECEEDING);
                if (Value_Date < Index_Set)
                {
                    Date Ave_Index_Start = AverageDate;
                    Date Ave_Index_End = Ave_Index_Start.AddMonths(ConvertToMonths(Index_Tenor));
                    Index_End = GoodDay(Ave_Index_End.GetJulian(), Index_City, Convention);
                    long Index_Tenor_Days = (long) (Index_End - AverageDate);
                    long IndexExpiry = (long) (Index_Set - Value_Date);
                    double NewRate = _GetIndex(Value_Date, Index_Set, AverageDate, Index_End, Index_Tenor,
                        Index_Daycount, Index_Coupon, Index_Coupon, *pIndexCurve, Index_Rateset);

                    // SAJ 25/9/96  Added Volatility margin to volatility to allow for bumping
                    double newVol = GetVolatility(CapsVolName, SwaptVolName, IndexExpiry, Index_Tenor_Days, 0.0) +
                                    VolatilityMargin;

                    // SAJ 25/9/96	Added following lines for convexity effect
                    double weight, adjForward;
                    GetModifiedForward(Value_Date, PaymentEnd, Index_Set, AverageDate, Index_End,
                        Index_Tenor, Index_Coupon, Index_Daycount,
                        *pIndexCurve, NewRate, newVol, weight, adjForward);
                    NewRate = weight * NewRate + (1 - weight) * adjForward;
                    // SAJ 25/9/96 End
                    sumRate += NewRate;
                    sumVol += (newVol * newVol);
                }

                numAvePoints++;
                // Increment average date by the averaging frequency
                // Here should make the convention Following otherwise will not get out of the end of the month
                // SAJ 25/9/96 Changed the following line to add AveFrequency days and then check good days
                //	    AverageDate = AddWorkDays(AverageDate, AveFrequency, Index_City, CHoliday::FOLLOWING);
                averageDate += AveFrequency;
                averageDate =
                    GoodDay(AverageDate, Index_City, CHoliday::FOLLOWING); // Use following to prevent chattering
                // SAJ 25/9/96 End
            }

            IndexVolatility = Math.Sqrt(sumVol / numAvePoints) + volatilityMargin;
            return sumRate / numAvePoints;
        }
        public void TestDynamicCallFromFile()
        {
            Stopwatch watch;
            // Make a product at runtime
            Product runtimeProduct = RuntimeProduct.CreateFromSourceFile(@"ScriptEuropeanOption.txt");

            // Setup an approriate simulation
            Share[] shares    = new Share[] { new Share("AAA", Currency.ZAR) };// One needs to know the index that will be required by the product to simulate it.
            Date    valueDate = new Date(2016, 08, 28);

            double[] divYield  = new double[] { 0.02 };
            double[] vol       = new double[] { 0.22 };
            double[] spotPrice = new double[] { 100.0 };
            double[,] correlations = new double[, ] {
                { 1.0 }
            };
            IDiscountingSource discountCurve = new DatesAndRates(Currency.ZAR, valueDate,
                                                                 new Date[] { valueDate, valueDate.AddMonths(120) },
                                                                 new double[] { 0.07, 0.07 });

            IFloatingRateSource[] rateForecastCurves = new IFloatingRateSource[0];

            EquitySimulator sim = new EquitySimulator(shares, spotPrice, vol, divYield,
                                                      correlations, discountCurve, rateForecastCurves);

            // Value the runtime product
            Coordinator coordinator;

            coordinator = new Coordinator(sim, new List <Simulator>(), 100000);
            watch       = Stopwatch.StartNew();
            double valueRuntime = coordinator.Value(new Product[] { runtimeProduct }, valueDate);

            watch.Stop();
            long timeRuntime = watch.ElapsedMilliseconds;

            // Setup the same product statically
            Date    exerciseDate  = new Date(2017, 08, 28);
            double  strike        = 100.0;
            Product staticProduct = new EuropeanOption(new Share("AAA", Currency.ZAR), strike, exerciseDate);

            // Value the static product
            coordinator = new Coordinator(sim, new List <Simulator> (), 100000);
            watch       = Stopwatch.StartNew();
            double valueStatic = coordinator.Value(new Product[] { staticProduct }, valueDate);

            watch.Stop();
            long timeStatic = watch.ElapsedMilliseconds;

            double refValue = Formulae.BlackScholes(PutOrCall.Call, strike, (exerciseDate - valueDate) / 365, spotPrice[0],
                                                    vol[0], 0.07, divYield[0]);

            Assert.AreEqual(refValue, valueRuntime, refValue * 0.03);
            Assert.AreEqual(refValue, valueStatic, refValue * 0.03);
        }
Example #32
0
        /// <summary>
        /// Ported from date_parser_t::parse()
        /// </summary>
        public DateInterval Parse()
        {
            DateSpecifier sinceSpecifier     = null;
            DateSpecifier untilSpecifier     = null;
            DateSpecifier inclusionSpecifier = null;

            DateInterval period       = new DateInterval();
            Date         today        = TimesCommon.Current.CurrentDate;
            bool         endInclusive = false;

            for (LexerToken tok = Lexer.NextToken(); tok.Kind != LexerTokenKindEnum.END_REACHED; tok = Lexer.NextToken())
            {
                switch (tok.Kind)
                {
                case LexerTokenKindEnum.TOK_DATE:
                case LexerTokenKindEnum.TOK_INT:
                case LexerTokenKindEnum.TOK_A_MONTH:
                case LexerTokenKindEnum.TOK_A_WDAY:
                    DetermineWhen(ref tok, ref inclusionSpecifier);
                    break;

                case LexerTokenKindEnum.TOK_DASH:
                    if (inclusionSpecifier != null)
                    {
                        sinceSpecifier     = inclusionSpecifier;
                        inclusionSpecifier = null;
                        tok = Lexer.NextToken();
                        DetermineWhen(ref tok, ref untilSpecifier);

                        // The dash operator is special: it has an _inclusive_ end.
                        endInclusive = true;
                    }
                    else
                    {
                        tok.Unexpected();
                    }
                    break;

                case LexerTokenKindEnum.TOK_SINCE:
                    if (sinceSpecifier != null)
                    {
                        tok.Unexpected();
                    }
                    else
                    {
                        tok = Lexer.NextToken();
                        DetermineWhen(ref tok, ref sinceSpecifier);
                    }
                    break;

                case LexerTokenKindEnum.TOK_UNTIL:
                    if (untilSpecifier != null)
                    {
                        tok.Unexpected();
                    }
                    else
                    {
                        tok = Lexer.NextToken();
                        DetermineWhen(ref tok, ref untilSpecifier);
                    }
                    break;

                case LexerTokenKindEnum.TOK_IN:
                    if (inclusionSpecifier != null)
                    {
                        tok.Unexpected();
                    }
                    else
                    {
                        tok = Lexer.NextToken();
                        DetermineWhen(ref tok, ref inclusionSpecifier);
                    }
                    break;

                case LexerTokenKindEnum.TOK_THIS:
                case LexerTokenKindEnum.TOK_NEXT:
                case LexerTokenKindEnum.TOK_LAST:
                {
                    int adjust = 0;
                    if (tok.Kind == LexerTokenKindEnum.TOK_NEXT)
                    {
                        adjust = 1;
                    }
                    else if (tok.Kind == LexerTokenKindEnum.TOK_LAST)
                    {
                        adjust = -1;
                    }

                    tok = Lexer.NextToken();
                    switch (tok.Kind)
                    {
                    case LexerTokenKindEnum.TOK_INT:
                    {
                        int amount = tok.Value.GetValue <int>();

                        Date baseDate = today;
                        Date end      = today;

                        if (adjust == 0)
                        {
                            adjust = 1;
                        }

                        tok = Lexer.NextToken();
                        switch (tok.Kind)
                        {
                        case LexerTokenKindEnum.TOK_YEARS:
                            baseDate = baseDate.AddYears(amount * adjust);
                            break;

                        case LexerTokenKindEnum.TOK_QUARTERS:
                            baseDate = baseDate.AddMonths(amount * adjust * 3);
                            break;

                        case LexerTokenKindEnum.TOK_MONTHS:
                            baseDate = baseDate.AddMonths(amount * adjust);
                            break;

                        case LexerTokenKindEnum.TOK_WEEKS:
                            baseDate = baseDate.AddDays(amount * adjust * 7);
                            break;

                        case LexerTokenKindEnum.TOK_DAYS:
                            baseDate = baseDate.AddDays(amount * adjust);
                            break;

                        default:
                            tok.Unexpected();
                            break;
                        }

                        if (adjust > 0)
                        {
                            Date temp = baseDate;
                            baseDate = end;
                            end      = temp;
                        }

                        sinceSpecifier = new DateSpecifier(baseDate);
                        untilSpecifier = new DateSpecifier(end);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_A_MONTH:
                    {
                        DetermineWhen(ref tok, ref inclusionSpecifier);

                        Date temp = new Date(today.Year, (int)inclusionSpecifier.Month, 1);
                        temp = temp.AddYears(adjust);
                        inclusionSpecifier = new DateSpecifier(temp.Year, (MonthEnum)temp.Month);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_A_WDAY:
                    {
                        DetermineWhen(ref tok, ref inclusionSpecifier);

                        Date temp = DateDuration.FindNearest(today, SkipQuantumEnum.WEEKS);
                        while (temp.DayOfWeek != inclusionSpecifier.WDay)
                        {
                            temp = temp.AddDays(1);
                        }
                        temp = temp.AddDays(7 * adjust);
                        inclusionSpecifier = new DateSpecifier(temp);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_YEAR:
                    {
                        Date temp = today;
                        temp = temp.AddYears(adjust);
                        inclusionSpecifier = new DateSpecifier(temp.Year);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_QUARTER:
                    {
                        Date baseDate = DateDuration.FindNearest(today, SkipQuantumEnum.QUARTERS);
                        Date temp;
                        if (adjust < 0)
                        {
                            temp = baseDate.AddMonths(3 * adjust);
                        }
                        else if (adjust == 0)
                        {
                            temp = baseDate.AddMonths(3);
                        }
                        else
                        {
                            baseDate = baseDate.AddMonths(3 * adjust);
                            temp     = baseDate.AddMonths(3 * adjust);
                        }
                        sinceSpecifier = new DateSpecifier(adjust < 0 ? temp : baseDate);
                        untilSpecifier = new DateSpecifier(adjust < 0 ? baseDate : temp);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_WEEK:
                    {
                        Date baseDate = DateDuration.FindNearest(today, SkipQuantumEnum.WEEKS);
                        Date temp;
                        if (adjust < 0)
                        {
                            temp = baseDate.AddDays(7 * adjust);
                        }
                        else if (adjust == 0)
                        {
                            temp = baseDate.AddDays(7);
                        }
                        else
                        {
                            baseDate = baseDate.AddDays(7 * adjust);
                            temp     = baseDate.AddDays(7 * adjust);
                        }
                        sinceSpecifier = new DateSpecifier(adjust < 0 ? temp : baseDate);
                        untilSpecifier = new DateSpecifier(adjust < 0 ? baseDate : temp);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_DAY:
                    {
                        Date temp = today;
                        temp = temp.AddDays(adjust);
                        inclusionSpecifier = new DateSpecifier(temp);
                        break;
                    }

                    case LexerTokenKindEnum.TOK_MONTH:
                    default:
                    {
                        Date temp = today;
                        temp = temp.AddMonths(adjust);
                        inclusionSpecifier = new DateSpecifier(temp.Year, (MonthEnum)temp.Month);
                        break;
                    }
                    }
                    break;
                }

                case LexerTokenKindEnum.TOK_TODAY:
                    inclusionSpecifier = new DateSpecifier(today);
                    break;

                case LexerTokenKindEnum.TOK_TOMORROW:
                    inclusionSpecifier = new DateSpecifier(today.AddDays(1));
                    break;

                case LexerTokenKindEnum.TOK_YESTERDAY:
                    inclusionSpecifier = new DateSpecifier(today.AddDays(-1));
                    break;

                case LexerTokenKindEnum.TOK_EVERY:
                    tok = Lexer.NextToken();
                    if (tok.Kind == LexerTokenKindEnum.TOK_INT)
                    {
                        int quantity = tok.Value.GetValue <int>();
                        tok = Lexer.NextToken();
                        switch (tok.Kind)
                        {
                        case LexerTokenKindEnum.TOK_YEARS:
                            period.Duration = new DateDuration(SkipQuantumEnum.YEARS, quantity);
                            break;

                        case LexerTokenKindEnum.TOK_QUARTERS:
                            period.Duration = new DateDuration(SkipQuantumEnum.QUARTERS, quantity);
                            break;

                        case LexerTokenKindEnum.TOK_MONTHS:
                            period.Duration = new DateDuration(SkipQuantumEnum.MONTHS, quantity);
                            break;

                        case LexerTokenKindEnum.TOK_WEEKS:
                            period.Duration = new DateDuration(SkipQuantumEnum.WEEKS, quantity);
                            break;

                        case LexerTokenKindEnum.TOK_DAYS:
                            period.Duration = new DateDuration(SkipQuantumEnum.DAYS, quantity);
                            break;

                        default:
                            tok.Unexpected();
                            break;
                        }
                    }
                    else
                    {
                        switch (tok.Kind)
                        {
                        case LexerTokenKindEnum.TOK_YEAR:
                            period.Duration = new DateDuration(SkipQuantumEnum.YEARS, 1);
                            break;

                        case LexerTokenKindEnum.TOK_QUARTER:
                            period.Duration = new DateDuration(SkipQuantumEnum.QUARTERS, 1);
                            break;

                        case LexerTokenKindEnum.TOK_MONTH:
                            period.Duration = new DateDuration(SkipQuantumEnum.MONTHS, 1);
                            break;

                        case LexerTokenKindEnum.TOK_WEEK:
                            period.Duration = new DateDuration(SkipQuantumEnum.WEEKS, 1);
                            break;

                        case LexerTokenKindEnum.TOK_DAY:
                            period.Duration = new DateDuration(SkipQuantumEnum.DAYS, 1);
                            break;

                        default:
                            tok.Unexpected();
                            break;
                        }
                    }
                    break;

                case LexerTokenKindEnum.TOK_YEARLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.YEARS, 1);
                    break;

                case LexerTokenKindEnum.TOK_QUARTERLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.QUARTERS, 1);
                    break;

                case LexerTokenKindEnum.TOK_BIMONTHLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.MONTHS, 2);
                    break;

                case LexerTokenKindEnum.TOK_MONTHLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.MONTHS, 1);
                    break;

                case LexerTokenKindEnum.TOK_BIWEEKLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.WEEKS, 2);
                    break;

                case LexerTokenKindEnum.TOK_WEEKLY:
                    period.Duration = new DateDuration(SkipQuantumEnum.WEEKS, 1);
                    break;

                case LexerTokenKindEnum.TOK_DAILY:
                    period.Duration = new DateDuration(SkipQuantumEnum.DAYS, 1);
                    break;

                default:
                    tok.Unexpected();
                    break;
                }
            }

            if (sinceSpecifier != null || untilSpecifier != null)
            {
                DateRange range = new DateRange(sinceSpecifier, untilSpecifier)
                {
                    EndExclusive = endInclusive
                };
                period.Range = new DateSpecifierOrRange(range);
            }
            else if (inclusionSpecifier != null)
            {
                period.Range = new DateSpecifierOrRange(inclusionSpecifier);
            }
            else
            {
                /* otherwise, it's something like "monthly", with no date reference */
            }

            return(period);
        }
Example #33
0
 public void CanAddZeroMonths()
 {
     var dt = new Date(2000, 1, 1);
     var actual = dt.AddMonths(0);
     var expected = new Date(2000, 1, 1);
     Assert.Equal(expected, actual);
 }
Example #34
0
        /// <summary>
        /// سرانه های اضافه کار تشویقی, شب کاری تشویقی, تعطیل کار تشویقی مربوط به ماه/سال مشخص به صورت صفحه بندی شده بر می گرداند
        /// بر اساس دسترسی کاربر به دپارتمان
        /// </summary>
        /// <param name="parentDepartmentId">آی دی ارگان/سازمان جهت جستجو</param>
        /// <param name="departmentName">نام معاونت جهت جستجو</param>
        /// <param name="year">سال</param>
        /// <param name="month">ماه</param>
        /// <param name="pageIndex">ایندکس صفحه</param>
        /// <param name="pageSize">اندازه صفحه</param>
        /// <param name="count">تعداد کل رکوردها بدون صفحه بندی</param>
        /// <returns>لیست پروکسی سرانه</returns>
        public IList <OverTimeProxy> GetDetails(decimal parentDepartmentId, string departmentName, int year, int month, int pageIndex, int pageSize, out int count)
        {
            DateTime Date;

            if (BLanguage.CurrentSystemLanguage == LanguagesName.Parsi)
            {
                Date = Utility.ToMildiDate(String.Format("{0}/{1}/{2}", year, month, 1));
            }
            else
            {
                Date = new DateTime(year, month, 1);
            }
            //-----------------------------------------------------------------
            //چک کن اگه موجودیت والد برای این ماه/سال در دیتابیس وجود نداشت, یه موجودیت والد ذخیره کن
            this.CheckOverTimeExists(Date);
            //-----------------------------------------------------------------

            OverTime       overTimeAlias       = null;
            OverTimeDetail overTimeDetailAlias = null;
            Department     departmentAlias     = null;
            IQueryOver <OverTimeDetail, OverTimeDetail> searchQuery;
            IList <decimal> accessableIDs = accessPort.GetAccessibleDeparments();

            if (accessableIDs.Count < this.operationBatchSizeValue && this.operationBatchSizeValue < 2100)
            {
                searchQuery = NHSession.QueryOver(() => overTimeDetailAlias)
                              .JoinAlias(() => overTimeDetailAlias.OverTime, () => overTimeAlias)
                              .JoinAlias(() => overTimeDetailAlias.Department, () => departmentAlias)
                              .Where(() =>
                                     departmentAlias.ID.IsIn(accessableIDs.ToList()) &&
                                     overTimeAlias.Date == Date &&
                                     departmentAlias.ParentPath.IsLike("," + parentDepartmentId + ",", MatchMode.Anywhere) &&
                                     departmentAlias.DepartmentType == DepartmentType.Assistance &&
                                     overTimeAlias.IsActive == true);
            }
            else
            {
                GTS.Clock.Model.Temp.Temp tempAlias = null;
                string operationGUID = this.bTemp.InsertTempList(accessableIDs);
                searchQuery = NHSession.QueryOver(() => overTimeDetailAlias)
                              .JoinAlias(() => overTimeDetailAlias.OverTime, () => overTimeAlias)
                              .JoinAlias(() => overTimeDetailAlias.Department, () => departmentAlias)
                              .JoinAlias(() => departmentAlias.TempList, () => tempAlias)
                              .Where(() =>
                                     tempAlias.OperationGUID == operationGUID &&
                                     overTimeAlias.Date == Date &&
                                     departmentAlias.ParentPath.IsLike("," + parentDepartmentId + ",", MatchMode.Anywhere) &&
                                     departmentAlias.DepartmentType == DepartmentType.Assistance &&
                                     overTimeAlias.IsActive == true);

                this.bTemp.DeleteTempList(operationGUID);
            }

            if (!Utility.IsEmpty(departmentName))
            {
                searchQuery.Where(() => departmentAlias.Name.IsLike(departmentName, MatchMode.Anywhere));
            }

            count = searchQuery.RowCount();
            IList <OverTimeDetail> list = new List <OverTimeDetail>();

            list = searchQuery.Skip(pageIndex * pageSize).Take(pageSize).List <OverTimeDetail>();

            personList = bPerson.GetPersonsInfoForOverTime();

            IList <OverTimeProxy> proxyList = new List <OverTimeProxy>();
            var calendarList = bCalendar.GetCalendarListByDateRange(Date, Date.AddMonths(1), "6");

            foreach (var item in list)
            {
                OverTimeProxy proxy = ConvertToProxy(item);
                proxy.MonthHolidayCount = calendarList != null?calendarList.Count() : 0;

                proxyList.Add(proxy);
            }

            return(proxyList);
        }
Example #35
0
 public void CanAddPositiveMonths_FromDay30_ToDay28()
 {
     var dt = new Date(2000, 11, 30);
     var actual = dt.AddMonths(3);
     var expected = new Date(2001, 2, 28);
     Assert.Equal(expected, actual);
 }
Example #36
0
        public static void Test_CalculatePrintNumber_02(Print print, string directory, Date date, int nb)
        {
            string traceFile = zPath.Combine(zPath.Combine(directory, @"Print\CalculatePrintDateNumber"), string.Format("Print_{0}_Number.txt", print.Name));

            Trace.WriteLine("print {0} frequency {1} calculate number from date {2:dd-MM-yyyy} nb {3} trace file \"{4}\"", print.Name, print.Frequency, date, nb, zPath.GetFileName(traceFile));
            //Trace.CurrentTrace.DisableBaseLog();
            //Trace.CurrentTrace.DisableTraceView = true;
            //Trace.CurrentTrace.AddTraceFile(traceFile, LogOptions.RazLogFile);
            Trace.CurrentTrace.AddOnWrite("Test_CalculatePrintNumber_02", WriteToFile.Create(traceFile, FileOption.RazFile).Write);
            try
            {
                Trace.WriteLine("print {0} frequency {1} calculate number from date {2:dd-MM-yyyy} nb {3}", print.Name, print.Frequency, date, nb);
                Trace.WriteLine();
                if (print.Frequency == PrintFrequency.Daily)
                {
                    for (int i = 0; i < nb; i++)
                    {
                        PrintIssue issue  = print.NewPrintIssue(date);
                        int        number = issue.PrintNumber;
                        Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                        date = date.AddDays(1);
                    }
                }
                else if (print.Frequency == PrintFrequency.Weekly)
                {
                    for (int i = 0; i < nb; i++)
                    {
                        PrintIssue issue  = print.NewPrintIssue(date);
                        int        number = issue.PrintNumber;
                        Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                        date = date.AddDays(7);
                    }
                }
                else if (print.Frequency == PrintFrequency.Monthly)
                {
                    for (int i = 0; i < nb; i++)
                    {
                        PrintIssue issue  = print.NewPrintIssue(date);
                        int        number = issue.PrintNumber;
                        Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                        date = date.AddMonths(1);
                    }
                }
                else if (print.Frequency == PrintFrequency.Bimonthly || print.Frequency == PrintFrequency.Quarterly)
                {
                    int lastNumber = 0;
                    for (int i = 0; i < nb;)
                    {
                        PrintIssue issue  = print.NewPrintIssue(date);
                        int        number = issue.PrintNumber;
                        if (number != lastNumber)
                        {
                            Trace.WriteLine("{0:yyyy-MM-dd ddd} {1}", issue.Date, number);
                            lastNumber = number;
                            i++;
                        }
                        date = date.AddMonths(1);
                    }
                }
            }
            finally
            {
                //Trace.CurrentTrace.EnableBaseLog();
                //Trace.CurrentTrace.RemoveTraceFile(traceFile);
                Trace.CurrentTrace.RemoveOnWrite("Test_CalculatePrintNumber_02");
                Trace.CurrentTrace.DisableViewer = false;
            }
        }
Example #37
0
 public static Date GetQuarterlyPrintDate(int printNumber, int refNumber, Date refDate)
 {
     return(refDate.AddMonths((printNumber - refNumber) * 3));
 }
        void TaskPerfomance()
        {
            using (var context = new TasksContext())
            {
                foreach (var task in context.Tasks)
                {
                    if (task.DateTime == DateTime.Now.ToString("g"))
                    {
                        if (task.IsSingly == true)
                        {
                            tasks.Add(task);
                            task.IsSingly = false;
                        }

                        if (task.IsDaily == true && task.DateTime == DateTime.Now.ToString("g"))
                        {
                            tasks.Add(task);
                            Date          = DateTime.Parse(task.DateTime);
                            Date          = Date.AddDays(1);
                            task.DateTime = Date.ToString("g");
                        }

                        if (task.IsWeekly == true && task.DateTime == DateTime.Now.ToString("g"))
                        {
                            tasks.Add(task);
                            Date          = DateTime.Parse(task.DateTime);
                            Date          = Date.AddMonths(1);
                            task.DateTime = Date.ToString("g");
                        }

                        if (task.IsAnnually == true && task.DateTime == DateTime.Now.ToString("g"))
                        {
                            tasks.Add(task);
                            Date          = DateTime.Parse(task.DateTime);
                            Date          = Date.AddYears(1);
                            task.DateTime = Date.ToString("g");
                        }
                    }

                    Date = DateTime.Parse(task.DateTime);
                    if (Date < DateTime.Now)
                    {
                        context.Tasks.Remove(task);
                    }
                }
                context.SaveChanges();
            }

            foreach (var task in tasks)
            {
                if (task.IsDownloadFile == true)
                {
                    Task = task;
                    Thread thread = new Thread(DownloadFiles);
                    thread.Start();
                }

                else if (task.IsMoveCatalog == true)
                {
                    Task = task;
                    Thread thread = new Thread(MoveFiles);
                    thread.Start();
                }

                else if (task.IsEmailSend == true)
                {
                    Task = task;
                    Thread thread = new Thread(EmailSend);
                    thread.Start();
                }
            }
        }