コード例 #1
0
        static void CalibrateModel(ShortRateModel model,
                                   List <CalibrationHelper> helpers)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            var om = new LevenbergMarquardt();

            model.calibrate(helpers, om,
                            new EndCriteria(400, 100, 1.0e-8, 1.0e-8, 1.0e-8), new Constraint(),
                            new List <double>());

            // Output the implied Black volatilities
            for (int i = 0; i < NumRows; i++)
            {
                int    j       = NumCols - i - 1; // 1x5, 2x4, 3x3, 4x2, 5x1
                int    k       = i * NumCols + j;
                double npv     = helpers[i].modelValue();
                double implied = helpers[i].impliedVolatility(npv, 1e-4,
                                                              1000, 0.05, 0.50);
                double diff = implied - SwaptionVols[k];
                Console.WriteLine("{0}x{1}: model {2:0.00000 %}, market {3:0.00000 %}, diff {4:0.00000 %} ",
                                  i + 1, SwapLenghts[j], implied, SwaptionVols[k], diff);
            }
        }
コード例 #2
0
        public DVPLI.EstimationResult Estimate(List <object> data, DVPLI.IEstimationSettings settings = null, DVPLI.IController controller = null, Dictionary <string, object> properties = null)
        {
            DVPLI.InterestRateMarketData irmd = data[0] as DVPLI.InterestRateMarketData;

            //Date today = new Date(15, Month.February, 2002);
            //Date settlement = new Date(19, Month.February, 2002);
            Settings.setEvaluationDate(irmd.Date);



            Handle <YieldTermStructure> termStructure = new Handle <YieldTermStructure>(new Utilities.ZeroRateFunction(irmd.Date, irmd.ZRMarketDates, irmd.ZRMarket));

            //termStructure.link
            HullWhite model = new HullWhite(termStructure);


            IborIndex index = new Euribor6M(termStructure);

            IPricingEngine engine = new JamshidianSwaptionEngine(model);

            List <CalibrationHelper> swaptions = new List <CalibrationHelper>();

            for (int i = 0; i < irmd.SwapDates.Length; i++)
            {
                for (int j = 0; j < irmd.SwapDuration.Length; j++)
                {
                    Quote             vol    = new SimpleQuote(irmd.SwaptionsVolatility[j, i]);
                    CalibrationHelper helper =
                        new SwaptionHelper(new Period((int)irmd.SwapDates[i], TimeUnit.Years),
                                           new Period((int)irmd.SwapDuration[j], TimeUnit.Years),
                                           new Handle <Quote>(vol),
                                           index,
                                           new Period(1, TimeUnit.Years),
                                           new Thirty360(),
                                           new Actual360(),
                                           termStructure,
                                           false);
                    helper.setPricingEngine(engine);
                    swaptions.Add(helper);
                }
            }

            // Set up the optimization problem
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8);
            EndCriteria        endCriteria        = new EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8);

            //Optimize
            model.calibrate(swaptions, optimizationMethod, endCriteria, new Constraint(), new List <double>());
            EndCriteria.Type ecType = model.endCriteria();


            Vector xMinCalculated = model.parameters();
            double yMinCalculated = model.value(xMinCalculated, swaptions);
            Vector xMinExpected   = new Vector(2);

            double yMinExpected = model.value(xMinExpected, swaptions);

            DVPLI.EstimationResult r = new DVPLI.EstimationResult(new string[] { "Alpha", "Sigma" }, new double[] { xMinCalculated[0], xMinCalculated[1] });
            return(r);
        }
コード例 #3
0
        public void minimize_test()
        {
            #region doc_minimize
            // Example from https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm

            // In this example, the Gauss–Newton algorithm will be used to fit a model to
            // some data by minimizing the sum of squares of errors between the data and
            // model's predictions.

            // In a biology experiment studying the relation between substrate concentration [S]
            // and reaction rate in an enzyme-mediated reaction, the data in the following table
            // were obtained:

            double[][] inputs  = Jagged.ColumnVector(new [] { 0.03, 0.1947, 0.425, 0.626, 1.253, 2.500, 3.740 });
            double[]   outputs = new[] { 0.05, 0.127, 0.094, 0.2122, 0.2729, 0.2665, 0.3317 };

            // It is desired to find a curve (model function) of the form
            //
            //   rate = \frac{V_{max}[S]}{K_M+[S]}
            //
            // that fits best the data in the least squares sense, with the parameters V_max
            // and K_M to be determined. Let's start by writing model equation below:

            LeastSquaresFunction function = (double[] parameters, double[] input) =>
            {
                return((parameters[0] * input[0]) / (parameters[1] + input[0]));
            };

            // Now, we can either write the gradient function of the model by hand or let
            // the model compute it automatically using Newton's finite differences method:

            LeastSquaresGradientFunction gradient = (double[] parameters, double[] input, double[] result) =>
            {
                result[0] = -((-input[0]) / (parameters[1] + input[0]));
                result[1] = -((parameters[0] * input[0]) / Math.Pow(parameters[1] + input[0], 2));
            };

            // Create a new Levenberg-Marquardt algorithm
            var gn = new LevenbergMarquardt(parameters: 2)
            {
                Function = function,
                Gradient = gradient,
                Solution = new[] { 0.9, 0.2 } // starting from b1 = 0.9 and b2 = 0.2
            };

            // Find the minimum value:
            gn.Minimize(inputs, outputs);

            // The solution will be at:
            double b1 = gn.Solution[0]; // will be 0.362
            double b2 = gn.Solution[1]; // will be 0.556
            #endregion

            Assert.AreEqual(0.362, b1, 1e-3);
            Assert.AreEqual(0.556, b2, 3e-3);
        }
コード例 #4
0
ファイル: T_Optimizers.cs プロジェクト: cub-/qlnet
        public void nestedOptimizationTest()
        {
            //("Testing nested optimizations...");
            OptimizationBasedCostFunction optimizationBasedCostFunction = new OptimizationBasedCostFunction();
            NoConstraint       constraint         = new NoConstraint();
            Vector             initialValues      = new Vector(1, 0.0);
            Problem            problem            = new Problem(optimizationBasedCostFunction, constraint, initialValues);
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt();
            //Simplex optimizationMethod(0.1);
            //ConjugateGradient optimizationMethod;
            //SteepestDescent optimizationMethod;
            EndCriteria endCriteria = new EndCriteria(1000, 100, 1e-5, 1e-5, 1e-5);

            optimizationMethod.minimize(problem, endCriteria);
        }
コード例 #5
0
        public void misra1a_test()
        {
            LevenbergMarquardt lm = new LevenbergMarquardt(2);

            double[]   outputs = new double[] { 10.07E0, 14.73E0, 17.94E0, 23.93E0, 29.61E0, 35.18E0, 40.02E0, 44.82E0, 50.76E0, 55.05E0, 61.01E0, 66.40E0, 75.47E0, 81.78E0 };
            double[][] inputs  = Jagged.ColumnVector(77.6E0, 114.9E0, 141.1E0, 190.8E0, 239.9E0, 289.0E0, 332.8E0, 378.4E0, 434.8E0, 477.3E0, 536.8E0, 593.1E0, 689.1E0, 760.0E0);

            lm.Function = Function;
            lm.Gradient = Gradient;
            lm.Solution = new double[] { 250, 0.0005 }; // starting values
            double error = lm.Minimize(inputs, outputs);

            Assert.AreEqual(238.944658680792, lm.Solution[0], 1e-5);
            Assert.AreEqual(0.00055014847409921093, lm.Solution[1], 1e-5);
        }
コード例 #6
0
        public void TestOptimization()
        {
            // generate x_i, y_i observations on test function
            var random = new Random();

            int n = 200;

            var matX = Vector <double> .Build.Dense(n);

            var matY = Vector <double> .Build.Dense(n);

            double a = 100;
            double b = 102;

            for (int i = 0; i < n; i++)
            {
                double x = (random.NextDouble() / (Math.PI / 4.0)) - (Math.PI / 8.0);
                double y = (a * Math.Cos(b * x)) + (b * Math.Sin(a * x)) + (random.NextDouble() * 0.1);
                matX[i] = x;
                matY[i] = y;
            }

            LevenbergMarquardt.Function f = (Vector <double> parameters) =>
            {
                // return y_i - f(x_i, parameters) as column vector
                var error = Vector <double> .Build.Dense(n);

                double a2 = parameters[0];
                double b2 = parameters[1];

                for (int i = 0; i < n; i++)
                {
                    double y = (a2 * Math.Cos(b2 * matX[i])) + (b2 * Math.Sin(a2 * matX[i]));
                    error[i] = matY[i] - y;
                }

                return(error);
            };

            var levenbergMarquardt = new LevenbergMarquardt(f);

            var parameters0 = Vector <double> .Build.Dense(2);

            parameters0[0] = 90;
            parameters0[1] = 96;

            var rmsError = levenbergMarquardt.Minimize(parameters0);
        }
