private NArray Value(Normal normalDistribution)
        {
            double deltaT = 1;
            double r      = 0.1;
            double vol    = 0.3;

            int vectorLength = 5000;
            var optionPrices = new NArray(StorageLocation.Host, vectorLength);

            var variates = NArray.CreateRandom(optionPrices.Length, normalDistribution);

            var logStockPrice = Math.Log(100)
                                + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;

            var forwardStockPrices = NMath.Exp(logStockPrice + r * deltaT);

            // now create deals
            var strikes = Enumerable.Range(0, 1000).Select(i => 80 + 5.0 / 1000).ToArray();
            var deals   = strikes.Select(s =>
                                         new Deal()
            {
                Strike = s, ForwardStockPrices = (i) => { return(forwardStockPrices); }
            })
                          .ToList();

            return(AggregateValuations(deals, vectorLength));
        }
Ejemplo n.º 2
0
        public void BlackScholes()
        {
            NArray s;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                s = 100 * NMath.Exp(NArray.CreateRandom(5, normal) * 0.2);
            }

            double k          = 90;
            var    volatility = 0.2;
            var    t          = 5;
            var    df         = Math.Exp(-0.005 * t);

            var result = NArray.Evaluate(() =>
            {
                var f = s / df;
                return(df * Finance.BlackScholes(CallPut.Call, f, k, volatility, t));
            }, s);

            var sds   = s + 1e-6;
            var check = (df * Finance.BlackScholes(CallPut.Call, sds / df, k, volatility, t)
                         - df * Finance.BlackScholes(CallPut.Call, s / df, k, volatility, t)) * 1e6;

            Assert.IsTrue(TestHelpers.AgreesAbsolute(result[1], check));
        }
        public void SimpleSpeedTest()
        {
            using (var randomStream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                var variates      = NArray.CreateRandom(5000, normalDistribution);
                var variatesArray = GetArray(variates);

                var variates2      = NArray.CreateRandom(5000, normalDistribution);
                var variatesArray2 = GetArray(variates);

                var target = NArray.CreateRandom(5000, normalDistribution);

                var targetArray = GetArray(target);

                TestHelpers.Timeit(() =>
                {
                    for (int i = 0; i < 1000; ++i)
                    {
                        //IntelMathKernelLibrary.Multiply(variatesArray, 0, variatesArray2, 0, targetArray, 0, 5000);
                        //IntelMathKernelLibrary.Exp(variatesArray, 0, targetArray, 0, variatesArray.Length);
                        IntelMathKernelLibrary.ConstantAddMultiply(variatesArray, 0, 5, 0, targetArray, 0, 5000);
                    }
                });
            }
        }
Ejemplo n.º 4
0
        public void WorkedExample()
        {
            NArray x0, x1;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                x0 = NArray.CreateRandom(5000, normal);
                x1 = NArray.CreateRandom(5000, normal);
            }

            var result = NArray.Evaluate(() =>
            {
                return(x0 * x1 + x0 * NMath.Exp(2 * x1));
            }, x0, x1);

            var derivativeWRTx0 = result[1];
            var derivativeWRTx1 = result[2];

            Assert.IsTrue(TestHelpers.AgreesAbsolute(derivativeWRTx0, x1 + NMath.Exp(2 * x1)));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(derivativeWRTx1, x0 + 2 * x0 * NMath.Exp(2 * x1)));

            // can also call in such a way that the expression list is appended to a StringBuilder:
            var logger       = new StringBuilder();
            var loggedResult = NArray.Evaluate(() =>
            {
                return(x0 * x1 + x0 * NMath.Exp(2 * x1));
            }, logger, x0, x1);

            Console.WriteLine(logger.ToString());
        }
Ejemplo n.º 5
0
        public void CUDA()
        {
            var location = StorageLocation.Host;
            var normal   = new Normal(new RandomNumberStream(location), 0, 1);
            var input    = NArray.CreateRandom(1000, normal);
            var result   = NArray.CreateLike(input);

            NArray.Evaluate(() =>
            {
                return(NMath.Exp(input * 0.2 + 6));
            });
        }
Ejemplo n.º 6
0
        public void BlackScholesPerformance()
        {
            double k          = 90;
            var    volatility = 0.2;
            var    t          = 5;

            var s            = new List <NArray>();
            int batchCount   = 1000;
            int vectorLength = 5000;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                for (int i = 0; i < batchCount; ++i)
                {
                    s.Add(100 * NMath.Exp(NArray.CreateRandom(vectorLength, normal) * 0.2));
                }
            }

            var result = NArray.CreateLike(s.First());

            double elapsedTime = TestHelpers.TimeitSeconds(() =>
            {
                for (int i = 0; i < batchCount; ++i)
                {
                    NArray.Evaluate(() =>
                    {
                        return(Finance.BlackScholes(CallPut.Call, s[i], k, volatility, t));
                    }, new List <NArray>(), Aggregator.ElementwiseAdd, new List <NArray> {
                        result
                    });
                }
            });

            Console.WriteLine(string.Format("Time per option price (single core): {0} ns", elapsedTime * 1e9 / (batchCount * vectorLength)));
            Console.WriteLine(string.Format("Valuations per second (single core): {0:F0} million", batchCount * vectorLength / (elapsedTime * 1e6)));
        }
