C# Error when trying to price instrument 'System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced'

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

C# Error when trying to price instrument 'System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced'

Ahmad Mahomed
Hi,

I am receiving the following error when trying to price a 20x10 swap from a bootstrapped curve.

"SwapRatesServiceTests.ImpliedRate_ForTwenty_x_TenYearSwap_ReturnsRate: System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced"

I don't have the faintest idea where to start to debug this issue. Any assistance will be highly appreciated.

IMPORTANT: I am using the C# Swig version of Quantlib, so my actual prod code is as follows based on the swapvaluation.cpp example:

The test method:

        [Test]
        public void ImpliedRate_ForTwenty_x_TenYearSwap_ReturnsRate() 
        {
            //Arrange
            var startingDate = new Date(10,Month.October,2030); // starting date of 20x10yr swap
            var length= 10;
            repo.Setup(r => r.Read(It.IsAny<string>())).Returns(LoadSwapPoints()); // LoadSwapPoints returns IEnumerable<RateHelpers>

            //Act
            service.ConstructSwapPoints(SettlementDate);
            var instrumentRate = service.ImpliedRate(startingDate, length);

            //Assert
            Assert.That(instrumentRate, Is.Not.Null); // this must change to a value test

        }

This is part of the larger ConstructSwapPoints method

            var depoFRASwapInstruments = PointVector; // RateHelperVector populated with RateHelpers
            DayCounter termStructureDayCounter = new ActualActual(ActualActual.Convention.Actual365);

            QuoteHandleVector quotes = new QuoteHandleVector();
            DateVector quoteDates = new DateVector();

            py = CreatePiecewiseLinearCurve(settlementDate, depoFRASwapInstruments, termStructureDayCounter, quotes, quoteDates);
            DiscountingTermStructure = new RelinkableYieldTermStructureHandle(py); //RelinkableYieldTermStructureHandle
            //DiscountingTermStructure.linkTo(py); // alternate way

            PricingEngine = new DiscountingSwapEngine(DiscountingTermStructure); // DiscountingSwapEngine           


With the ImpliedRate method as follows (i have snipped some parts out due to IP restrictions);
 
        public double ImpliedRate(Date startingDate, int length)
        {
            
            var swapMaturityDate = startingDate.Add(new Period(length, TimeUnit.Years));
            var curveMaturityDate = py.maxDate();
 
            Schedule fixedSchedule = new Schedule(startingDate, swapMaturityDate, new Period(Frequency.Quarterly), SouthAfricanCalender, Convention, Convention, DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startingDate, swapMaturityDate, new Period(Frequency.Quarterly), SouthAfricanCalender, Convention, Convention, DateGeneration.Rule.Forward, false);

            VanillaSwap impliedSwap = new VanillaSwap(
                _VanillaSwap.Type.Payer, 
                10000000.0, 
                fixedSchedule, 
                0.1, 
                Actual365FixedDayCounter, 
                floatSchedule, 
                new Jibar(new Period(Frequency.Quarterly)), 
                0, 
                Actual365FixedDayCounter);

            impliedSwap.setPricingEngine(PricingEngine);

            return impliedSwap.fairRate();
        }


I hope my terminology is correct as the finance jargon is still new to me.

--
Ahmad Mahomed

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store
http://p.sf.net/sfu/nokia-dev2dev
_______________________________________________
QuantLib-users mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/quantlib-users
Reply | Threaded
Open this post in threaded view
|

Re: C# Error when trying to price instrument 'System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced'

Ahmad Mahomed
OK some, further investigating lead me to believe the following:

1) The actual error is being thrown from the `discountingswapengine.cpp` calculate routine specifically around these lines. The fact that the error is showing 2nd leg implies to me that the loop fails at the second iteration (there should be only two loops since there are only two legs). The only code here that deals with Handles and pointers  from what I gather relate to  the 'discountCurve_'. I am not too familiar with C++ but my guess is that the offending piece of code is this statement: '**discountCurve_'. which deals with dereferencing a pointer. I also noted that the Handle class has overridden the '*' operator, so the net effect of this statement is unknown to me. So my guess is that somehow the reference to the  discountcurve pointer is being lost...or the error is within the CashFlows.

   for (Size i=0; i<arguments_.legs.size(); ++i) {
            try {
                results_.legNPV[i] = arguments_.payer[i] *
                    CashFlows::npv(arguments_.legs[i],
                                   **discountCurve_,
                                   includeRefDateFlows,
                                   settlementDate,
                                   results_.valuationDate);
                results_.legBPS[i] = arguments_.payer[i] *
                    CashFlows::bps(arguments_.legs[i],
                                   **discountCurve_,
                                   includeRefDateFlows,
                                   settlementDate,
                                   results_.valuationDate);
            } catch (std::exception &e) {
                QL_FAIL(io::ordinal(i+1) << " leg: " << e.what());
            }
            results_.value += results_.legNPV[i];
            try {
                Date d = CashFlows::startDate(arguments_.legs[i]);
                startDiscounts[i] = discountCurve_->discount(d);
            } catch (...) {
                startDiscounts[i] = Null<DiscountFactor>();
            }
}



On 25 October 2010 11:24, Ahmad Mahomed <[hidden email]> wrote:
Hi,

I am receiving the following error when trying to price a 20x10 swap from a bootstrapped curve.

"SwapRatesServiceTests.ImpliedRate_ForTwenty_x_TenYearSwap_ReturnsRate: System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced"

I don't have the faintest idea where to start to debug this issue. Any assistance will be highly appreciated.

IMPORTANT: I am using the C# Swig version of Quantlib, so my actual prod code is as follows based on the swapvaluation.cpp example:

The test method:

        [Test]
        public void ImpliedRate_ForTwenty_x_TenYearSwap_ReturnsRate() 
        {
            //Arrange
            var startingDate = new Date(10,Month.October,2030); // starting date of 20x10yr swap
            var length= 10;
            repo.Setup(r => r.Read(It.IsAny<string>())).Returns(LoadSwapPoints()); // LoadSwapPoints returns IEnumerable<RateHelpers>

            //Act
            service.ConstructSwapPoints(SettlementDate);
            var instrumentRate = service.ImpliedRate(startingDate, length);

            //Assert
            Assert.That(instrumentRate, Is.Not.Null); // this must change to a value test

        }

This is part of the larger ConstructSwapPoints method

            var depoFRASwapInstruments = PointVector; // RateHelperVector populated with RateHelpers
            DayCounter termStructureDayCounter = new ActualActual(ActualActual.Convention.Actual365);

            QuoteHandleVector quotes = new QuoteHandleVector();
            DateVector quoteDates = new DateVector();

            py = CreatePiecewiseLinearCurve(settlementDate, depoFRASwapInstruments, termStructureDayCounter, quotes, quoteDates);
            DiscountingTermStructure = new RelinkableYieldTermStructureHandle(py); //RelinkableYieldTermStructureHandle
            //DiscountingTermStructure.linkTo(py); // alternate way

            PricingEngine = new DiscountingSwapEngine(DiscountingTermStructure); // DiscountingSwapEngine           


With the ImpliedRate method as follows (i have snipped some parts out due to IP restrictions);
 
        public double ImpliedRate(Date startingDate, int length)
        {
            
            var swapMaturityDate = startingDate.Add(new Period(length, TimeUnit.Years));
            var curveMaturityDate = py.maxDate();
 
            Schedule fixedSchedule = new Schedule(startingDate, swapMaturityDate, new Period(Frequency.Quarterly), SouthAfricanCalender, Convention, Convention, DateGeneration.Rule.Forward, false);
            Schedule floatSchedule = new Schedule(startingDate, swapMaturityDate, new Period(Frequency.Quarterly), SouthAfricanCalender, Convention, Convention, DateGeneration.Rule.Forward, false);

            VanillaSwap impliedSwap = new VanillaSwap(
                _VanillaSwap.Type.Payer, 
                10000000.0, 
                fixedSchedule, 
                0.1, 
                Actual365FixedDayCounter, 
                floatSchedule, 
                new Jibar(new Period(Frequency.Quarterly)), 
                0, 
                Actual365FixedDayCounter);

            impliedSwap.setPricingEngine(PricingEngine);

            return impliedSwap.fairRate();
        }


I hope my terminology is correct as the finance jargon is still new to me.

--
Ahmad Mahomed



--
Ahmad Mahomed

------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store
http://p.sf.net/sfu/nokia-dev2dev
_______________________________________________
QuantLib-users mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/quantlib-users
Reply | Threaded
Open this post in threaded view
|

Re: C# Error when trying to price instrument 'System.ApplicationException : 2nd leg: empty Handle cannot be dereferenced'

Luigi Ballabio
On Wed, 2010-10-27 at 11:51 +0200, Ahmad Mahomed wrote:
> 1) The actual error is being thrown from the
> `discountingswapengine.cpp` calculate routine specifically around
> these lines. The fact that the error is showing 2nd leg implies to me
> that the loop fails at the second iteration (there should be only two
> loops since there are only two legs). The only code here that deals
> with Handles and pointers  from what I gather relate to  the
> 'discountCurve_'.

No, the discount curve seems fine (or the engine would blow at the first
iteration.)  My guess is that you don't pass to your Jibar index the
risk-free curve:

>                     VanillaSwap impliedSwap = new VanillaSwap(
>                         _VanillaSwap.Type.Payer,
>                         10000000.0,
>                         fixedSchedule,
>                         0.1,
>                         Actual365FixedDayCounter,
>                         floatSchedule,
>                         new Jibar(new Period(Frequency.Quarterly)),
>                         0,
>                         Actual365FixedDayCounter);

without a term structure, the Jibar above can return past fixings but
not forecast future ones.  If you replace the Jibar constructor above
with

new Jibar(new Period(Frequency.Quarterly), DiscountingTermStructure)

it might work (unless there are other similar places in the code that
we're not seeing...)

Luigi


--

The idea that an arbitrary naive human should be able to properly
use a given tool without training or understanding is even more
wrong for computing than it is for other tools (e.g. automobiles,
airplanes, guns, power saws).
-- Doug Gwyn



------------------------------------------------------------------------------
Nokia and AT&T present the 2010 Calling All Innovators-North America contest
Create new apps & games for the Nokia N8 for consumers in  U.S. and Canada
$10 million total in prizes - $4M cash, 500 devices, nearly $6M in marketing
Develop with Nokia Qt SDK, Web Runtime, or Java and Publish to Ovi Store
http://p.sf.net/sfu/nokia-dev2dev
_______________________________________________
QuantLib-users mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/quantlib-users