コード例 #7
0
        private WcsSolution SolveLM()
        {
            Vector2d temp             = Points[0].Image - Points[1].Image;
            double   imageLength      = temp.Length;
            double   angularSperation = CAAAngularSeparation.Separation(Points[0].Celestial.RA, Points[0].Celestial.Dec, Points[1].Celestial.RA, Points[1].Celestial.Dec);

            // Degrees per pixel
            double scale = angularSperation / imageLength;

            WcsSolution sinit = Solve(Points[0], Points[1]);


            TanSolver ts = new TanSolver(sinit.CenterX, sinit.CenterY, sinit.Rotation - 180, sinit.Scale);

            foreach (CorresponencePoint cp in Points)
            {
                SolveList.Add(new CoorespondenceSolver(ts, cp, width, height));
            }


            regressionParameters.AddRange(ts.Parameters);

            int count = SolveList.Count;

            double[,] data = new double[2, count];
            for (int i = 0; i < count; i++)
            {
                data[0, i] = i;
                data[1, i] = 0;
            }
            Parameter[] observed = new Parameter[] { ParmeterIndex };

            lm = new LevenbergMarquardt(new functionDelegate(SolveFunction), regressionParameters.ToArray(), observed, data);

            for (int d = 0; d < 50; d++)
            {
                lm.Iterate();
            }

            WcsSolution s = ts.GetSolution();

            s.OffsetX = width / 2;
            s.OfsetY  = height / 2;


            return(s);
        }
コード例 #8
0
        public void SetupSolve(CalibrationInfo ci, bool useConstraints, bool radialDistortion)
        {
            foreach (ProjectorEntry pe in ci.Projectors)
            {
                SolveProjector sp = new SolveProjector(pe, ci.DomeSize, ci.ScreenType == ScreenTypes.FishEye ? ProjectionType.FishEye : ProjectionType.Projector, ScreenTypes.Spherical, ci.ScreenType == ScreenTypes.FishEye ? SolveParameters.FishEye : (SolveParameters)ci.SolveParameters);
                sp.RadialDistorion = radialDistortion;
                projectors.Add(sp);

                if (useConstraints)
                {
                    foreach (GroundTruthPoint gt in pe.Constraints)
                    {
                        SolveList.Add(new Constraint(sp, gt));
                    }
                }
            }

            foreach (Edge edge in ci.Edges)
            {
                foreach (EdgePoint pnt in edge.Points)
                {
                    SolveList.Add(new Coorespondence(projectors[edge.Left - 1], projectors[edge.Right - 1], pnt));
                }
            }


            foreach (SolveProjector sp in projectors)
            {
                regressionParameters.AddRange(sp.Parameters);
            }


            int count = SolveList.Count;

            double[,] data = new double[2, count];
            for (int i = 0; i < count; i++)
            {
                data[0, i] = i;
                data[1, i] = 0;
            }
            Parameter[] observed = new Parameter[] { ParmeterIndex };

            lm = new LevenbergMarquardt(new functionDelegate(SolveFunction), regressionParameters.ToArray(), observed, data);
        }
コード例 #9
0
ファイル: T_Optimizers.cs プロジェクト: cub-/qlnet
        public override Vector values(Vector x)
        {
            // dummy nested optimization
            Vector coefficients = new Vector(3, 1.0);
            OneDimensionalPolynomialDegreeN oneDimensionalPolynomialDegreeN = new OneDimensionalPolynomialDegreeN(coefficients);
            NoConstraint       constraint         = new NoConstraint();
            Vector             initialValues      = new Vector(1, 100.0);
            Problem            problem            = new Problem(oneDimensionalPolynomialDegreeN, constraint, initialValues);
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt();
            //Simplex optimizationMethod(0.1);
            //ConjugateGradient optimizationMethod;
            //SteepestDescent optimizationMethod;
            EndCriteria endCriteria = new EndCriteria(1000, 100, 1e-5, 1e-5, 1e-5);

            optimizationMethod.minimize(problem, endCriteria);
            // return dummy result
            Vector dummy = new Vector(1, 0);

            return(dummy);
        }
