public TreeSwaptionEngine(ShortRateModel model, TimeGrid grid, YieldTermStructureHandle termStructure) : this(NQuantLibcPINVOKE.new_TreeSwaptionEngine__SWIG_2(ShortRateModel.getCPtr(model), TimeGrid.getCPtr(grid), YieldTermStructureHandle.getCPtr(termStructure)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public GaussianPathGenerator(StochasticProcess arg0, TimeGrid timeGrid, GaussianRandomSequenceGenerator generator, bool brownianBridge) : this(NQuantLibcPINVOKE.new_GaussianPathGenerator__SWIG_1(StochasticProcess.getCPtr(arg0), TimeGrid.getCPtr(timeGrid), GaussianRandomSequenceGenerator.getCPtr(generator), brownianBridge), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public BrownianBridge(TimeGrid timeGrid) : this(NQuantLibcPINVOKE.new_BrownianBridge__SWIG_2(TimeGrid.getCPtr(timeGrid)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public Path(TimeGrid timeGrid) : this(NQuantLibcPINVOKE.new_Path__SWIG_1(TimeGrid.getCPtr(timeGrid)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public void BuildDates(QLNet.Calendar calendar, QLNet.DayCounter dc) { _dates.Resize(_tenors.Count); Date today = Settings.evaluationDate(); for (int i = 0; i < _tenors.Count; i++) { if (_tenors[i].units() == TimeUnit.Days) { _dates[i] = calendar.adjust(today + _tenors[i]); } else { _dates[i] = calendar.advance(today, _tenors[i], BusinessDayConvention.Following, true); } } QLNet.Utils.QL_REQUIRE(_dates.Count == _tenors.Count, () => "Date/Tenor mismatch"); // Build times _times.Resize(_dates.Count); for (int i = 0; i < _dates.Count; i++) { _times[i] = dc.yearFraction(today, _dates[i]); } _timeGrid = new TimeGrid(_times, _times.Count); // Log the date grid //log(); }
public Path(TimeGrid timeGrid, QlArray values) : this(NQuantLibcPINVOKE.new_Path__SWIG_0(TimeGrid.getCPtr(timeGrid), QlArray.getCPtr(values)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public TreeSwaptionEngine(ShortRateModel model, TimeGrid grid) : this(NQuantLibcPINVOKE.new_TreeSwaptionEngine__SWIG_3(ShortRateModel.getCPtr(model), TimeGrid.getCPtr(grid)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
public InvCumulativeMersenneTwisterPathGenerator(StochasticProcess arg0, TimeGrid timeGrid, InvCumulativeMersenneTwisterGaussianRsg generator, bool brownianBridge) : this(NQuantLibcPINVOKE.new_InvCumulativeMersenneTwisterPathGenerator__SWIG_1(StochasticProcess.getCPtr(arg0), TimeGrid.getCPtr(timeGrid), InvCumulativeMersenneTwisterGaussianRsg.getCPtr(generator), brownianBridge), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } }
/* * private double inner_product(IEnumerable a, IEnumerable b, double val) * { * IEnumerator ita = a.GetEnumerator(); * IEnumerator itb = b.GetEnumerator(); * while( ita.MoveNext() && itb.MoveNext() ) * val += (double)ita.Current * (double)itb.Current; * return val; * } */ #region NumericalMethod interface /// <summary> /// Initialize a DiscretizedAsset object. /// </summary> /// <param name="asset"></param> /// <param name="time"></param> public override void Initialize(IDiscretizedAsset asset, double time) { int i = TimeGrid.FindIndex(time); asset.Time = time; asset.Reset(Count(i)); }
public MultiPathGeneratorMersenneTwister(QLNet.StochasticProcess process, TimeGrid grid, ulong seed, bool antitheticSampling) { _process = process; _grid = grid; _seed = seed; _antitheticSampling = antitheticSampling; _antitheticVariate = true; Reset(); }
public TimeGrid timeGrid() { TimeGrid ret = new TimeGrid(NQuantLibcPINVOKE.InvCumulativeMersenneTwisterPathGenerator_timeGrid(swigCPtr), false); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public TimeGrid timeGrid() { TimeGrid ret = new TimeGrid(NQuantLibcPINVOKE.PiecewiseTimeDependentHestonModel_timeGrid(swigCPtr), false); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public TimeGrid timeGrid() { TimeGrid ret = new TimeGrid(NQuantLibcPINVOKE.GaussianPathGenerator_timeGrid(swigCPtr), false); if (NQuantLibcPINVOKE.SWIGPendingException.Pending) { throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public void Truncate(int len) { if (_dates.Count > len) { //DLOG("Truncating DateGrid, removing elements " << dates_[len] << " to " << dates_.back()); _dates.Resize(len); _tenors.Resize(len); _times.Resize(len); _timeGrid = new TimeGrid(_times, 0); // TODO: Is this correct?? //DLOG("DateGrid size now " << dates_.size()); } }
protected async override void OnBackKeyPress(CancelEventArgs e) { e.Cancel = true; await Task.WhenAll(new[] { AnimationTrigger.AnimateClose(), TimeGrid.AnimateAsync(new BounceOutDownAnimation()) }); NavigationService.GoBack(); }
public void testConstructorMandatorySteps() { // Testing TimeGrid construction with only mandatory points List <double> test_times = new List <double> { 0.0, 1.0, 2.0, 4.0 }; TimeGrid tg = new TimeGrid(test_times); // Time grid must include all times from passed iterator. // Further no additional times can be added. QAssert.CollectionAreEqual(tg.Times(), test_times); }
public void testLambdaBootstrapping() { //"Testing caplet LMM lambda bootstrapping..." //SavedSettings backup; double tolerance = 1e-10; double[] lambdaExpected = { 14.3010297550, 19.3821411939, 15.9816590141, 15.9953118303, 14.0570815635, 13.5687599894, 12.7477197786, 13.7056638165, 11.6191989567 }; LiborForwardModelProcess process = makeProcess(); Matrix covar = process.covariance(0.0, null, 1.0); for (int i = 0; i < 9; ++i) { double calculated = Math.Sqrt(covar[i + 1, i + 1]); double expected = lambdaExpected[i] / 100; if (Math.Abs(calculated - expected) > tolerance) { Assert.Fail("Failed to reproduce expected lambda values" + "\n calculated: " + calculated + "\n expected: " + expected); } } LfmCovarianceParameterization param = process.covarParam(); List <double> tmp = process.fixingTimes(); TimeGrid grid = new TimeGrid(tmp.Last(), 14); for (int t = 0; t < grid.size(); ++t) { //verifier la presence du null Matrix diff = param.integratedCovariance(grid[t], null) - param.integratedCovariance(grid[t], null); for (int i = 0; i < diff.rows(); ++i) { for (int j = 0; j < diff.columns(); ++j) { if (Math.Abs(diff[i, j]) > tolerance) { Assert.Fail("Failed to reproduce integrated covariance" + "\n calculated: " + diff[i, j] + "\n expected: " + 0); } } } } }
private void HistoryTimelineHeader_ItemSwipe(object sender, ItemSwipeEventArgs e) { if (e.Direction == SwipeListDirection.Right) { // update state state++; if (state == 3) { HistoryTimelineHeader.RightOrButtomBehavior = SwipeListBehavior.Disabled; } else { HistoryTimelineHeader.RightOrButtomBehavior = SwipeListBehavior.Expand; } if (historyGrid == null) { // create time grid historyGrid = new TimeGrid(); // set as content HistoryTimelineContent.Children.Clear(); HistoryTimelineContent.Children.Add(historyGrid); historyGrid.HorizontalAlignment = HorizontalAlignment.Stretch; historyGrid.VerticalAlignment = VerticalAlignment.Stretch; } // setup content SetupHistoryGrid(state); SetupHistoryBarContent(state); } else { // update state state--; if (state == 0) { HistoryTimelineHeader.LeftOrTopBehavior = SwipeListBehavior.Disabled; } else { HistoryTimelineHeader.RightOrButtomBehavior = SwipeListBehavior.Expand; } // setup content SetupHistoryGrid(state); SetupHistoryBarContent(state); } HistoryTimelineHeader.ResetSwipe(); }
public void testMandatoryTimes() { // Testing that mandatory times are recalled correctly List <double> test_times = new List <double> { 1.0, 2.0, 4.0 }; TimeGrid tg = new TimeGrid(test_times, 8); // Mandatory times are those provided by the original iterator. List <double> tg_mandatory_times = tg.mandatoryTimes(); QAssert.CollectionAreEqual(tg_mandatory_times, test_times); }
public void testClosestTime() { // Testing that the returned time matches the requested index List <double> test_times = new List <double> { 1.0, 2.0, 5.0 }; TimeGrid tg = new TimeGrid(test_times); int expected_time = 5; QAssert.IsTrue(tg.closestTime(4).IsEqual(expected_time), "Expected time of: " + expected_time + ", which does not match " + "the returned time: " + tg.closestTime(4)); }
public void testClosestIndex() { // Testing that the returned index is closest to the requested time List <double> test_times = new List <double> { 1.0, 2.0, 5.0 }; TimeGrid tg = new TimeGrid(test_times); int expected_index = 3; QAssert.IsTrue(tg.closestIndex(4) == expected_index, "Expected index: " + expected_index + ", which does not match " + "the returned index: " + tg.closestIndex(4)); }
private void comboLanguage_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { if ((string)comboLanguage.SelectedValue == "English") { lang = LanguagePreset.Language.English; grid = new TimeGridEnglish(); } else { lang = LanguagePreset.Language.Dutch; grid = new TimeGridDutch(); } }
private void pathGenerator(UnderlyingInfo under) { ulong seed = 1; int timeSteps = 365; // int dimensions = this.processArr_.factors(); double t = processArr_.time(maturity); TimeGrid grid = new TimeGrid(t, timeSteps); IRNG rndGenerator = (IRNG) new PseudoRandom().make_sequence_generator(dimensions * (grid.size() - 1), seed); this.pathGenerator_ = new MultiPathGenerator <IRNG>(this.processArr_, grid, rndGenerator, false); }
public ScenarioCube(double r, double[] spots, double[] q, double[] vols, double[,] correlations, int nSteps, double dt) { nAssets = spots.Length; this.nSteps = nSteps; this.dt = dt; Processes = new List <StochasticProcess1D>(nAssets); Correlations = new Matrix(nAssets, nAssets); Date now = new Date(DateTime.Now.Date); DayCounter dc = new SimpleDayCounter(); yc = new Handle <YieldTermStructure>(new FlatForward(now, r, dc)); for (int i = 0; i < nAssets; ++i) { Handle <Quote> x0 = new Handle <Quote>(new SimpleQuote(spots[i])); Handle <YieldTermStructure> dyc = new Handle <YieldTermStructure>(new FlatForward(now, q[i], dc)); Handle <BlackVolTermStructure> bv = new Handle <BlackVolTermStructure>(new BlackConstantVol(now, new Calendar(), vols[i], dc)); Processes.Add(new GeneralizedBlackScholesProcess(x0, dyc, yc, bv)); for (int j = 0; j < nAssets; ++j) { if (i == j) { Correlations[i, j] = 1; } else { Correlations[i, j] = Correlations[j, i] = correlations[i, j]; } } } spa = new StochasticProcessArray(Processes, Correlations); rsg = new RandomSequenceGenerator <MersenneTwisterUniformRng>(nSteps * Processes.Count, new MersenneTwisterUniformRng()); tg = new TimeGrid(nSteps * dt, nSteps); var rsg2 = new InverseCumulativeRsg <RandomSequenceGenerator <MersenneTwisterUniformRng>, InverseCumulativeNormal>(rsg, new InverseCumulativeNormal()); mpg = new MultiPathGenerator <InverseCumulativeRsg <RandomSequenceGenerator <MersenneTwisterUniformRng>, InverseCumulativeNormal> >(spa, tg, rsg2, false); }
public void testConstructorEvenSteps() { // Testing TimeGrid construction with n evenly spaced points double end_time = 10; int steps = 5; TimeGrid tg = new TimeGrid(end_time, steps); List <double> expected_times = new List <double> { 0.0, 2.0, 4.0, 6.0, 8.0, 10.0 }; QAssert.CollectionAreEqual(tg.Times(), expected_times); }
/// <summary> /// Roll-back a DiscretizedAsset object until a certain time. /// </summary> /// <param name="asset"></param> /// <param name="toTime"></param> public override void Rollback(IDiscretizedAsset asset, double toTime) { double from = asset.Time; // Can't Rollback to the future: if (from < toTime) { throw new ArgumentException("LatBackFut"); } int iFrom = TimeGrid.FindIndex(from); int iTo = TimeGrid.FindIndex(toTime); for (int i = iFrom - 1; i >= iTo; i--) { var newValues = new double[Count(i)]; Stepback(i, asset.Values, newValues); asset.Time = TimeGrid[i]; asset.Values = newValues; asset.AdjustValues(); } }
/// <summary> /// Computes the present value of an asset using Arrow-Debrew prices. /// </summary> /// <param name="asset"></param> /// <returns></returns> public double PresentValue(IDiscretizedAsset asset) { int i = TimeGrid.FindIndex(asset.Time); if (i > _statePricesLimit) { ComputeStatePrices(i); } // return DotProduct(asset.Values, statePrices[i]); var prices = (double[])_statePrices[i]; Debug.Assert( asset.Values.Length == prices.Length, "arrays with different sizes cannot be multiplied."); double val = 0.0; for (int j = 0; j < prices.Length; j++) { val += asset.Values[j] * prices[j]; } return(val); // return inner_product(asset.Values, statePriceValues(i), 0.0); }
public void testConstructorAdditionalSteps() { // Testing TimeGrid construction with additional steps List <double> test_times = new List <double> { 1.0, 2.0, 4.0 }; TimeGrid tg = new TimeGrid(test_times, 8); // Expect 8 evenly sized steps over the interval [0, 4]. List <double> expected_times = new List <double> { 0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0 }; QAssert.CollectionAreEqual(tg.Times(), expected_times); }
private void PlotChart( Graphics graphics ) { int lux = x_offset + chart_lpadding; int luy = y_offset + CHART_UPADDING; //defaultBrush.Color = Color.White; //defaultPen.Color = Color.Black; //if ( graphDef.Background == null ) //{ defaultBrush.Color = graphDef.CanvasColor; graphics.FillRectangle(defaultBrush, lux, luy, chartWidth, chartHeight ); //} // Draw the chart area frame defaultPen.Color = graphDef.FrameColor; graphics.DrawRectangle(defaultPen, lux, luy, chartWidth, chartHeight ); double val; double[] tmpSeries = new double[numPoints]; GridRange range = graphDef.GridRange; bool rigid = ( range != null ? range.Rigid : false ); double lowerValue = ( range != null ? range.LowerValue : Double.MaxValue ); double upperValue = ( range != null ? range.UpperValue : Double.MinValue ); // For autoscale, detect lower and upper limit of values PlotDef[] plotDefs = graphDef.PlotDefs; for ( int i = 0; i < plotDefs.Length; i++ ) { plotDefs[i].SetSource( sources, sourceIndex ); Source src = plotDefs[i].Source; // Only try autoscale when we do not have a rigid grid if ( !rigid && src != null ) { double min = src.GetAggregate( Source.AGG_MINIMUM ); double max = src.GetAggregate( Source.AGG_MAXIMUM ); // If the plotdef is a stack, evaluate ALL previous values to find a possible max if ( plotDefs[i].plotType == PlotDef.PLOT_STACK && i >= 1 ) { if ( plotDefs[i - 1].plotType == PlotDef.PLOT_STACK ) { // Use this source plus stack of previous ones for (int j = 0; j < tmpSeries.Length; j++) { val = tmpSeries[j] + plotDefs[i].GetValue(j, timestamps); if ( val < lowerValue ) lowerValue = val; if ( val > upperValue ) upperValue = val; tmpSeries[j] = val; } } else { // Use this source plus the previous one for (int j = 0; j < tmpSeries.Length; j++) { val = plotDefs[i - 1].GetValue(j, timestamps) + plotDefs[i].GetValue(j, timestamps); if ( val < lowerValue ) lowerValue = val; if ( val > upperValue ) upperValue = val; tmpSeries[j] = val; } } } else // Only use min/max of a single datasource { if ( min < lowerValue ) lowerValue = min; if ( max > upperValue ) upperValue = max; } } } vGrid = new ValueGrid( range, lowerValue, upperValue, graphDef.ValueAxis, graphDef.BaseValue ); tGrid = new TimeGrid( graphDef.StartTime, (graphDef.EndTime != 0? graphDef.EndTime : calculatedEndTime), graphDef.TimeAxis, graphDef.FirstDayOfWeek ); lowerValue = vGrid.LowerValue; upperValue = vGrid.UpperValue; // Use a special graph 'object' that takes care of resizing and reversing y coordinates ChartGraphics g = new ChartGraphics( graphics ); g.SetDimensions( chartWidth, chartHeight ); g.SetXRange( tGrid.StartTime, tGrid.EndTime ); g.SetYRange( lowerValue, upperValue ); // Set the chart origin point double diff = 1.0d; if ( lowerValue < 0 ) diff = 1.0d - ( lowerValue / ( -upperValue + lowerValue )); graphOriginX = lux; graphOriginY = (int) (luy + chartHeight * diff); // If the grid is behind the plots, draw it first if ( !graphDef.FrontGrid ) PlotChartGrid( g ); // Use AA if necessary if ( graphDef.AntiAliasing ) graphics.SmoothingMode = SmoothingMode.AntiAlias; // Prepare clipping area and origin graphics.SetClip(new System.Drawing.Rectangle( lux, luy, chartWidth, chartHeight)); graphics.TranslateTransform( graphOriginX, graphOriginY ); int lastPlotType = PlotDef.PLOT_LINE; int[] parentSeries = new int[numPoints]; // Pre calculate x positions of the corresponding timestamps int[] xValues = new int[timestamps.Length]; for (int i = 0; i < timestamps.Length; i++) xValues[i] = g.GetX(timestamps[i]); // Draw all graphed values for (int i = 0; i < plotDefs.Length; i++) { plotDefs[i].Draw( g, xValues, parentSeries, lastPlotType ); if(plotDefs[i].PlotType != PlotDef.PLOT_STACK) { lastPlotType = plotDefs[i].PlotType; } } // Reset clipping area, origin and AA settings graphics.TranslateTransform( (float)-graphOriginX, (float)-graphOriginY ); graphics.SetClip(new System.Drawing.Rectangle(0, 0, imgWidth, imgHeight)); graphics.SmoothingMode = SmoothingMode.None; // If the grid is in front of the plots, draw it now if ( graphDef.FrontGrid ) PlotChartGrid( g ); }
static void Main(string[] args) { DateTime startTime = DateTime.Now; Date todaysDate = new Date(15, Month.February, 2002); Calendar calendar = new TARGET(); Date settlementDate = new Date(19, Month.February, 2002); Settings.instance().setEvaluationDate(todaysDate); // flat yield term structure impling 1x5 swap at 5% Quote flatRate = new SimpleQuote(0.04875825); FlatForward myTermStructure = new FlatForward( settlementDate, new QuoteHandle(flatRate), new Actual365Fixed()); RelinkableYieldTermStructureHandle rhTermStructure = new RelinkableYieldTermStructureHandle(); rhTermStructure.linkTo(myTermStructure); // Define the ATM/OTM/ITM swaps Period fixedLegTenor = new Period(1, TimeUnit.Years); BusinessDayConvention fixedLegConvention = BusinessDayConvention.Unadjusted; BusinessDayConvention floatingLegConvention = BusinessDayConvention.ModifiedFollowing; DayCounter fixedLegDayCounter = new Thirty360(Thirty360.Convention.European); Period floatingLegTenor = new Period(6, TimeUnit.Months); double dummyFixedRate = 0.03; IborIndex indexSixMonths = new Euribor6M(rhTermStructure); Date startDate = calendar.advance(settlementDate, 1, TimeUnit.Years, floatingLegConvention); Date maturity = calendar.advance(startDate, 5, TimeUnit.Years, floatingLegConvention); Schedule fixedSchedule = new Schedule(startDate, maturity, fixedLegTenor, calendar, fixedLegConvention, fixedLegConvention, DateGeneration.Rule.Forward, false); Schedule floatSchedule = new Schedule(startDate, maturity, floatingLegTenor, calendar, floatingLegConvention, floatingLegConvention, DateGeneration.Rule.Forward, false); VanillaSwap swap = new VanillaSwap( VanillaSwap.Type.Payer, 1000.0, fixedSchedule, dummyFixedRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); DiscountingSwapEngine swapEngine = new DiscountingSwapEngine(rhTermStructure); swap.setPricingEngine(swapEngine); double fixedATMRate = swap.fairRate(); double fixedOTMRate = fixedATMRate * 1.2; double fixedITMRate = fixedATMRate * 0.8; VanillaSwap atmSwap = new VanillaSwap( VanillaSwap.Type.Payer, 1000.0, fixedSchedule, fixedATMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); VanillaSwap otmSwap = new VanillaSwap( VanillaSwap.Type.Payer, 1000.0, fixedSchedule, fixedOTMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); VanillaSwap itmSwap = new VanillaSwap( VanillaSwap.Type.Payer, 1000.0, fixedSchedule, fixedITMRate, fixedLegDayCounter, floatSchedule, indexSixMonths, 0.0, indexSixMonths.dayCounter()); atmSwap.setPricingEngine(swapEngine); otmSwap.setPricingEngine(swapEngine); itmSwap.setPricingEngine(swapEngine); // defining the swaptions to be used in model calibration PeriodVector swaptionMaturities = new PeriodVector(); swaptionMaturities.Add(new Period(1, TimeUnit.Years)); swaptionMaturities.Add(new Period(2, TimeUnit.Years)); swaptionMaturities.Add(new Period(3, TimeUnit.Years)); swaptionMaturities.Add(new Period(4, TimeUnit.Years)); swaptionMaturities.Add(new Period(5, TimeUnit.Years)); CalibrationHelperVector swaptions = new CalibrationHelperVector(); // List of times that have to be included in the timegrid DoubleVector times = new DoubleVector(); for (int i = 0; i < numRows; i++) { int j = numCols - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1 int k = i * numCols + j; Quote vol = new SimpleQuote(swaptionVols[k]); SwaptionHelper helper = new SwaptionHelper( swaptionMaturities[i], new Period(swapLengths[j], TimeUnit.Years), new QuoteHandle(vol), indexSixMonths, indexSixMonths.tenor(), indexSixMonths.dayCounter(), indexSixMonths.dayCounter(), rhTermStructure); swaptions.Add(helper); times.AddRange(helper.times()); } // Building time-grid TimeGrid grid = new TimeGrid(times, 30); // defining the models // G2 modelG2 = new G2(rhTermStructure)); HullWhite modelHW = new HullWhite(rhTermStructure); HullWhite modelHW2 = new HullWhite(rhTermStructure); BlackKarasinski modelBK = new BlackKarasinski(rhTermStructure); // model calibrations // Console.WriteLine( "G2 (analytic formulae) calibration" ); // for (int i=0; i<swaptions.Count; i++) // NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine( // new G2SwaptionEngine( modelG2, 6.0, 16 ) ); // // calibrateModel( modelG2, swaptions, 0.05); // Console.WriteLine( "calibrated to:" ); // Console.WriteLine( "a = " + modelG2.parameters()[0] ); // Console.WriteLine( "sigma = " + modelG2.parameters()[1] ); // Console.WriteLine( "b = " + modelG2.parameters()[2] ); // Console.WriteLine( "eta = " + modelG2.parameters()[3] ); // Console.WriteLine( "rho = " + modelG2.parameters()[4] ); Console.WriteLine("Hull-White (analytic formulae) calibration"); for (int i = 0; i < swaptions.Count; i++) { NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine( new JamshidianSwaptionEngine(modelHW)); } calibrateModel(modelHW, swaptions, 0.05); // Console.WriteLine( "calibrated to:" ); // Console.WriteLine( "a = " + modelHW.parameters()[0] ); // Console.WriteLine( "sigma = " + modelHW.parameters()[1] ); Console.WriteLine("Hull-White (numerical) calibration"); for (int i = 0; i < swaptions.Count; i++) { NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine( new TreeSwaptionEngine(modelHW2, grid)); } calibrateModel(modelHW2, swaptions, 0.05); // std::cout << "calibrated to:\n" // << "a = " << modelHW2->params()[0] << ", " // << "sigma = " << modelHW2->params()[1] // << std::endl << std::endl; Console.WriteLine("Black-Karasinski (numerical) calibration"); for (int i = 0; i < swaptions.Count; i++) { NQuantLibc.as_black_helper(swaptions[i]).setPricingEngine( new TreeSwaptionEngine(modelBK, grid)); } calibrateModel(modelBK, swaptions, 0.05); // std::cout << "calibrated to:\n" // << "a = " << modelBK->params()[0] << ", " // << "sigma = " << modelBK->params()[1] // << std::endl << std::endl; // ATM Bermudan swaption pricing Console.WriteLine("Payer bermudan swaption struck at {0} (ATM)", fixedATMRate); DateVector bermudanDates = new DateVector(); Schedule schedule = new Schedule(startDate, maturity, new Period(3, TimeUnit.Months), calendar, BusinessDayConvention.Following, BusinessDayConvention.Following, DateGeneration.Rule.Forward, false); for (uint i = 0; i < schedule.size(); i++) { bermudanDates.Add(schedule.date(i)); } Exercise bermudaExercise = new BermudanExercise(bermudanDates); Swaption bermudanSwaption = new Swaption(atmSwap, bermudaExercise); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelHW, 50)); Console.WriteLine("HW: " + bermudanSwaption.NPV()); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelHW2, 50)); Console.WriteLine("HW (num): " + bermudanSwaption.NPV()); bermudanSwaption.setPricingEngine( new TreeSwaptionEngine(modelBK, 50)); Console.WriteLine("BK (num): " + bermudanSwaption.NPV()); DateTime endTime = DateTime.Now; TimeSpan delta = endTime - startTime; Console.WriteLine(); Console.WriteLine("Run completed in {0} s", delta.TotalSeconds); Console.WriteLine(); }
public TreeSwaptionEngine(ShortRateModel model, TimeGrid grid, YieldTermStructureHandle termStructure) : this(NQuantLibcPINVOKE.new_TreeSwaptionEngine__SWIG_2(ShortRateModel.getCPtr(model), TimeGrid.getCPtr(grid), YieldTermStructureHandle.getCPtr(termStructure)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); }
public TreeSwaptionEngine(ShortRateModel model, TimeGrid grid) : this(NQuantLibcPINVOKE.new_TreeSwaptionEngine__SWIG_3(ShortRateModel.getCPtr(model), TimeGrid.getCPtr(grid)), true) { if (NQuantLibcPINVOKE.SWIGPendingException.Pending) throw NQuantLibcPINVOKE.SWIGPendingException.Retrieve(); }
public void testSwaptionPricing() { // Testing forward swap and swaption pricing const int size = 10; const int steps = 8 * size; #if QL_USE_INDEXED_COUPON const double tolerance = 1e-6; #else const double tolerance = 1e-12; #endif List <Date> dates = new List <Date>(); List <double> rates = new List <double>(); dates.Add(new Date(4, 9, 2005)); dates.Add(new Date(4, 9, 2011)); rates.Add(0.04); rates.Add(0.08); IborIndex index = makeIndex(dates, rates); LiborForwardModelProcess process = new LiborForwardModelProcess(size, index); LmCorrelationModel corrModel = new LmExponentialCorrelationModel(size, 0.5); LmVolatilityModel volaModel = new LmLinearExponentialVolatilityModel(process.fixingTimes(), 0.291, 1.483, 0.116, 0.00001); // set-up pricing engine process.setCovarParam((LfmCovarianceParameterization) new LfmCovarianceProxy(volaModel, corrModel)); // set-up a small Monte-Carlo simulation to price swations List <double> tmp = process.fixingTimes(); TimeGrid grid = new TimeGrid(tmp, tmp.Count, steps); List <int> location = new List <int>(); for (int i = 0; i < tmp.Count; ++i) { location.Add(grid.index(tmp[i])); } ulong seed = 42; const int nrTrails = 5000; LowDiscrepancy.icInstance = new InverseCumulativeNormal(); IRNG rsg = (InverseCumulativeRsg <RandomSequenceGenerator <MersenneTwisterUniformRng> , InverseCumulativeNormal>) new PseudoRandom().make_sequence_generator(process.factors() * (grid.size() - 1), seed); MultiPathGenerator <IRNG> generator = new MultiPathGenerator <IRNG>(process, grid, rsg, false); LiborForwardModel liborModel = new LiborForwardModel(process, volaModel, corrModel); Calendar calendar = index.fixingCalendar(); DayCounter dayCounter = index.forwardingTermStructure().link.dayCounter(); BusinessDayConvention convention = index.businessDayConvention(); Date settlement = index.forwardingTermStructure().link.referenceDate(); SwaptionVolatilityMatrix m = liborModel.getSwaptionVolatilityMatrix(); for (int i = 1; i < size; ++i) { for (int j = 1; j <= size - i; ++j) { Date fwdStart = settlement + new Period(6 * i, TimeUnit.Months); Date fwdMaturity = fwdStart + new Period(6 * j, TimeUnit.Months); Schedule schedule = new Schedule(fwdStart, fwdMaturity, index.tenor(), calendar, convention, convention, DateGeneration.Rule.Forward, false); double swapRate = 0.0404; VanillaSwap forwardSwap = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0, schedule, swapRate, dayCounter, schedule, index, 0.0, index.dayCounter()); forwardSwap.setPricingEngine(new DiscountingSwapEngine(index.forwardingTermStructure())); // check forward pricing first double expected = forwardSwap.fairRate(); double calculated = liborModel.S_0(i - 1, i + j - 1); if (Math.Abs(expected - calculated) > tolerance) { QAssert.Fail("Failed to reproduce fair forward swap rate" + "\n calculated: " + calculated + "\n expected: " + expected); } swapRate = forwardSwap.fairRate(); forwardSwap = new VanillaSwap(VanillaSwap.Type.Receiver, 1.0, schedule, swapRate, dayCounter, schedule, index, 0.0, index.dayCounter()); forwardSwap.setPricingEngine(new DiscountingSwapEngine(index.forwardingTermStructure())); if (i == j && i <= size / 2) { IPricingEngine engine = new LfmSwaptionEngine(liborModel, index.forwardingTermStructure()); Exercise exercise = new EuropeanExercise(process.fixingDates()[i]); Swaption swaption = new Swaption(forwardSwap, exercise); swaption.setPricingEngine(engine); GeneralStatistics stat = new GeneralStatistics(); for (int n = 0; n < nrTrails; ++n) { Sample <IPath> path = (n % 2 != 0) ? generator.antithetic() : generator.next(); MultiPath value = path.value as MultiPath; Utils.QL_REQUIRE(value != null, () => "Invalid Path"); //Sample<MultiPath> path = generator.next(); List <double> rates_ = new InitializedList <double>(size); for (int k = 0; k < process.size(); ++k) { rates_[k] = value[k][location[i]]; } List <double> dis = process.discountBond(rates_); double npv = 0.0; for (int k = i; k < i + j; ++k) { npv += (swapRate - rates_[k]) * (process.accrualEndTimes()[k] - process.accrualStartTimes()[k]) * dis[k]; } stat.add(Math.Max(npv, 0.0)); } if (Math.Abs(swaption.NPV() - stat.mean()) > stat.errorEstimate() * 2.35) { QAssert.Fail("Failed to reproduce swaption npv" + "\n calculated: " + stat.mean() + "\n expected: " + swaption.NPV()); } } } } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(TimeGrid obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; }