Ejemplo n.º 7
0
        public void DivisionTest()
        {
            NArray a, b;

            using (var stream = new RandomNumberStream(StorageLocation.Host))
            {
                a = NArray.CreateRandom(1000, new Normal(stream, 0, 1));
                b = NArray.CreateRandom(1000, new Normal(stream, 0, 1));
            }

            // First test
            var expected1     = 5.0 / a;
            var expectedDiff1 = -5.0 / (a * a);

            var obtained1 = NArray.Evaluate(() =>
            {
                return(5.0 / a);
            }, a);


            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained1[0], expected1));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained1[1], expectedDiff1));

            // Second test
            var expected2       = a / b;
            var expectedDiff2_1 = 1 / b;
            var expectedDiff2_2 = -a / (b * b);

            var obtained2 = NArray.Evaluate(() =>
            {
                return(a / b);
            }, a, b);

            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[0], expected2));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[1], expectedDiff2_1));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[2], expectedDiff2_2));
        }
Ejemplo n.º 8
0
        public void OptionPricingTest()
        {
            var location = StorageLocation.Host;

            IntelMathKernelLibrary.SetAccuracyMode(VMLAccuracy.HighAccuracy);

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                var optionPricesVector  = new NArray(location, 5000);
                var optionPricesIndexed = new NArray(location, 5000);

                var variates = NArray.CreateRandom(optionPricesVector.Length, normalDistribution);

                TestHelpers.Timeit(() =>
                {
                    VectorForm(variates, optionPricesVector);
                });

                //TestHelpers.Timeit(() =>
                //{
                //    using (NArray.DeferredExecution())
                //    {
                //        VectorForm(variates, optionPricesVector);
                //    }
                //});

                TestHelpers.Timeit(() =>
                {
                    IndexedForm((variates.Storage as ManagedStorage <double>).Array,
                                (optionPricesIndexed.Storage as ManagedStorage <double>).Array);
                });
                Console.WriteLine(
                    TestHelpers.AgreesAbsoluteString(optionPricesVector, optionPricesIndexed));
            }
        }
        /// <summary>
        /// Test of efficiency for a large number of simple vector operations.
        /// In particular, tests enhanced recycling of locals.
        /// </summary>
        public void SimpleTest()
        {
            // create 500 random vectors
            var vectorLength = 5000;
            var vectors      = new NArray[500];

            using (var randomStream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                for (int i = 0; i < vectors.Length; ++i)
                {
                    vectors[i] = NArray.CreateRandom(vectorLength, normalDistribution);
                }
            }
            var watch  = new System.Diagnostics.Stopwatch(); watch.Start();
            var result = NArray.CreateLike(vectors.First());

            for (int i = 0; i < vectors.Length; ++i)
            {
                for (int j = 0; j < vectors.Length; ++j)
                {
                    result.Add(vectors[i] * vectors[j] * 123);
                    //result = result + vectors[i] * vectors[j] * 123;
                }
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            var arrays = vectors.Select(v => (v.Storage as ManagedStorage <double>).Array).ToArray();

            watch.Restart();
            var arrayResult = new double[vectors.First().Length];

            for (int i = 0; i < vectors.Length; ++i)
            {
                for (int j = 0; j < vectors.Length; ++j)
                {
                    for (int k = 0; k < arrayResult.Length; ++k)
                    {
                        arrayResult[k] += arrays[i][k] * arrays[j][k] * 123;
                    }
                }
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Restart();
            result = NArray.CreateLike(vectors.First());
            for (int i = 0; i < vectors.Length; ++i)
            {
                var batch = NArray.Evaluate(() =>
                {
                    NArray res = NArray.CreateScalar(0);
                    for (int j = 0; j < vectors.Length; ++j)
                    {
                        res = res + vectors[i] * vectors[j] * 123;
                    }
                    return(res);
                });
                result += batch;
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
        }
Ejemplo n.º 10
0
        public void TestBlackScholes()
        {
            var location = StorageLocation.Host;

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                double deltaT = 1;
                double r      = 0.1;
                double vol    = 0.3;

                var options = new ParallelOptions();
                options.MaxDegreeOfParallelism = 1;

                var    variates     = NArray.CreateRandom(5000, normalDistribution);
                NArray optionPrices = NArray.CreateLike(variates);
                var    watch        = new Stopwatch(); watch.Start();

                Parallel.For(0, 1000, options, (i) =>
                {
                    optionPrices      = NArray.CreateLike(variates);
                    var logStockPrice = Math.Log(100)
                                        + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                    var stockPrices = NMath.Exp(logStockPrice);

                    optionPrices.Assign(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                });
                Console.WriteLine("Baseline sequential");
                Console.WriteLine(watch.ElapsedMilliseconds); watch.Restart();

                Parallel.For(0, 1000, (i) =>
                {
                    optionPrices      = NArray.CreateLike(variates);
                    var logStockPrice = Math.Log(100)
                                        + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                    var stockPrices = NMath.Exp(logStockPrice);

                    optionPrices.Assign(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                });
                Console.WriteLine("Baseline threaded");
                Console.WriteLine(watch.ElapsedMilliseconds);

                NArray optionPrices2 = NArray.CreateLike(variates);

                watch.Restart();
                var vectorOptions = new DeferredExecution.VectorExecutionOptions()
                {
                    MultipleThreads = true
                };
                Parallel.For(0, 1000, options, (i) =>
                {
                    optionPrices2 = NArray.CreateLike(variates);
                    NArray.Evaluate(optionPrices2, () =>
                    {
                        var logStockPrice = Math.Log(100)
                                            + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                        var stockPrices = NMath.Exp(logStockPrice);

                        return(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                    });
                });
                Console.WriteLine("Deferred sequential");
                Console.WriteLine(watch.ElapsedMilliseconds);
                Console.WriteLine(CheckitString((optionPrices.Storage as ManagedStorage <double>).Array, (optionPrices2.Storage as ManagedStorage <double>).Array));
                watch.Restart();

                Parallel.For(0, 1000, (i) =>
                {
                    //optionPrices2 = NArray.CreateLike(variates);
                    optionPrices2 = NArray.Evaluate(() =>
                    {
                        var logStockPrice = Math.Log(100)
                                            + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                        var stockPrices = NMath.Exp(logStockPrice);

                        return(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                    });
                });
                Console.WriteLine("Deferred threaded");
                Console.WriteLine(watch.ElapsedMilliseconds); watch.Restart();
                Console.WriteLine(CheckitString((optionPrices.Storage as ManagedStorage <double>).Array, (optionPrices2.Storage as ManagedStorage <double>).Array));
            }
        }
Ejemplo n.º 11
0
        public void Example1()
        {
            var location = StorageLocation.Host;

            var watch = new System.Diagnostics.Stopwatch(); watch.Start();

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normal = new Normal(randomStream, 0, 1);
                var test   = NArray.CreateRandom(1000, normal);
                for (int i = 0; i < 363 * 100; ++i)
                {
                    test.FillRandom(normal);
                }
            }
            watch.Stop();
            var elapsed = watch.ElapsedMilliseconds * 5000 / (100 * 1000);

            NArray a, b;

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normal = new Normal(randomStream, 0, 1);
                a = NArray.CreateRandom(5000, normal);
                b = NArray.CreateRandom(5000, normal);
            }

            var expressions = new StringBuilder();
            var result      = NArray.Evaluate(() =>
            {
                return(a * b + a * NMath.Exp(b));
            }, expressions);

            var expressionsDiff = new StringBuilder();
            var resultDiff      = NArray.Evaluate(() =>
            {
                return(a * b + a * NMath.Exp(2 * b));
            }, expressionsDiff, a, b);

            var output = expressionsDiff.ToString();

            var expressionsDiff2 = new StringBuilder();

            var s = NMath.Exp(a) + 5;

            var resultDiff2 = NArray.Evaluate(() =>
            {
                return(Finance.BlackScholes(CallPut.Call, s, 5, 1, 1));
                //return NMath.Exp(NMath.Sqrt(a));
            }, expressionsDiff2, s);

            var check    = (Finance.BlackScholes(CallPut.Call, s + 1e-6, 5, 1, 1) - Finance.BlackScholes(CallPut.Call, s, 5, 1, 1)) / 1e-6;
            var expected = check.DebugDataView.Take(10).ToArray();
            var obtained = resultDiff2[1].DebugDataView.Take(10).ToArray();

            var output2 = expressionsDiff2.ToString();

            Console.Write(output2);

            VectorAccelerator.Tests.TestHelpers.Timeit(() =>
            {
                var resultTiming = NArray.Evaluate(() =>
                {
                    return(Finance.BlackScholes(CallPut.Call, s, 5, 1, 1));
                }, expressionsDiff2);
            });
        }