コード例 #10
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(LevenbergMarquardt obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
コード例 #11
0
        static double CalibrateColorCamera(List <Matrix> worldPoints, List <System.Drawing.PointF> imagePoints, Matrix cameraMatrix, Matrix distCoeffs, Matrix rotation, Matrix translation)
        {
            int nPoints = worldPoints.Count;

            {
                Matrix R, t;
                CameraMath.DLT(cameraMatrix, distCoeffs, worldPoints, imagePoints, out R, out t);
                //var r = Orientation.RotationVector(R);
                var r = RoomAliveToolkit.ProjectorCameraEnsemble.RotationVectorFromRotationMatrix(R);
                rotation.Copy(r);
                translation.Copy(t);
            }

            // pack parameters into vector
            // parameters: fx, fy, cx, cy, k1, k2, + 3 for rotation, 3 translation = 12
            int nParameters = 12;
            var parameters  = new Matrix(nParameters, 1);

            {
                int pi = 0;
                parameters[pi++] = cameraMatrix[0, 0]; // fx
                parameters[pi++] = cameraMatrix[1, 1]; // fy
                parameters[pi++] = cameraMatrix[0, 2]; // cx
                parameters[pi++] = cameraMatrix[1, 2]; // cy
                parameters[pi++] = distCoeffs[0];      // k1
                parameters[pi++] = distCoeffs[1];      // k2
                parameters[pi++] = rotation[0];
                parameters[pi++] = rotation[1];
                parameters[pi++] = rotation[2];
                parameters[pi++] = translation[0];
                parameters[pi++] = translation[1];
                parameters[pi++] = translation[2];
            }

            // size of our error vector
            int nValues = nPoints * 2; // each component (x,y) is a separate entry

            LevenbergMarquardt.Function function = delegate(Matrix p)
            {
                var fvec = new Matrix(nValues, 1);


                // unpack parameters
                int    pi = 0;
                double fx = p[pi++];
                double fy = p[pi++];
                double cx = p[pi++];
                double cy = p[pi++];

                double k1 = p[pi++];
                double k2 = p[pi++];

                var K = Matrix.Identity(3, 3);
                K[0, 0] = fx;
                K[1, 1] = fy;
                K[0, 2] = cx;
                K[1, 2] = cy;

                var d = Matrix.Zero(5, 1);
                d[0] = k1;
                d[1] = k2;

                var r = new Matrix(3, 1);
                r[0] = p[pi++];
                r[1] = p[pi++];
                r[2] = p[pi++];

                var t = new Matrix(3, 1);
                t[0] = p[pi++];
                t[1] = p[pi++];
                t[2] = p[pi++];

                //var R = Orientation.Rodrigues(r);
                var R = RoomAliveToolkit.ProjectorCameraEnsemble.RotationMatrixFromRotationVector(r);



                var x = new Matrix(3, 1);

                int fveci = 0;
                for (int i = 0; i < worldPoints.Count; i++)
                {
                    // transform world point to local camera coordinates
                    x.Mult(R, worldPoints[i]);
                    x.Add(t);

                    // fvec_i = y_i - f(x_i)
                    double u, v;
                    CameraMath.Project(K, d, x[0], x[1], x[2], out u, out v);

                    var imagePoint = imagePoints[i];
                    fvec[fveci++] = imagePoint.X - u;
                    fvec[fveci++] = imagePoint.Y - v;
                }
                return(fvec);
            };

            // optimize
            var calibrate = new LevenbergMarquardt(function);

            while (calibrate.State == LevenbergMarquardt.States.Running)
            {
                var rmsError = calibrate.MinimizeOneStep(parameters);
                Console.WriteLine("rms error = " + rmsError);
            }
            for (int i = 0; i < nParameters; i++)
            {
                Console.WriteLine(parameters[i] + "\t");
            }
            Console.WriteLine();

            // unpack parameters
            {
                int    pi = 0;
                double fx = parameters[pi++];
                double fy = parameters[pi++];
                double cx = parameters[pi++];
                double cy = parameters[pi++];
                double k1 = parameters[pi++];
                double k2 = parameters[pi++];
                cameraMatrix[0, 0] = fx;
                cameraMatrix[1, 1] = fy;
                cameraMatrix[0, 2] = cx;
                cameraMatrix[1, 2] = cy;
                distCoeffs[0]      = k1;
                distCoeffs[1]      = k2;
                rotation[0]        = parameters[pi++];
                rotation[1]        = parameters[pi++];
                rotation[2]        = parameters[pi++];
                translation[0]     = parameters[pi++];
                translation[1]     = parameters[pi++];
                translation[2]     = parameters[pi++];
            }


            return(calibrate.RMSError);
        }
コード例 #12
0
        static double CalibrateDepthCamera(List <Matrix> worldPoints, List <System.Drawing.PointF> imagePoints, Matrix cameraMatrix, Matrix distCoeffs)
        {
            int nPoints = worldPoints.Count;

            // pack parameters into vector
            // parameters: fx, fy, cx, cy, k1, k2 = 6 parameters
            int nParameters = 6;
            var parameters  = new Matrix(nParameters, 1);

            {
                int pi = 0;
                parameters[pi++] = cameraMatrix[0, 0]; // fx
                parameters[pi++] = cameraMatrix[1, 1]; // fy
                parameters[pi++] = cameraMatrix[0, 2]; // cx
                parameters[pi++] = cameraMatrix[1, 2]; // cy
                parameters[pi++] = distCoeffs[0];      // k1
                parameters[pi++] = distCoeffs[1];      // k2
            }

            // size of our error vector
            int nValues = nPoints * 2; // each component (x,y) is a separate entry

            LevenbergMarquardt.Function function = delegate(Matrix p)
            {
                var fvec = new Matrix(nValues, 1);

                // unpack parameters
                int    pi = 0;
                double fx = p[pi++];
                double fy = p[pi++];
                double cx = p[pi++];
                double cy = p[pi++];
                double k1 = p[pi++];
                double k2 = p[pi++];

                var K = Matrix.Identity(3, 3);
                K[0, 0] = fx;
                K[1, 1] = fy;
                K[0, 2] = cx;
                K[1, 2] = cy;

                var d = Matrix.Zero(5, 1);
                d[0] = k1;
                d[1] = k2;

                int fveci = 0;
                for (int i = 0; i < worldPoints.Count; i++)
                {
                    // fvec_i = y_i - f(x_i)
                    double u, v;
                    var    x = worldPoints[i];
                    CameraMath.Project(K, d, x[0], x[1], x[2], out u, out v);

                    var imagePoint = imagePoints[i];
                    fvec[fveci++] = imagePoint.X - u;
                    fvec[fveci++] = imagePoint.Y - v;
                }
                return(fvec);
            };

            // optimize
            var calibrate = new LevenbergMarquardt(function);

            while (calibrate.State == LevenbergMarquardt.States.Running)
            {
                var rmsError = calibrate.MinimizeOneStep(parameters);
                Console.WriteLine("rms error = " + rmsError);
            }
            for (int i = 0; i < nParameters; i++)
            {
                Console.WriteLine(parameters[i] + "\t");
            }
            Console.WriteLine();

            // unpack parameters
            {
                int    pi = 0;
                double fx = parameters[pi++];
                double fy = parameters[pi++];
                double cx = parameters[pi++];
                double cy = parameters[pi++];
                double k1 = parameters[pi++];
                double k2 = parameters[pi++];
                cameraMatrix[0, 0] = fx;
                cameraMatrix[1, 1] = fy;
                cameraMatrix[0, 2] = cx;
                cameraMatrix[1, 2] = cy;
                distCoeffs[0]      = k1;
                distCoeffs[1]      = k2;
            }


            return(calibrate.RMSError);
        }
コード例 #13
0
ファイル: Core.cs プロジェクト: w1r2p1/MiDax
        public static void Run(bool generate = false, bool generate_from_db = false)
        {
            Dictionary <string, string> dicSettings = new Dictionary <string, string>();

            dicSettings["APP_NAME"] = "Midax";
            dicSettings["PUBLISHING_START_TIME"] = "2016-01-22 08:00:00";
            dicSettings["PUBLISHING_STOP_TIME"]  = "2016-01-22 09:00:00";
            dicSettings["REPLAY_MODE"]           = "CSV";
            dicSettings["REPLAY_POPUP"]          = "1";
            dicSettings["TRADING_START_TIME"]    = "2016-01-22 08:45:00";
            dicSettings["TRADING_STOP_TIME"]     = "2016-01-22 08:59:00";
            dicSettings["TRADING_CLOSING_TIME"]  = "2016-01-22 08:57:00";
            dicSettings["TRADING_MODE"]          = "REPLAY";
            dicSettings["TRADING_SIGNAL"]        = "MacD_1_5_IX.D.DAX.DAILY.IP";
            dicSettings["TRADING_LIMIT_PER_BP"]  = "10";
            dicSettings["TRADING_CURRENCY"]      = "GBP";
            Config.Settings = dicSettings;

            string        action = generate ? "Generating" : "Testing";
            var           dax    = new MarketData("DAX:IX.D.DAX.DAILY.IP");
            List <string> tests  = new List <string>();

            Console.WriteLine(action + " WMA...");
            // Test weighted moving average with long intervals
            tests.Add(@"..\..\expected_results\testWMA.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
            {
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMAgen.csv");
            }
            var macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);

            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test weighted moving average with short intervals
            tests = new List <string>();
            tests.Add(@"..\..\expected_results\testWMA2.csv");
            dicSettings["REPLAY_CSV"] = Config.TestList(tests);
            if (generate)
            {
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA2gen.csv");
            }
            dax.Clear();
            macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test weighted moving average with linear time decay
            tests = new List <string>();
            tests.Add(@"..\..\expected_results\testWMA3.csv");
            dicSettings["REPLAY_CSV"]        = Config.TestList(tests);
            dicSettings["TIME_DECAY_FACTOR"] = "3";
            if (generate)
            {
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA3gen.csv");
            }
            dax.Clear();
            macDTestWMA = new ModelMacDTest(dax, 1, 2, 3);
            MarketDataConnection.Instance.Connect(null);
            macDTestWMA.StartSignals();
            macDTestWMA.StopSignals();

            // Test volume weighted moving average with linear time decay

            /*
             * tests = new List<string>();
             * tests.Add(@"..\..\expected_results\testWMA4.csv");
             * dicSettings["REPLAY_CSV"] = Config.TestList(tests);
             * if (generate)
             *  dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testWMA4gen.csv");
             * var macDVTest = new ModelMacDVTest(dax, 1, 2, 3);
             * MarketDataConnection.Instance.Connect(null);
             * macDVTest.StartSignals();
             * macDVTest.StopSignals();*/
            dicSettings.Remove("TIME_DECAY_FACTOR");

            // Test RSI and Correlation indicators
            tests = new List <string>();
            tests.Add(@"..\..\expected_results\testRsiCorrel.csv");
            dicSettings["INDEX_ICEDOW"] = "DOW:IceConnection_DOW";
            dicSettings["INDEX_DOW"]    = "DOW:IX.D.DOW.DAILY.IP";
            dicSettings["INDEX_DAX"]    = "DAX:IX.D.DAX.DAILY.IP";
            dicSettings["REPLAY_CSV"]   = Config.TestList(tests);
            if (generate)
            {
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\testRsiCorrelgen.csv");
            }
            dax.Clear();
            var icedow = new MarketData(dicSettings["INDEX_ICEDOW"]);
            var dow    = new MarketData(dicSettings["INDEX_DOW"]);
            var macD   = new ModelMacDTest(dax, 1, 2, 3);
            //var macDV = new ModelMacDVTest(icedow, 1, 2, 3, dow);
            var moleTest = new ModelMoleTest(macD);

            MarketDataConnection.Instance.Connect(null);
            macD.StartSignals(false);
            //macDV.StartSignals(false);
            moleTest.StartSignals(false);
            MarketDataConnection.Instance.StartListening();
            moleTest.StopSignals(false);
            //macDV.StartSignals(false);
            macD.StopSignals(false);
            MarketDataConnection.Instance.StopListening();

            Console.WriteLine(action + " calibration...");

            // Test a 1mn linear regression
            var mktData    = new MarketData("testLRMktData");
            var updateTime = Config.ParseDateTimeLocal(dicSettings["TRADING_START_TIME"]);

            mktData.TimeSeries.Add(updateTime, new Price(100));
            mktData.TimeSeries.Add(updateTime.AddSeconds(20), new Price(120));
            mktData.TimeSeries.Add(updateTime.AddSeconds(40), new Price(140));
            mktData.TimeSeries.Add(updateTime.AddSeconds(60), new Price(130));
            mktData.TimeSeries.Add(updateTime.AddSeconds(80), new Price(145));
            mktData.TimeSeries.Add(updateTime.AddSeconds(100), new Price(165));
            mktData.TimeSeries.Add(updateTime.AddSeconds(120), new Price(145));
            var linReg      = new IndicatorLinearRegression(mktData, new TimeSpan(0, 2, 0));
            var linRegCoeff = linReg.linearCoeff(updateTime.AddSeconds(120));

            if (Math.Abs(linRegCoeff.Value - 0.821428571428573m) > 1e-8m)
            {
                throw new ApplicationException("Linear regression error");
            }


            // Test the optimization of function a * cos(b * x) + b * sin(a * x) using Levenberg Marquardt
            LevenbergMarquardt.objective_func objFunc = (NRealMatrix x) => { NRealMatrix y = new NRealMatrix(x.Rows, 1);
                                                                             for (int idxRow = 0; idxRow < y.Rows; idxRow++)
                                                                             {
                                                                                 y.SetAt(idxRow, 0, new NDouble(2 * Math.Cos(x[idxRow, 0]) + Math.Sin(2 * x[idxRow, 0])));
                                                                             }
                                                                             return(y); };
            List <double> inputs = new List <double>();
            Random        rnd    = new Random(155);

            for (int idxPt = 0; idxPt < 10; idxPt++)
            {
                inputs.Add(rnd.NextDouble() * 2);
            }
            List <Value> modelParams = new List <Value>();

            modelParams.Add(new Value(-0.2)); modelParams.Add(new Value(0.3));
            LevenbergMarquardt.model_func modelFunc = (NRealMatrix x, NRealMatrix weights) => { NRealMatrix y = new NRealMatrix(x.Rows, 1);
                                                                                                double      a = weights[0, 0]; double b = weights[0, 1];
                                                                                                for (int idxRow = 0; idxRow < y.Rows; idxRow++)
                                                                                                {
                                                                                                    y.SetAt(idxRow, 0, new NDouble(a * Math.Cos(b * x[idxRow, 0]) + b * Math.Sin(a * x[idxRow, 0])));
                                                                                                }
                                                                                                return(y); };
            Func <double, double, double, double> derA = (double a, double b, double x) => Math.Cos(b * x) + b * x * Math.Cos(a * x);
            Func <double, double, double, double> derB = (double a, double b, double x) => - a * x * Math.Sin(b * x) + Math.Sin(a * x);

            LevenbergMarquardt.model_func jacFunc = (NRealMatrix x, NRealMatrix weights) =>
            {
                NRealMatrix jac = new NRealMatrix(x.Rows, 2);
                double      a = weights[0, 0]; double b = weights[0, 1];
                for (int idxRow = 0; idxRow < jac.Rows; idxRow++)
                {
                    jac.SetAt(idxRow, 0, new NDouble(-derA(a, b, x[idxRow, 0])));
                    jac.SetAt(idxRow, 1, new NDouble(-derB(a, b, x[idxRow, 0])));
                }
                return(jac);
            };
            LevenbergMarquardt calibModel = new LevenbergMarquardt(objFunc, inputs, modelParams, modelFunc, jacFunc);

            calibModel.Solve();
            if (Math.Abs(modelParams[0].X - 2) > calibModel.ObjectiveError || Math.Abs(modelParams[1].X - 1) > calibModel.ObjectiveError)
            {
                throw new ApplicationException("LevenbergMarquardt calibration error");
            }

            // Parity-2 problem
            NeuralNetwork ann = new NeuralNetwork(2, 1, new List <int>()
            {
                2
            });
            List <List <double> > annInputs = new List <List <double> >();

            annInputs.Add(new List <double>()
            {
                -1, -1
            });
            annInputs.Add(new List <double>()
            {
                -1, 1
            });
            annInputs.Add(new List <double>()
            {
                1, -1
            });
            annInputs.Add(new List <double>()
            {
                1, 1
            });
            List <List <double> > annOutputs = new List <List <double> >();

            annOutputs.Add(new List <double>()
            {
                1
            });
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                1
            });
            // test forward propagation
            ann._outputs.Neurons[0].Weights[0].X        = 1;
            ann._outputs.Neurons[0].Weights[1].X        = -1;
            ann._outputs.Neurons[0].Weights[2].X        = -1;
            ann._innerLayers[0].Neurons[0].Weights[0].X = 1;
            ann._innerLayers[0].Neurons[0].Weights[1].X = 1;
            ann._innerLayers[0].Neurons[0].Weights[2].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[0].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[1].X = 1;
            ann._innerLayers[0].Neurons[1].Weights[2].X = -1;
            ann._inputs.Neurons[0].Value.X = -1;
            ann._inputs.Neurons[1].Value.X = -1;
            if (Math.Abs(ann._outputs.Neurons[0].Activation() - -0.38873457229297215) > calibModel.ObjectiveError)
            {
                throw new ApplicationException("Neural network forward propagation error");
            }
            // Test neural network training for parity-2 problem
            ann = new NeuralNetwork(2, 1, new List <int>()
            {
                2
            });
            ann.Train(annInputs, annOutputs);

            // Test neural network training for parity-3 problem
            ann = new NeuralNetwork(3, 1, new List <int>()
            {
                2
            });
            annInputs = new List <List <double> >();
            annInputs.Add(new List <double>()
            {
                -1, -1, -1
            });
            annInputs.Add(new List <double>()
            {
                -1, -1, 1
            });
            annInputs.Add(new List <double>()
            {
                -1, 1, -1
            });
            annInputs.Add(new List <double>()
            {
                -1, 1, 1
            });
            annInputs.Add(new List <double>()
            {
                1, -1, -1
            });
            annInputs.Add(new List <double>()
            {
                1, -1, 1
            });
            annInputs.Add(new List <double>()
            {
                1, 1, -1
            });
            annInputs.Add(new List <double>()
            {
                1, 1, 1
            });
            annOutputs = new List <List <double> >();
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                1
            });
            annOutputs.Add(new List <double>()
            {
                1
            });
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                1
            });
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                -1
            });
            annOutputs.Add(new List <double>()
            {
                1
            });
            ann.Train(annInputs, annOutputs);

            Console.WriteLine(action + " live indicators and signals...");
            tests = new List <string>();
            tests.Add(@"..\..\expected_results\core_22_1_2016.csv");
            if (generate_from_db)
            {
                dicSettings["DB_CONTACTPOINT"] = "192.168.1.26";
            }
            dicSettings["REPLAY_MODE"] = generate_from_db ? "DB" : "CSV";
            dicSettings["REPLAY_CSV"]  = Config.TestList(tests);
            if (generate)
            {
                dicSettings["PUBLISHING_CSV"] = string.Format("..\\..\\expected_results\\coregen_22_1_2016.csv");
            }
            MarketDataConnection.Instance.Connect(null);
            dax.Clear();
            var model = new ModelMacDTest(dax);

            model.StartSignals();

            Console.WriteLine(action + " daily indicators...");
            model.StopSignals();
            Thread.Sleep(1000);

            if (!dicSettings.ContainsKey("PUBLISHING_CSV"))
            {
                // the program is expected to throw exceptions in this scope, just press continue if you are debugging
                // all exceptions should be handled, and the program should terminate with a success message box

                // test that the right numer of trades was placed. this is an extra sanity check to make sure the program is not idle
                if (ReplayTester.Instance.NbProducedTrades != ReplayTester.Instance.NbExpectedTrades)
                {
                    model.ProcessError(string.Format("the model did not produced the expected number of trades. It produced {0} trades instead of {1} expected",
                                                     ReplayTester.Instance.NbProducedTrades, ReplayTester.Instance.NbExpectedTrades));
                }

                // test trade booking
                MarketDataConnection.Instance = new ReplayConnection(true);
                model = new ModelMacDTest(dax);
                MarketDataConnection.Instance.Connect(null);
                Console.WriteLine(action + " trade booking...");
                var tradeTime      = Config.ParseDateTimeLocal(dicSettings["TRADING_CLOSING_TIME"]).AddSeconds(-1);
                var tradeTest      = new Trade(tradeTime, dax.Id, SIGNAL_CODE.SELL, 10, 10000m);
                var expectedTrades = new Dictionary <KeyValuePair <string, DateTime>, Trade>();
                expectedTrades[new KeyValuePair <string, DateTime>("###DUMMY_TRADE_REF1###", tradeTime)] = tradeTest;
                ReplayTester.Instance.SetExpectedResults(null, null, expectedTrades, null);
                var task = model.PTF.Subscribe();
                task.Wait();
                model.PTF.BookTrade(tradeTest, dax.Name);
                Thread.Sleep(5000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != -10)
                {
                    throw new ApplicationException("SELL Trade booking error");
                }
                var expectedTrade = new Trade(tradeTime, dax.Id, SIGNAL_CODE.BUY, 10, 10000m);
                expectedTrade.Reference = "###CLOSE_DUMMY_TRADE_REF2###";
                expectedTrade.Id        = "###DUMMY_TRADE_ID1###";
                expectedTrades[new KeyValuePair <string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                model.PTF.ClosePosition(tradeTest, tradeTime);
                Thread.Sleep(5000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != 0)
                {
                    throw new ApplicationException("Trade position closing error");
                }
                expectedTrade.Reference = "###DUMMY_TRADE_REF3###";
                expectedTrade.Id        = "###DUMMY_TRADE_ID2###";
                expectedTrades[new KeyValuePair <string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                model.PTF.BookTrade(new Trade(tradeTest, true, tradeTime), dax.Name);
                Thread.Sleep(5000);
                if (model.PTF.GetPosition(tradeTest.Epic).Quantity != 10)
                {
                    throw new ApplicationException("BUY Trade booking error");
                }
                expectedTrade           = new Trade(tradeTime, dax.Id, SIGNAL_CODE.SELL, 10, 0m);
                expectedTrade.Reference = "###CLOSE_DUMMY_TRADE_REF4###";
                expectedTrade.Id        = "###DUMMY_TRADE_ID2###";
                expectedTrades[new KeyValuePair <string, DateTime>(expectedTrade.Reference, tradeTime)] = expectedTrade;
                Portfolio.Instance.CloseAllPositions(tradeTest.TradingTime);
                Thread.Sleep(5000);

                // test synchronization issues with the broker
                List <string> testsSync = new List <string>();
                testsSync.Add(@"..\..\expected_results\sync.csv");
                dicSettings["REPLAY_CSV"]     = Config.TestList(testsSync);
                MarketDataConnection.Instance = new ReplayCrazySeller();
                model = new ModelMacDTest(dax);
                Console.WriteLine(action + " synchronization...");
                MarketDataConnection.Instance.Connect(null);
                model.StartSignals();
                model.StopSignals();
                testsSync = new List <string>();
                testsSync.Add(@"..\..\expected_results\sync2.csv");
                dicSettings["REPLAY_CSV"]     = Config.TestList(testsSync);
                MarketDataConnection.Instance = new ReplayCrazyBuyer();
                model = new ModelMacDTest(dax);
                MarketDataConnection.Instance.Connect(null);
                model.StartSignals();
                model.StopSignals();

                Console.WriteLine(action + " expected exceptions...");
                dicSettings["REPLAY_CSV"]     = Config.TestList(tests);
                MarketDataConnection.Instance = new ReplayConnection(true);
                MarketDataConnection.Instance.Connect(null);
                List <string> testError = new List <string>();
                testError.Add(@"..\..\expected_results\error.csv");
                dicSettings["REPLAY_CSV"] = Config.TestList(testError);
                var    modelErr = new ModelMacDTest(dax);
                string expected;
                bool   success = false;
                try
                {
                    MarketDataConnection.Instance.Connect(null);
                    modelErr.StartSignals();
                }
                catch (Exception exc)
                {
                    expected = "Test failed: indicator EMA_1_IX.D.DAX.DAILY.IP time 08:30 expected value 9740.791666666666666666666667 != 9740.3";
                    success  = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                    {
                        model.ProcessError(exc.Message, expected);
                    }
                }
                if (!success)
                {
                    model.ProcessError("An expected exception has not been thrown");
                }
                success = false;
                try
                {
                    modelErr.StopSignals();
                }
                catch (Exception exc)
                {
                    model.ProcessError(exc.Message + " - Wrong daily mean exception removed");
                }
                success = false;
                try
                {
                    model.StopSignals();
                }
                catch (Exception exc)
                {
                    model.ProcessError(exc.Message + " - Double EOD publishing exception removed");
                }
                success = false;
                try
                {
                    MarketDataConnection.Instance = new ReplayConnection(true);
                    MarketDataConnection.Instance.Connect(null);
                    model = new ModelMacDTest(new MarketData(dax.Id));
                    model.StartSignals();
                }
                catch (Exception exc)
                {
                    expected = "Test failed: indicator EMA_1_IX.D.DAX.DAILY.IP time 08:30 expected value 9740.791666666666666666666667 != 9740.3";
                    success  = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                    {
                        model.ProcessError(exc.Message, expected);
                    }
                }
                if (!success)
                {
                    model.ProcessError("An expected exception has not been thrown");
                }
                success = false;
                try
                {
                    MarketDataConnection.Instance.Resume();
                }
                catch (Exception exc)
                {
                    expected = "Time series do not accept values in the past";
                    success  = (exc.Message.Replace(" AM", "") == expected);
                    if (!success)
                    {
                        model.ProcessError(exc.Message, expected);
                    }
                }
                if (!success)
                {
                    model.ProcessError("An expected exception has not been thrown");
                }
                model.StopSignals();
                success = false;
            }
        }
コード例 #14
0
ファイル: HestonPricing.cs プロジェクト: DerivAIS/PelicanVert
        static void Main(string[] args)
        {
            DateTime timer = DateTime.Now;

            ////////////////  DATES  //////////////////////////////////////////////

            Calendar calendar       = new TARGET();
            Date     todaysDate     = new Date(15, Month.January, 2017);
            Date     settlementDate = new Date(todaysDate);

            Settings.setEvaluationDate(todaysDate);
            DayCounter dayCounter = new Actual365Fixed();


            ////////////////  MARKET  //////////////////////////////////////////////

            // Spot
            double         underlying  = 4468.17;
            Handle <Quote> underlyingH = new Handle <Quote>(new SimpleQuote(underlying));

            // riskfree
            double riskFreeRate = 0.035;
            Handle <YieldTermStructure> flatTermStructure = new Handle <YieldTermStructure>(new FlatForward(settlementDate, riskFreeRate, dayCounter));

            // dividend
            double dividendYield = 0.0;
            double fixedDiv      = 5.0;

            Handle <YieldTermStructure> flatDividendTS        = new Handle <YieldTermStructure>(new FlatForward(settlementDate, dividendYield, dayCounter));
            Handle <YieldTermStructure> FixedDivTermStructure = new Handle <YieldTermStructure>(new FixedForward(settlementDate, fixedDiv, underlying, dayCounter));

            // vol surface

            Date StartDateVol = settlementDate + new Period(1, TimeUnit.Months);


            List <int> maturityInDays = new InitializedList <int>()
            {
                0, 13, 41, 90, 165, 256, 345, 524, 703
            };
            List <Date> datesVol = new InitializedList <Date>();

            for (int d = 1; d < maturityInDays.Count; d++)
            {
                datesVol.Add(calendar.advance(settlementDate, new Period(maturityInDays[d], TimeUnit.Days)));
            }

            List <double> strikes = new InitializedList <double>()
            {
                3400, 3600, 3800, 4000, 4200, 4400, 4500, 4600, 4800, 5000, 5200, 5400, 5600
            };

            Matrix blackVolMatrix = new Matrix(maturityInDays.Count - 1, strikes.Count, 0.2);
            var    vols           = new InitializedList <double>()
            {
                0.6625, 0.4875, 0.4204, 0.3667, 0.3431, 0.3267, 0.3121, 0.3121,
                0.6007, 0.4543, 0.3967, 0.3511, 0.3279, 0.3154, 0.2984, 0.2921,
                0.5084, 0.4221, 0.3718, 0.3327, 0.3155, 0.3027, 0.2919, 0.2889,
                0.4541, 0.3869, 0.3492, 0.3149, 0.2963, 0.2926, 0.2819, 0.2800,
                0.4060, 0.3607, 0.3330, 0.2999, 0.2887, 0.2811, 0.2751, 0.2775,
                0.3726, 0.3396, 0.3108, 0.2781, 0.2788, 0.2722, 0.2661, 0.2686,
                0.3550, 0.3277, 0.3012, 0.2781, 0.2781, 0.2661, 0.2661, 0.2681,
                0.3428, 0.3209, 0.2958, 0.2740, 0.2688, 0.2627, 0.2580, 0.2620,
                0.3302, 0.3062, 0.2799, 0.2631, 0.2573, 0.2533, 0.2504, 0.2544,
                0.3343, 0.2959, 0.2705, 0.2540, 0.2504, 0.2464, 0.2448, 0.2462,
                0.3460, 0.2845, 0.2624, 0.2463, 0.2425, 0.2385, 0.2373, 0.2422,
                0.3857, 0.2860, 0.2578, 0.2399, 0.2357, 0.2327, 0.2312, 0.2351,
                0.3976, 0.2860, 0.2607, 0.2356, 0.2297, 0.2268, 0.2241, 0.2320
            };


            for (int i = 0; i < vols.Count; i++)
            {
                int testraw = (int)(i % (datesVol.Count));
                int testcol = (int)(i / (datesVol.Count));

                blackVolMatrix[testraw, testcol] = vols[i];
            }



            BlackVarianceSurface mySurface = new BlackVarianceSurface(settlementDate, calendar, datesVol,
                                                                      strikes, Matrix.transpose(blackVolMatrix), dayCounter);

            Handle <BlackVolTermStructure> mySurfaceH = new Handle <BlackVolTermStructure>(mySurface);


            ////////////////  CALIBRATION  //////////////////////////////////////////////

            Period helperPeriod = new Period();

            //helpers
            List <CalibrationHelper> calibrationHelpers = new List <CalibrationHelper>();

            for (int k = 0; k < strikes.Count; k++)
            {
                for (int d = 0; d < datesVol.Count; d++)
                {
                    helperPeriod = new Period(datesVol[d] - settlementDate, TimeUnit.Days);
                    calibrationHelpers.Add(new HestonModelHelper(helperPeriod,
                                                                 calendar,
                                                                 underlying,
                                                                 strikes[k],
                                                                 new Handle <Quote>(new SimpleQuote(blackVolMatrix[d, k])),
                                                                 flatTermStructure,
                                                                 flatDividendTS,
                                                                 CalibrationHelper.CalibrationErrorType.ImpliedVolError));
                }
            }


            // starting data
            double v0    = 0.1;
            double kappa = 1.0;
            double theta = 0.1;
            double sigma = 0.5;
            double rho   = -0.5;

            // model
            HestonProcess hestonProcess = new HestonProcess(flatTermStructure,
                                                            flatDividendTS,
                                                            underlyingH,
                                                            v0, kappa, theta, sigma, rho);

            HestonModel hestonmodel = new HestonModel(hestonProcess);

            AnalyticHestonEngine analyticHestonEngine = new AnalyticHestonEngine(hestonmodel);


            foreach (HestonModelHelper hmh in calibrationHelpers)
            {
                hmh.setPricingEngine(analyticHestonEngine);
            }


            // optimization
            double             tolerance          = 1.0e-8;
            LevenbergMarquardt optimizationmethod = new LevenbergMarquardt(tolerance, tolerance, tolerance);

            hestonmodel.calibrate(calibrationHelpers, optimizationmethod, new EndCriteria(400, 40, tolerance, tolerance, tolerance));

            double        error     = 0.0;
            List <double> errorList = new InitializedList <double>();


            ////////////////  CALIBRATION RESULTS  //////////////////////////////////////////////
            Console.WriteLine("Calbration :");
            Console.WriteLine("-----------");

            foreach (HestonModelHelper hmh in calibrationHelpers)
            {
                error += Math.Abs(hmh.calibrationError());
                errorList.Add(Math.Abs(hmh.calibrationError()));
            }

            Vector hestonParameters = hestonmodel.parameters();

            Console.WriteLine("v0    = {0:0.00%}", hestonParameters[4]);
            Console.WriteLine("kappa = {0:0.00%}", hestonParameters[1]);
            Console.WriteLine("theta = {0:0.00%}", hestonParameters[0]);
            Console.WriteLine("sigma = {0:0.00%}", hestonParameters[2]);
            Console.WriteLine("rho   = {0:0.00%}", hestonParameters[3]);
            Console.WriteLine();
            Console.WriteLine("Total error = {0:0.0000}", error);
            Console.WriteLine("Mean error  = {0:0.0000%}", error / (errorList.Count - 1));
            Console.WriteLine();

            int    StepsPerYear      = 52;
            double absoluteTolerance = 80.0;
            ulong  mcSeed            = 42;

            // MC Heston process
            HestonProcess calibratedHestonProcess = new HestonProcess(flatTermStructure,
                                                                      flatDividendTS,
                                                                      underlyingH,
                                                                      hestonParameters[4],
                                                                      hestonParameters[1],
                                                                      hestonParameters[0],
                                                                      hestonParameters[2],
                                                                      hestonParameters[3]);

            // BS process
            GeneralizedBlackScholesProcessTolerance bsmProcess = new GeneralizedBlackScholesProcessTolerance(underlyingH, FixedDivTermStructure, flatTermStructure, mySurfaceH);

            ////////////////  ENGINES  /////////////////////////////////////////////////


            IPricingEngine mcHestonEngine = new MakeMCEuropeanHestonEngine <PseudoRandom, Statistics>(calibratedHestonProcess)
                                            .withStepsPerYear(StepsPerYear)
                                            .withAbsoluteTolerance(absoluteTolerance)
                                            .withSeed(mcSeed)
                                            .getAsPricingEngine();

            double         absoluteTolerance2      = 1.0;
            IPricingEngine mcGenHestonEngineTestbs = new MakeMCGenericScriptInstrument <PseudoRandom>(bsmProcess)
                                                     .withStepsPerYear(StepsPerYear)
                                                     .withAbsoluteTolerance(absoluteTolerance2)
                                                     .withSeed(mcSeed)
                                                     .value();

            IPricingEngine mcGenHestonEngineTestbs2 = new MakeMCGenericScriptInstrument <PseudoRandom>(calibratedHestonProcess)
                                                      .withStepsPerYear(StepsPerYear)
                                                      .withAbsoluteTolerance(absoluteTolerance2)
                                                      .withSeed(mcSeed)
                                                      .value();


            ////////////////  PRICING  //////////////////////////////////////////////
            Console.WriteLine("Pricing Vanilla:");
            Console.WriteLine("---------------");


            Date     maturity         = new Date(17, Month.May, 2019);
            Exercise europeanExercise = new EuropeanExercise(maturity);

            Option.Type       type           = Option.Type.Call;
            double            strike         = underlying;
            StrikedTypePayoff payoff         = new PlainVanillaPayoff(type, strike);
            VanillaOption     europeanOption = new VanillaOption(payoff, europeanExercise);

            // heston
            europeanOption.setPricingEngine(analyticHestonEngine);
            Console.Write("Heston pricing = {0:0.0000}", europeanOption.NPV());
            Console.WriteLine("  ->   {0:0.0000%}", europeanOption.NPV() / underlying);

            // Mc heston
            europeanOption.setPricingEngine(mcHestonEngine);
            Console.Write("HestMC pricing = {0:0.0000}", europeanOption.NPV());
            Console.Write("  ->   {0:0.0000%}", europeanOption.NPV() / underlying);
            Console.WriteLine("  tolerance   {0:0.0} / {1:0.00%}", absoluteTolerance, absoluteTolerance / underlying);

            // analytic bs
            europeanOption.setPricingEngine(new AnalyticEuropeanEngine(bsmProcess));
            Console.Write("BS pricing     = {0:0.0000}", europeanOption.NPV());
            Console.WriteLine("  ->   {0:0.0000%}", europeanOption.NPV() / underlying);


            Console.WriteLine();
            ////////////////  AUTOCALL HESTON //////////////////////////////////////////////

            List <Date> fixingdates = new InitializedList <Date>();
            double      coupon      = 0.05;
            double      barrierlvl  = 0.6;

            for (int i = 1; i <= 4; i++)
            {
                fixingdates.Add(settlementDate + new Period(i, TimeUnit.Years));
            }

            ScriptGenericAutocall myGenericAutocallHTTEst = new ScriptGenericAutocall(fixingdates, coupon, barrierlvl, underlying);

            myGenericAutocallHTTEst.setPricingEngine(mcGenHestonEngineTestbs);

            Console.WriteLine("Pricing Autocall BS :");
            Console.WriteLine("---------------------");
            Console.WriteLine("test = {0:0.0000}", myGenericAutocallHTTEst.NPV());
            Console.WriteLine("Err = {0:0.0000%}", myGenericAutocallHTTEst.errorEstimate() / myGenericAutocallHTTEst.NPV());
            Console.WriteLine("Samples = {0}", myGenericAutocallHTTEst.samples());
            Console.Write("\n");

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("ProbaCall {1} = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaCall " + i), i + 1);
            }
            Console.WriteLine("ProbaMid = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaMid"));
            Console.WriteLine("probaDown = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.WriteLine("test = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.WriteLine("AvgDown/Proba = {0:0.0000%}", myGenericAutocallHTTEst.inspout("AvgDown") / myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.Write("\n");


            myGenericAutocallHTTEst.setPricingEngine(mcGenHestonEngineTestbs2);

            Console.WriteLine("Pricing Autocall Heston:");
            Console.WriteLine("------------------------");
            Console.WriteLine("test = {0:0.0000}", myGenericAutocallHTTEst.NPV());
            Console.WriteLine("Err = {0:0.0000%}", myGenericAutocallHTTEst.errorEstimate() / myGenericAutocallHTTEst.NPV());
            Console.WriteLine("Samples = {0}", myGenericAutocallHTTEst.samples());
            Console.Write("\n");

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("ProbaCall {1} = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaCall " + i), i + 1);
            }
            Console.WriteLine("ProbaMid = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaMid"));
            Console.WriteLine("probaDown = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.WriteLine("test = {0:0.0000%}", myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.WriteLine("AvgDown/Proba = {0:0.0000%}", myGenericAutocallHTTEst.inspout("AvgDown") / myGenericAutocallHTTEst.inspout("ProbaDown"));
            Console.Write("\n");


            ////////////////  END TEST  //////////////////////////////////////////////
            Console.WriteLine();
            Console.WriteLine(" \nRun completed in {0}", DateTime.Now - timer);
            Console.WriteLine();

            Console.Write("Press any key to continue ...");
            Console.ReadKey();
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: JustDevGuy97/wat-minwd
        static void Main(string[] args)
        {
            // Suppose we would like to fit a circle to the given points.
            double[][] inputs = new double[][]
            {
                new [] { 1.0, 7.0 },
                new [] { 2.0, 6.0 },
                new [] { 5.0, 8.0 },
                new [] { 7.0, 7.0 },
                new [] { 9.0, 5.0 },
                new [] { 3.0, 7.0 }
            };

            // In a least squares sense, we want the distance between a point and
            // the ideal circle center minus the radius to be zero.
            double[] outputs = Vector.Zeros(inputs.GetColumn(0).Length);

            // Setup the solver with the Regression and Gradient functions and an
            // initial solution guess. We'll solve for 3 parameters: the circle
            // center and the radius.
            LevenbergMarquardt lm = new LevenbergMarquardt(3)
            {
                Function = (w, k) =>
                {
                    double dx = w[0] - k[0];
                    double dy = w[1] - k[1];
                    double dr = Math.Sqrt(dx * dx + dy * dy) - w[2];
                    return(dr);
                },

                Gradient = (w, k, m) =>
                {
                    double dx = w[0] - k[0];
                    double dy = w[1] - k[1];
                    double di = Math.Sqrt(dx * dx + dy * dy);
                    m[0] = dx / di;
                    m[1] = dy / di;
                    m[2] = -1;
                },

                Solution = new double[] { 5.3794, 7.2532, 3.037 }
            };

            // Iteratively solve for the optimal solution according to some
            // convergence criteria
            double error = double.MaxValue;

            for (int i = 0; i < 50; i++)
            {
                lm.Minimize(inputs, outputs);
                if (lm.Value < error && error - lm.Value < 1.0e-12)
                {
                    break;
                }
                error = lm.Value;
            }
            double x = lm.Solution[0]; // 4.7398
            double y = lm.Solution[1]; // 2.9835
            double r = lm.Solution[2]; // 4.7142

            Console.WriteLine(x);
            Console.WriteLine(y);
            Console.WriteLine(r);
            Console.ReadLine();
        }
コード例 #16
0
        private void test(double initialSill, double initialRange)
        {

          //  double[] temperature = new double[] { 229.15, 247.85, 256.95, 267.15, 278.15, 285.25, 294.35, 307.95, 323.05, 337.85 };
          //  double[] pressure = new double[] { 133.3224898, 666.6124489, 1333.224898, 2666.449795, 5332.899591, 7999.349386, 13332.24898, 26664.49795, 53328.99591, 101325.0922 };

            double[,] z = new double[2, spatial.GetDistancesValues().Length];

            for (int i = 0; i < spatial.GetDistancesValues().Length; i++)
            {
                z[0, i] = spatial.GetDistancesValues()[i];
                z[1, i] = spatial.GetSemivariancesValues()[i];
            }

            Parameter S = new Parameter(initialSill);
            Parameter R = new Parameter(initialRange);
            Parameter D = new Parameter(0.0);

            Func<double> regressionFunction = () => S * (1 - Math.Exp((-3* Math.Abs(D))/R));
            Parameter[] regressionParameters = new Parameter[] {R, S};
            Parameter[] observedParameters = new Parameter[] { D };
            LevenbergMarquardt levenbergMarquardt = new LevenbergMarquardt(regressionFunction, regressionParameters, observedParameters, z);

            for (int i = 0; i < 50; i++)
            {
                levenbergMarquardt.Iterate();
            }

        
        }
コード例 #17
0
        public void testCachedHullWhite()
        {
            //("Testing Hull-White calibration against cached values...");

            Date today      = new Date(15, Month.February, 2002);
            Date settlement = new Date(19, Month.February, 2002);

            Settings.setEvaluationDate(today);
            Handle <YieldTermStructure> termStructure =
                new Handle <YieldTermStructure>(Utilities.flatRate(settlement, 0.04875825, new Actual365Fixed()));
            //termStructure.link
            HullWhite model = new HullWhite(termStructure);

            CalibrationData[] data = { new CalibrationData(1, 5, 0.1148),
                                       new CalibrationData(2, 4, 0.1108),
                                       new CalibrationData(3, 3, 0.1070),
                                       new CalibrationData(4, 2, 0.1021),
                                       new CalibrationData(5, 1, 0.1000) };
            IborIndex         index = new Euribor6M(termStructure);

            IPricingEngine engine = new JamshidianSwaptionEngine(model);

            List <CalibrationHelper> swaptions = new List <CalibrationHelper>();

            for (int i = 0; i < data.Length; i++)
            {
                Quote             vol    = new SimpleQuote(data[i].volatility);
                CalibrationHelper helper =
                    new SwaptionHelper(new Period(data[i].start, TimeUnit.Years),
                                       new Period(data[i].length, TimeUnit.Years),
                                       new Handle <Quote>(vol),
                                       index,
                                       new Period(1, TimeUnit.Years),
                                       new Thirty360(),
                                       new Actual360(),
                                       termStructure,
                                       false);
                helper.setPricingEngine(engine);
                swaptions.Add(helper);
            }

            // Set up the optimization problem
            // Real simplexLambda = 0.1;
            // Simplex optimizationMethod(simplexLambda);
            LevenbergMarquardt optimizationMethod = new LevenbergMarquardt(1.0e-8, 1.0e-8, 1.0e-8);
            EndCriteria        endCriteria        = new EndCriteria(10000, 100, 1e-6, 1e-8, 1e-8);

            //Optimize
            model.calibrate(swaptions, optimizationMethod, endCriteria, new Constraint(), new List <double>());
            EndCriteria.Type ecType = model.endCriteria();

            // Check and print out results
            #if QL_USE_INDEXED_COUPON
            double cachedA = 0.0488199, cachedSigma = 0.00593579;
            #else
            double cachedA = 0.0488565, cachedSigma = 0.00593662;
            #endif
            double tolerance = 1.120e-5;
            //double tolerance = 1.0e-6;
            Vector xMinCalculated = model.parameters();
            double yMinCalculated = model.value(xMinCalculated, swaptions);
            Vector xMinExpected   = new Vector(2);
            xMinExpected[0] = cachedA;
            xMinExpected[1] = cachedSigma;
            double yMinExpected = model.value(xMinExpected, swaptions);
            if (Math.Abs(xMinCalculated[0] - cachedA) > tolerance ||
                Math.Abs(xMinCalculated[1] - cachedSigma) > tolerance)
            {
                Assert.Fail("Failed to reproduce cached calibration results:\n"
                            + "calculated: a = " + xMinCalculated[0] + ", "
                            + "sigma = " + xMinCalculated[1] + ", "
                            + "f(a) = " + yMinCalculated + ",\n"
                            + "expected:   a = " + xMinExpected[0] + ", "
                            + "sigma = " + xMinExpected[1] + ", "
                            + "f(a) = " + yMinExpected + ",\n"
                            + "difference: a = " + (xMinCalculated[0] - xMinExpected[0]) + ", "
                            + "sigma = " + (xMinCalculated[1] - xMinExpected[1]) + ", "
                            + "f(a) = " + (yMinCalculated - yMinExpected) + ",\n"
                            + "end criteria = " + ecType);
            }
        }
コード例 #18
0
        public IKrigingModel GetFunction(Model model, double sill, double range, double nugget)
        {


             msill = new Parameter(sill);
             mrange = new Parameter(range);
             mnugget = new Parameter(nugget);
             distance = new Parameter();


            // Parameter[] regressionParameters=null;
           //  Parameter[] observedParameters = null; ;
             observedParameters = new Parameter[] { distance };
            // regressionParameters = new Parameter[] { mrange, msill,mnugget };
            DefineParametersCalculation();
            switch (model)
            { 
                case Model.Circular:
                    krigingModel = new ModelCircular();
                    regressionFunction =  () =>
                         distance > 0 && distance <= Math.Abs(this.mrange) ? this.mnugget + (((2 * Math.Abs(this.msill)) / Math.PI) * (((distance / Math.Abs(this.mrange)) * Math.Sqrt(1 - ((distance * distance) / (Math.Abs(this.mrange) * Math.Abs(this.mrange))))) + Math.Asin(distance / Math.Abs(this.mrange)))) : distance >Math.Abs(this.mrange)?this.mnugget +Math.Abs(this.msill):0
                         ;
                    break;
                case Model.Exponential:
                    krigingModel = new ModelExponential();
                    regressionFunction = () =>distance>0?
                   Math.Abs(this.mnugget) + (Math.Abs(this.msill) * (1 - Math.Exp(-3 * Math.Abs(distance) / Math.Abs(this.mrange)))):0;
                    break;
                case Model.Gaussian:
                    krigingModel = new ModelGaussian();
                    regressionFunction = () =>distance>0?
                    Math.Abs(this.mnugget) + (Math.Abs(this.msill) * (1 - Math.Exp(-3 * (Math.Abs(distance) / Math.Abs(this.mrange)) * (Math.Abs(distance) / Math.Abs(this.mrange))))):0;
                    break;
                case Model.Spherical:
                    krigingModel = new ModelSpherical();
                    regressionFunction = () =>

                                    distance > 0 && distance <= Math.Abs(this.mrange) ?
                                             Math.Abs(this.mnugget) + (Math.Abs(this.msill) * ((1.5 * (this.distance / Math.Abs(this.mrange))) -
                                             (0.5 * (this.distance / Math.Abs(this.mrange)) * (this.distance / Math.Abs(this.mrange)) * (this.distance / Math.Abs(this.mrange))))) :
                                             distance > Math.Abs(this.mrange) ?
                                                  Math.Abs(this.mnugget) + Math.Abs(this.msill) :
                                                  0; 

                    break;
            }

            if (regressionParameters.Length == 0)
            {
                krigingModel.Range =range;
                krigingModel.C1 = sill ;
                if (nugget < 0)
                {
                    krigingModel.C0 = 0;
                }
                else
                {
                    krigingModel.C0 = nugget;
                }
                OnChangedKriginParameter(EventArgs.Empty);
                return krigingModel;

            }

             LevenbergMarquardt levenbergMarquardt;

             if (regressionParameters != null)
             {
                 try
                 {

                     levenbergMarquardt = new LevenbergMarquardt(regressionFunction, regressionParameters, observedParameters, z,2);

                     for (int i = 0; i < 50; i++)
                     {
                         levenbergMarquardt.Iterate();
                     }
                     DefineParametersCalculationValues(sill, range, nugget);
                
                 }
                 catch
                 {

                     DefineParametersCalculationValues(sill, range, nugget);
                     krigingModel.Range = range;
                     krigingModel.C1 = sill;
                     if (nugget < 0)
                     {
                         krigingModel.C0 = 0;
                     }
                     else
                     {
                         krigingModel.C0 = nugget;
                     }
                     OnChangedKriginParameter(EventArgs.Empty);
                     return krigingModel;
                 
                 }

             }

             OnChangedKriginParameter(EventArgs.Empty);
             return krigingModel;

        }
コード例 #19
0
        public void testCalibration()
        {
            // Testing calibration of a Libor forward model
            const int    size      = 14;
            const double tolerance = 8e-3;

            double[] capVols = { 0.145708, 0.158465, 0.166248, 0.168672,
                                 0.169007, 0.167956, 0.166261, 0.164239,
                                 0.162082, 0.159923, 0.157781, 0.155745,
                                 0.153776, 0.151950, 0.150189, 0.148582,
                                 0.147034, 0.145598, 0.144248 };

            double[] swaptionVols = { 0.170595, 0.166844, 0.158306, 0.147444,
                                      0.136930, 0.126833, 0.118135, 0.175963,
                                      0.166359, 0.155203, 0.143712, 0.132769,
                                      0.122947, 0.114310, 0.174455, 0.162265,
                                      0.150539, 0.138734, 0.128215, 0.118470,
                                      0.110540, 0.169780, 0.156860, 0.144821,
                                      0.133537, 0.123167, 0.114363, 0.106500,
                                      0.164521, 0.151223, 0.139670, 0.128632,
                                      0.119123, 0.110330, 0.103114, 0.158956,
                                      0.146036, 0.134555, 0.124393, 0.115038,
                                      0.106996, 0.100064 };

            IborIndex index = makeIndex();
            LiborForwardModelProcess    process       = new LiborForwardModelProcess(size, index);
            Handle <YieldTermStructure> termStructure = index.forwardingTermStructure();

            // set-up the model
            LmVolatilityModel volaModel = new LmExtLinearExponentialVolModel(process.fixingTimes(),
                                                                             0.5, 0.6, 0.1, 0.1);

            LmCorrelationModel corrModel = new LmLinearExponentialCorrelationModel(size, 0.5, 0.8);

            LiborForwardModel model = new LiborForwardModel(process, volaModel, corrModel);

            int        swapVolIndex = 0;
            DayCounter dayCounter   = index.forwardingTermStructure().link.dayCounter();

            // set-up calibration helper
            List <CalibrationHelper> calibrationHelper = new List <CalibrationHelper>();

            int i;

            for (i = 2; i < size; ++i)
            {
                Period         maturity = i * index.tenor();
                Handle <Quote> capVol   = new Handle <Quote>(new SimpleQuote(capVols[i - 2]));

                CalibrationHelper caphelper = new CapHelper(maturity, capVol, index, Frequency.Annual,
                                                            index.dayCounter(), true, termStructure, CalibrationHelper.CalibrationErrorType.ImpliedVolError);

                caphelper.setPricingEngine(new AnalyticCapFloorEngine(model, termStructure));

                calibrationHelper.Add(caphelper);

                if (i <= size / 2)
                {
                    // add a few swaptions to test swaption calibration as well
                    for (int j = 1; j <= size / 2; ++j)
                    {
                        Period         len         = j * index.tenor();
                        Handle <Quote> swaptionVol = new Handle <Quote>(
                            new SimpleQuote(swaptionVols[swapVolIndex++]));

                        CalibrationHelper swaptionHelper =
                            new SwaptionHelper(maturity, len, swaptionVol, index,
                                               index.tenor(), dayCounter,
                                               index.dayCounter(),
                                               termStructure, CalibrationHelper.CalibrationErrorType.ImpliedVolError);

                        swaptionHelper.setPricingEngine(new LfmSwaptionEngine(model, termStructure));

                        calibrationHelper.Add(swaptionHelper);
                    }
                }
            }

            LevenbergMarquardt om = new LevenbergMarquardt(1e-6, 1e-6, 1e-6);

            //ConjugateGradient gc = new ConjugateGradient();

            model.calibrate(calibrationHelper,
                            om,
                            new EndCriteria(2000, 100, 1e-6, 1e-6, 1e-6),
                            new Constraint(),
                            new List <double>());

            // measure the calibration error
            double calculated = 0.0;

            for (i = 0; i < calibrationHelper.Count; ++i)
            {
                double diff = calibrationHelper[i].calibrationError();
                calculated += diff * diff;
            }

            if (Math.Sqrt(calculated) > tolerance)
            {
                QAssert.Fail("Failed to calibrate libor forward model"
                             + "\n    calculated diff: " + Math.Sqrt(calculated)
                             + "\n    expected : smaller than  " + tolerance);
            }
        }
コード例 #20
0
ファイル: LevenbergMarquardt.cs プロジェクト: minikie/test
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(LevenbergMarquardt obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }