示例#1
0
        private byte[] ProcessBallJoint(RigidBodyJoint ballJoint)
        {
            try
            {
                List <byte> ballJointBytes = new List <byte>();

                //Adds ID to signify that it's a rotational joint
                ushort ID          = 4;
                byte[] ballJointID = BitConverter.GetBytes(ID);
                ballJointBytes.AddRange(ballJointID);

                foreach (AssemblyJoint joint in ballJoint.Joints)
                {
                    //Adds the ID of the parent STL to the output array
                    STLData parentSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceOne.Name), out parentSTL);
                    byte[] parentIDBytes = BitConverter.GetBytes((uint)(parentSTL.getID()));
                    ballJointBytes.AddRange(parentIDBytes);
                    //Adds the ID of the child STL to the output array
                    STLData childSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceTwo.Name), out childSTL);
                    byte[] childIDBytes = BitConverter.GetBytes((uint)(childSTL.getID()));
                    ballJointBytes.AddRange(childIDBytes);
                    //Adds the vector parallel to the movement onto the array of bytes
                    ballJoint.GetJointData(out object GeometryOne, out object GeometryTwo, out NameValueMap nameMap);
                    Circle vectorCircle    = (Circle)GeometryTwo;
                    byte[] vectorJointData = new byte[12];
                    BitConverter.GetBytes((float)vectorCircle.Center.X).CopyTo(vectorJointData, 0);
                    BitConverter.GetBytes((float)vectorCircle.Center.Y).CopyTo(vectorJointData, 4);
                    BitConverter.GetBytes((float)vectorCircle.Center.Z).CopyTo(vectorJointData, 8);
                    ballJointBytes.AddRange(vectorJointData);
                    //Adds the point of connection relative to the parent part
                    byte[] transJointData             = new byte[12];
                    AssemblyJointDefinition jointData = joint.Definition;
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.X).CopyTo(transJointData, 0);
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.Y).CopyTo(transJointData, 4);
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.Z).CopyTo(transJointData, 8);
                    ballJointBytes.AddRange(transJointData);
                    //Adds the degrees of freedom
                    byte[]         freedomData       = new byte[8];
                    ModelParameter positionData      = (ModelParameter)jointData.AngularPosition;
                    double         relataivePosition = positionData._Value;
                    if (jointData.HasLinearPositionEndLimit)
                    {
                        positionData = (ModelParameter)jointData.AngularPositionEndLimit;
                        BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))).CopyTo(freedomData, 0);
                    }
                    positionData = (ModelParameter)jointData.AngularPositionStartLimit;
                    BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))).CopyTo(freedomData, 4);
                    ballJointBytes.AddRange(freedomData);
                }
                return(ballJointBytes.ToArray());
            }
            catch (Exception e)
            {
                //catches problems
                MessageBox.Show(e.Message + "\n\n\n" + e.StackTrace);
                return(null);
            }
        }
示例#2
0
        public void Initialize()
        {
            IForecastingModel model = null;

            Models = new List <IForecastingModel>();

            AnnModelParameter annPara = new AnnModelParameter();

            model = new NeuralNetworkModel(annPara);
            Models.Add(model);

            Heiflow.AI.SVM.Parameter p = new Heiflow.AI.SVM.Parameter();
            model = new SVMModel(p);
            Models.Add(model);

            ModelParameter mp = new ModelParameter();

            model = new MLRModel(mp);
            Models.Add(model);

            Recognizers = new List <IRecognizer>();

            foreach (var mm in Models)
            {
                var recognizer = new ImageRecognizer(mm, _IImageSetsBuilder, _IColorClassification);
                Recognizers.Add(recognizer);
            }
        }
示例#3
0
        /// <summary>
        /// Ctor for linear regression model
        /// </summary>
        public RegressionModelEquation(string modelName, double[] coefficients, double rmse, double minX, double maxX, double minY, double maxY, string nameX, string nameY, bool normalizeValues)
        {
            IsLinearRegression = true;
            Name             = modelName;
            CreationDate     = DateTime.Now;
            NormalizeValues  = normalizeValues;
            _outputParameter = new ModelParameter
            {
                Id          = XMLWork.FindIDWithName(nameY, Properties.Settings.Default.Languages),
                Coefficient = 1,
                LowerBound  = minY,
                UpperBound  = maxY
            };
            _RMSE            = rmse;
            _inputParameters = new List <ModelParameter>
            {
                new ModelParameter
                {
                    Id          = null,
                    Coefficient = coefficients[0],
                    LowerBound  = null,
                    UpperBound  = null
                },

                new ModelParameter
                {
                    Id          = XMLWork.FindIDWithName(nameX, Properties.Settings.Default.Languages),
                    Coefficient = coefficients[1],
                    LowerBound  = minX,
                    UpperBound  = maxX
                }
            };
        }
        /// <summary>
        /// 获取模型的参数信息
        /// </summary>
        /// <param name="fileData">模型文件数据</param>
        /// <returns>模型参数</returns>
        public static Ai.Hong.FileFormat.QuantModelFormat.QuantModelParameter GetModelParameter(byte[] fileData)
        {
            ModelParameter modelInfo = QuantGetModelParameter(fileData);

            if (modelInfo.allFileCount == int.MaxValue)
            {
                return(null);
            }

            Ai.Hong.FileFormat.QuantModelFormat.QuantModelParameter retModelInfo = new QuantModelFormat.QuantModelParameter();
            retModelInfo.allFileCount       = modelInfo.allFileCount;
            retModelInfo.calFileCount       = modelInfo.calFileCount;
            retModelInfo.innerTestFileCount = modelInfo.innerTestFileCount;
            retModelInfo.outerTestFileCount = modelInfo.outerTestFileCount;

            retModelInfo.fileFirstX   = modelInfo.fileFirstX;
            retModelInfo.fileLastX    = modelInfo.fileLastX;
            retModelInfo.fileXStep    = modelInfo.fileXStep;
            retModelInfo.fileSpecCols = modelInfo.fileSpecCols;

            retModelInfo.modelFirstX   = modelInfo.modelFirstX;
            retModelInfo.modelLastX    = modelInfo.modelLastX;
            retModelInfo.modelSpecCols = modelInfo.modelSpecCols;
            retModelInfo.modelStepX    = modelInfo.modelStepX;

            return(retModelInfo);
        }
        public async Task <IActionResult> CreateActivity([FromBody] JObject activitySpecs)
        {
            // basic input validation
            string zipFileName = activitySpecs["zipFileName"].Value <string>();
            string engineName  = activitySpecs["engine"].Value <string>();

            // define Activities API
            dynamic oauth = await OAuthController.GetInternalAsync();

            ActivitiesApi activitiesApi = new ActivitiesApi();

            activitiesApi.Configuration.AccessToken = oauth.access_token;

            // standard name for this sample
            string appBundleName = zipFileName + "AppBundle";
            string activityName  = zipFileName + "Activity";

            //
            PageString activities = await activitiesApi.ActivitiesGetItemsAsync();

            string qualifiedActivityId = string.Format("{0}.{1}+{2}", NickName, activityName, Alias);

            if (!activities.Data.Contains(qualifiedActivityId))
            {
                // define the activity
                // ToDo: parametrize for different engines...
                string         commandLine  = string.Format(@"$(engine.path)\\{0} /i $(args[inputFile].path) /al $(appbundles[{1}].path)", Executable(engineName), appBundleName);
                ModelParameter inputFile    = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "input file", true, "$(inputFile)");
                ModelParameter inputJson    = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "input json", false, "params.json");
                ModelParameter outputFile   = new ModelParameter(false, false, ModelParameter.VerbEnum.Put, "output file", true, "outputFile.rvt");
                Activity       activitySpec = new Activity(
                    new List <string>()
                {
                    commandLine
                },
                    new Dictionary <string, ModelParameter>()
                {
                    { "inputFile", inputFile },
                    { "inputJson", inputJson },
                    { "outputFile", outputFile }
                },
                    engineName, new List <string>()
                {
                    string.Format("{0}.{1}+{2}", NickName, appBundleName, Alias)
                }, null,
                    string.Format("Description for {0}", activityName), null, activityName);
                Activity newActivity = await activitiesApi.ActivitiesCreateItemAsync(activitySpec);

                // specify the alias for this Activity
                Alias aliasSpec = new Alias(1, null, Alias);
                Alias newAlias  = await activitiesApi.ActivitiesCreateAliasAsync(activityName, aliasSpec);

                return(Ok(new { Activity = qualifiedActivityId }));
            }

            // as this activity points to a AppBundle "dev" alias (which points to the last version of the bundle),
            // there is no need to update it (for this sample), but this may be extended for different contexts
            return(Ok(new { Activity = "Activity already defined" }));
        }
示例#6
0
 public Model(ModelParameter instance, int batch, int inputChannels, int inputWidth, int inputHeight)
 {
     Instance      = instance;
     BatchCount    = batch;
     InputChannels = inputChannels;
     InputWidth    = inputWidth;
     InputHeight   = inputHeight;
 }
 internal GenerationLocationValues()
 {
     EffectsRotation = new Value.Boolean(false);
     Type = new Value.Enum<ParameterType>();
     Point = new PointParameter();
     Sphere = new SphereParameter();
     Model = new ModelParameter();
     Circle = new CircleParameter();
 }
 internal GenerationLocationValues()
 {
     EffectsRotation = new Value.Boolean(false);
     Type            = new Value.Enum <ParameterType>();
     Point           = new PointParameter();
     Sphere          = new SphereParameter();
     Model           = new ModelParameter();
     Circle          = new CircleParameter();
 }
 /// <summary>
 /// Initializes the object.
 /// </summary>
 /// <param name="startDate">The start date.</param>
 /// <param name="endDate">The end date.</param>
 /// <param name="frequency">The frequency of the dates generated.</param>
 public ModelParameterDateSequence(DateTime startDate, DateTime endDate, DateFrequency frequency)
 {
     StartDate = startDate;
     EndDate   = endDate;
     Frequency = frequency;
     GenerateSequenceFromStartDate = true;
     FollowFrequency  = true;
     SkipPeriods      = new ModelParameter((double)0);
     SkipPeriodsArray = new ModelParameter((double)0);
 }
 /// <summary>
 /// Initializes the object.
 /// </summary>
 /// <param name="startDateExpression">The expression for the start date.</param>
 /// <param name="endDateExpression">The expression for the end date.</param>
 /// <param name="frequencyExpression">The expression for the frequency.</param>
 public ModelParameterDateSequence(string startDateExpression, string endDateExpression, string frequencyExpression)
 {
     StartDateExpression           = startDateExpression;
     EndDateExpression             = endDateExpression;
     FrequencyExpression           = frequencyExpression;
     GenerateSequenceFromStartDate = true;
     FollowFrequency  = true;
     SkipPeriods      = new ModelParameter((double)0);
     SkipPeriodsArray = new ModelParameter((double)0);
 }
示例#11
0
        public ModelLocal(DBandMES dbandMES, DataBaseType type, Logger log)
        {
            _dbandMES = dbandMES;
            ModelParameter dbParam = new ModelParameter {
                DataBaseType = type,
                UserName     = _dbandMES.UserName,
                PassWord     = _dbandMES.PassWord,
                Host         = _dbandMES.IP,
                Port         = _dbandMES.Port,
                DBorService  = _dbandMES.DBName
            };

            InitDataBase(dbParam, log);
        }
示例#12
0
        public ModelLocal(SQLSetting setting, DataBaseType type, Logger log)
        {
            _setting = setting;
            ModelParameter dbParam = new ModelParameter {
                DataBaseType = type,
                UserName     = _setting.UserName,
                PassWord     = _setting.PassWord,
                Host         = _setting.IP,
                Port         = _setting.Port,
                DBorService  = _setting.DBName
            };

            InitDataBase(dbParam, log);
        }
示例#13
0
        public ModelOracle(OracleSetting oracleMESSetting, Logger log)
        {
            _setting = oracleMESSetting;
            ModelParameter dbParam = new ModelParameter {
                DataBaseType = DataBaseType.Oracle,
                UserName     = _setting.UserID,
                PassWord     = _setting.PassWord,
                Host         = _setting.Host,
                Port         = _setting.Port,
                DBorService  = _setting.ServiceName
            };

            InitDataBase(dbParam, log);
            IDValue = "SEQ_EM_WQPF_ID.NEXTVAL";
        }
        /// <summary>
        /// Main constructor for computable regression model
        /// </summary>
        /// <param name="outputParameterId">Id of the output parameter of the model</param>
        /// <param name="inputParametersIds">List of Ids of input parameters of the model</param>
        public ComputableRegressionModel(int outputParameterId, List <int> inputParametersIds)
        {
            _outputParameter = new ModelParameter {
                Id = outputParameterId
            };
            _inputParameters = new List <ModelParameter>();
            foreach (var parameterId in inputParametersIds)
            {
                _inputParameters.Add(new ModelParameter {
                    Id = parameterId
                });
            }

            _modelTrained = false;
        }
示例#15
0
 /// <summary>
 /// Ctor for loading from database
 /// </summary>
 public RegressionModelEquation(int id, string name, DateTime creationDate, double rmse, int outputParamId, List <ModelParameter> inputParameters, bool normalizeValues)
 {
     IsLinearRegression = inputParameters.Count == 2;
     Id               = id;
     Name             = name;
     CreationDate     = creationDate;
     NormalizeValues  = normalizeValues;
     _RMSE            = rmse;
     _outputParameter = new ModelParameter
     {
         Id          = outputParamId,
         Coefficient = 1,
         LowerBound  = null,
         UpperBound  = null
     };
     _inputParameters = inputParameters;
 }
示例#16
0
        /// <summary>
        /// 获取模型参数信息
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        private static ModelParameter QuantGetModelParameter(byte[] fileData)
        {
            try
            {
                IntPtr retptr = IntPtr.Zero;

                if (fileData == null || fileData.Length == 0)
                {
                    throw new Exception("Invalid Parameter");
                }

                if (CommonMethod.Is64BitVersion())
                {
                    retptr = SPAGetModelParameter64(fileData, fileData.Length);
                }
                else
                {
                    retptr = SPAGetModelParameter32(fileData, fileData.Length);
                }

                if (retptr == IntPtr.Zero)
                {
                    throw new Exception(FileFormat.GetDLLErrorMessage());
                }

                bool retOK   = true;
                var  retData = CommonMethod.CopyStructureFromIntptrAndFree <ModelParameter>(ref retptr, out retOK);
                if (!retOK)
                {
                    ErrorString          = "Invalid data reading";
                    retData.allFileCount = int.MaxValue;    //错误
                }

                return(retData);
            }
            catch (Exception ex)
            {
                ErrorString = ex.Message;
                var retData = new ModelParameter();
                retData.allFileCount = int.MaxValue;
                return(retData);
            }
        }
示例#17
0
    // Use this for initialization
    void Start()
    {
        if (!cell)
        {
            throw new System.Exception("Cell not found!!!");
        }
        GameController gc = GameObject.Find("GameController").GetComponent <GameController>();

        mParameter = gc.Parameter;

        // Overwrite parameter from unity to match screen
        mParameter.EpithelialCellsPerRow    = cellHorizontalCount;
        mParameter.EpithelialCellsPerColumn = cellVerticalCount;

        // Initializing chemokine concentration to 0
        mCurrentCheConcentration = Vector <double> .Build.Dense(mParameter.EpithelialCellsPerRow *mParameter.EpithelialCellsPerColumn, 0);

        //Initialize our 2D Transform array with the width and height
        cellMap = new GameObject[cellHorizontalCount, cellVerticalCount];

        //Iterate over each future tile positions for x and y
        for (int z = 0; z < cellVerticalCount; z++)
        {
            for (int x = 0; x < cellHorizontalCount; x++)
            {
                //Instantiate tile prefab at the desired position as a Transform object
                //var offset = z % 2 == 0 ? cellTileWidth / 2 : 0;
                //var xCoord = x * cellTileWidth - gc.Width - offset;
                //var zCoord = z * cellTileHeight - gc.Height;
                var       xCoord = x * gc.Width / cellHorizontalCount - gc.Width / 2;
                var       zCoord = z * gc.Height / cellVerticalCount - gc.Height / 2;
                Transform tile   = Instantiate(cell.transform, new Vector3(xCoord, 0, zCoord), Quaternion.identity, transform) as Transform;
                //Set the tiles parent to the GameObject this script is attached to
                //tile.parent = transform;
                //Set the 2D map array element to the current tile that we just created.
                cellMap[x, z] = tile.gameObject;
            }
        }

        StartCoroutine(CalculateChemokine());
    }
示例#18
0
        /// <summary>
        /// Assigns new trial values for x in order to use it
        /// for the evaluation of the constraints and the objective function.
        /// </summary>
        /// <param name="project">The project where to evaluate.</param>
        /// <param name="x">The vector of x values.</param>
        /// <returns>A <see cref="SquaredGaussianModel"/> set with the values.</returns>
        internal static SquaredGaussianModel Assign(ProjectROV project, Vector x)
        {
            Engine.Parser.NewContext();

            SquaredGaussianModel model = project.Processes[0].Plugin as SquaredGaussianModel;

            // Assign the new values.
            ModelParameter a1 = model.a1 as ModelParameter;
            ModelParameter s1 = model.sigma1 as ModelParameter;

            a1.m_Value = (RightValue)x[0];
            s1.m_Value = (RightValue)x[1];

            bool errors = model.Parse(null);

            if (errors)
            {
                throw new Exception("Cannot Assing model");
            }

            return(model);
        }
示例#19
0
        /// <summary>
        /// Ctor for multiple regression model
        /// </summary>
        public RegressionModelEquation(string modelName, string outputParamName, List <string> inputParamNames, double rmse, double[] equationCoefficients,
                                       string[] equationParametersNames, double[] equationParametersLowerBounds, double[] equationParametersUpperBounds, bool normalizeValues)
        {
            IsLinearRegression = false;
            Name             = modelName;
            CreationDate     = DateTime.Now;
            NormalizeValues  = normalizeValues;
            _outputParameter = new ModelParameter
            {
                Id          = XMLWork.FindIDWithName(outputParamName, Properties.Settings.Default.Languages),
                Coefficient = 1,
                LowerBound  = null,
                UpperBound  = null
            };

            _RMSE            = rmse;
            _inputParameters = new List <ModelParameter>
            {
                new ModelParameter
                {
                    Id          = null,
                    Coefficient = equationCoefficients[0],
                    LowerBound  = null,
                    UpperBound  = null
                }
            };
            for (int i = 1; i < equationCoefficients.Length; i++)
            {
                _inputParameters.Add(new ModelParameter
                {
                    Id          = XMLWork.FindIDWithName(equationParametersNames[i - 1], Properties.Settings.Default.Languages),
                    Coefficient = equationCoefficients[i],
                    LowerBound  = equationParametersLowerBounds[i - 1],
                    UpperBound  = equationParametersUpperBounds[i - 1]
                });
            }
        }
 /// <summary>
 /// Initializes the object.
 /// </summary>
 /// <param name="startDateExpression">The expression for the start date.</param>
 /// <param name="endDateExpression">The expression for the end date.</param>
 /// <param name="frequencyExpression">The expression for the frequency.</param>
 public ModelParameterDateSequence(string startDateExpression, string endDateExpression, string frequencyExpression)
 {
     StartDateExpression = startDateExpression;
     EndDateExpression = endDateExpression;
     FrequencyExpression = frequencyExpression;
     GenerateSequenceFromStartDate = true;
     FollowFrequency = true;
     SkipPeriods = new ModelParameter((double)0);
 }
 /// <summary>
 /// Initializes the object.
 /// </summary>
 /// <param name="startDate">The start date.</param>
 /// <param name="endDate">The end date.</param>
 /// <param name="frequency">The frequency of the dates generated.</param>
 public ModelParameterDateSequence(DateTime startDate, DateTime endDate, DateFrequency frequency)
 {
     StartDate = startDate;
     EndDate = endDate;
     Frequency = frequency;
     GenerateSequenceFromStartDate = true;
     FollowFrequency = true;
     SkipPeriods = new ModelParameter((double)0);
 }
        /// <summary>
        /// Initializes the object based on the serialized data.
        /// </summary>
        /// <param name="info">The SerializationInfo that holds the serialized object data.</param>
        /// <param name="context">The StreamingContext that contains contextual
        /// information about the source.</param>
        public ModelParameterDateSequence(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            // Set the default for GenerateSequenceFromStartDate and FollowFrequency
            GenerateSequenceFromStartDate = true;
            FollowFrequency = true;

            int serialializedVersion;
            try
            {
                serialializedVersion = info.GetInt32("_VersionDateSequence");
            }
            catch
            {
                serialializedVersion = 0;
            }

            if (serialializedVersion < 2)
            {
                #region No expressions
                try
                {
                    this.StartDate = new DateTime(info.GetInt64("_StartDate"));
                    this.EndDate = new DateTime(info.GetInt64("_EndDate"));
                }
                catch (Exception)
                {
                    // In case the calibration time was serialized in a different way.
                    this.StartDate = info.GetDateTime("_StartDate");
                    this.EndDate = info.GetDateTime("_EndDate");
                }

                int frequency = info.GetInt32("_Frequency");
                Array enumValues = Enum.GetValues(typeof(DateFrequency));
                foreach (DateFrequency value in enumValues)
                {
                    if ((int)value == frequency)
                    {
                        Frequency = value;
                        break;
                    }
                }

                if (serialializedVersion >= 1)
                {
                    // Introduction of ExcludeStartDate
                    bool exclude = info.GetBoolean("_ExcludeStartDate");
                    SkipPeriods = exclude ? new ModelParameter(1) : new ModelParameter((double)0);
                }
                else
                {
                    SkipPeriods = new ModelParameter((double)0);
                }

                #endregion // No expressions
            }
            else
            {
                if (serialializedVersion < 4)
                {
                    string tmpS = info.GetString("_StartDateExpression");
                    DateTime tmpD;
                    if (DateTime.TryParseExact(tmpS, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out tmpD))
                        StartDate = tmpD;
                    else
                        StartDateExpression = new ModelParameter(tmpS);

                    tmpS = info.GetString("_EndDateExpression");
                    if (DateTime.TryParseExact(tmpS, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out tmpD))
                        EndDate = tmpD;
                    else
                        EndDateExpression = new ModelParameter(tmpS);
                }
                else
                {
                    StartDateExpression = (ModelParameter)info.GetValue("_StartDateExpression", typeof(ModelParameter));
                    EndDateExpression = (ModelParameter)info.GetValue("_EndDateExpression", typeof(ModelParameter));
                    SetupExportedIDs();
                }

                FrequencyExpression = info.GetString("_FrequencyExpression");

                if (serialializedVersion >= 3)
                {
                    // FollowFrequency and GenerateSequenceFromStartDate in version 3
                    FollowFrequency = info.GetBoolean("_FollowFrequency");
                    GenerateSequenceFromStartDate = info.GetBoolean("_GenerateSequenceFromStartDate");
                }

                // Skip Periods introduced in version 5
                if (serialializedVersion < 5)
                {
                    bool exclude = info.GetBoolean("_ExcludeStartDate");
                    SkipPeriods = exclude ? new ModelParameter(1) : new ModelParameter((double)0);
                }
                else
                {
                    SkipPeriods = (ModelParameter)info.GetValue("_SkipPeriods", typeof(ModelParameter));
                }
            }
        }
示例#23
0
        public void Test()
        {
            Engine.MultiThread = true;

            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim = 20000;
            int n_steps = 1024;
            double a = 0.2;
            double DR = 0.02;
            double r0 = 0.015;
            double a1 = 0.02;
            double sigma1 = 0.01;
            double maturityOpt = 5.0;
            double strike = 0.005;
            double tau = 0.5;
            double strike2 = 1.0 / (1.0 + strike * tau);

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");
            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");
            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pa = new ModelParameter(a, "a");
            Pa.VarName = "a";
            rov.Symbols.Add(Pa);

            ModelParameter PDR = new ModelParameter(DR, "PDR");
            PDR.VarName = "DR";
            rov.Symbols.Add(PDR);

            ModelParameter Pr0 = new ModelParameter(r0, "r0");
            Pr0.VarName = "r0";
            rov.Symbols.Add(Pr0);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");
            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            AFunction zerorate = new AFunction(rov);
            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)("(1-exp(-a*x1))*DR + r0");
            rov.Symbols.Add(zerorate);

            HW1 process = new HW1(a1, sigma1, "@zr");

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@V1";

            OptionTree op = new OptionTree(rov);

            // 1) RATE FUNCTION, with this the price is higher than the theoretical one
            // op.PayoffInfo.PayoffExpression = "tau*max(rate(TT;tau;@v1) - strike; 0)";
            // 2) OBTAIN RATE FROM bond = exp(-rate*t),
            // with this the price is higher than the theoretical one but it's more near than 1)
            // op.PayoffInfo.PayoffExpression = "tau*max(-ln(bond(TT;TT+tau;@v1))/tau - strike; 0)";
            // 3) CONVERT RATE from discrete to continuous through (1+r_d) = exp(r_c)
            // In this way the price is the same as the theoretical one.
            op.PayoffInfo.PayoffExpression = "tau*max(ln(1+rate(TT;tau;@v1)) - strike; 0)";

            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturityOpt;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;
            double samplePrice = price.value;

            double sampleDevSt = price.stdDev / Math.Sqrt(2.0 * (double)n_sim);

            // Calculation of the theoretical value of the caplet.
            CapHW1 cap = new CapHW1(zerorate);
            double theoreticalPrice = cap.HWCaplet(a1, sigma1, maturityOpt,
                                                   maturityOpt + tau, strike2);
            Console.WriteLine("Theoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.Less(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#24
0
        public void TestSimulation()
        {
            Engine.MultiThread = true;

            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;
            int    n_sim      = 10000;
            int    n_steps    = 512;
            double strike     = 90.0;
            double maturity   = 2.0;
            double rate       = 0.1;
            double dy         = 0.05;
            double volatility = 0.2;
            double S0         = 100;

            ModelParameter Pstrike = new ModelParameter(strike, string.Empty, "strike");

            rov.Symbols.Add(Pstrike);

            ModelParameter PS0 = new ModelParameter(S0, string.Empty, "S0");

            rov.Symbols.Add(PS0);

            AFunction payoff = new AFunction(rov);

            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            AFunction rfunc = new AFunction(rov);

            rfunc.VarName = "r";
            rfunc.m_IndependentVariables = 1;
            rfunc.m_Value = (RightValue)rate;
            rov.Symbols.Add(rfunc);

            AFunction qfunc = new AFunction(rov);

            qfunc.VarName = "q";
            qfunc.m_IndependentVariables = 1;
            qfunc.m_Value = (RightValue)dy;
            rov.Symbols.Add(qfunc);

            AFunction volfunc = new AFunction(rov);

            volfunc.VarName = "localvol";
            volfunc.m_IndependentVariables = 2;
            volfunc.m_Value = (RightValue)volatility;
            rov.Symbols.Add(volfunc);

            DupireProcess process = new DupireProcess();

            process.s0       = (ModelParameter)"S0";
            process.r        = (ModelParameter)"@r";
            process.q        = (ModelParameter)"@q";
            process.localVol = (ModelParameter)"@localvol";

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);

            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;
            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "payoff(v1)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity;
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);
            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);
            ResultItem price       = rov.m_ResultList[0] as ResultItem;
            double     samplePrice = price.value;
            double     sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            // Calculation of the theoretical value of the call.
            double theoreticalPrice = BlackScholes.Call(rate, S0, strike, volatility, maturity, dy);

            Console.WriteLine("Theoretical Price  = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price  = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.LessOrEqual(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#25
0
        public void Test()
        {
            Engine.MultiThread = true;

            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int    n_sim   = 100000;
            int    n_steps = 256;
            double strike  = 90.0;
            double tau     = 2.0;
            double rate    = 0.1;
            double dy      = 0.07;

            ModelParameter pStrike = new ModelParameter(strike, "strike");

            pStrike.VarName = "strike";
            rov.Symbols.Add(pStrike);

            AFunction payoff = new AFunction(rov);

            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            AFunction zrfunc = new AFunction(rov);

            zrfunc.VarName = "zr";
            zrfunc.m_IndependentVariables = 1;
            zrfunc.m_Value = (RightValue)rate;
            rov.Symbols.Add(zrfunc);

            AFunction dyfunc = new AFunction(rov);

            dyfunc.VarName = "dy";
            dyfunc.m_IndependentVariables = 1;
            dyfunc.m_Value = (RightValue)dy;
            rov.Symbols.Add(dyfunc);

            HestonExtendedProcess process = new HestonExtendedProcess();

            process.k           = (ModelParameter)2.5;
            process.theta       = (ModelParameter)0.4;
            process.sigma       = (ModelParameter)0.2;
            process.S0          = (ModelParameter)100.0;
            process.V0          = (ModelParameter)0.3;
            process.zrReference = (ModelParameter)"@zr";
            process.dyReference = (ModelParameter)"@dy";
            double discount = Math.Exp(-rate * tau);

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);

            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = 0.0;

            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "payoff(v1a)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)tau;
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price       = rov.m_ResultList[0] as ResultItem;
            double     samplePrice = discount * price.value;
            double     sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            // Calculates the theoretical value of the call.
            Vector param = new Vector(5);

            param[0] = process.k.V();
            param[1] = process.theta.V();
            param[2] = process.sigma.V();
            param[3] = 0.0;
            param[4] = process.V0.V();
            HestonCall hestonCall       = new HestonCall();
            double     theoreticalPrice = hestonCall.HestonCallPrice(param, process.S0.V(),
                                                                     tau, strike, rate, dy);

            Console.WriteLine("Theoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.Less(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#26
0
        private byte[] ProcessLinearJoint(RigidBodyJoint linearJoint, JointData jointDataObject)
        {
            try {
                ArrayList linearJointBytes = new ArrayList();

                //Adds ID to signify that it's a linear joint
                ushort ID            = 1;
                byte[] linearJointID = BitConverter.GetBytes(ID);
                linearJointBytes.Add(linearJointID);

                foreach (AssemblyJoint joint in linearJoint.Joints)
                {
                    //Adds the ID of the parent STL to the output array
                    STLData parentSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceOne.Name), out parentSTL);
                    byte[] parentIDBytes = BitConverter.GetBytes((uint)(parentSTL.getID()));
                    linearJointBytes.Add(parentIDBytes);
                    //Adds the ID of the child STL to the output array
                    STLData childSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceTwo.Name), out childSTL);
                    byte[] childIDBytes = BitConverter.GetBytes((uint)(childSTL.getID()));
                    linearJointBytes.Add(childIDBytes);
                    //Adds the vector parallel to the movement onto the array of bytes
                    object       GeometryOne, GeometryTwo;
                    NameValueMap nameMap;
                    linearJoint.GetJointData(out GeometryOne, out GeometryTwo, out nameMap);
                    Line   vectorLine      = (Line)GeometryTwo;
                    byte[] vectorJointData = new byte[12];
                    BitConverter.GetBytes(vectorLine.RootPoint.X).CopyTo(vectorJointData, 0);
                    BitConverter.GetBytes(vectorLine.RootPoint.Y).CopyTo(vectorJointData, 4);
                    BitConverter.GetBytes(vectorLine.RootPoint.Z).CopyTo(vectorJointData, 8);
                    linearJointBytes.Add(vectorJointData);
                    //Adds the point of connection relative to the parent part
                    byte[] transJointData             = new byte[12];
                    AssemblyJointDefinition jointData = joint.Definition;
                    BitConverter.GetBytes(jointData.OriginTwo.Point.X).CopyTo(transJointData, 0);
                    BitConverter.GetBytes(jointData.OriginTwo.Point.Y).CopyTo(transJointData, 4);
                    BitConverter.GetBytes(jointData.OriginTwo.Point.Z).CopyTo(transJointData, 8);
                    linearJointBytes.Add(transJointData);
                    //Adds the degrees of freedom
                    byte[]         freedomData       = new byte[8];
                    ModelParameter positionData      = (ModelParameter)jointData.LinearPosition;
                    double         relataivePosition = positionData._Value;
                    positionData = (ModelParameter)jointData.LinearPositionEndLimit;
                    BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))).CopyTo(freedomData, 0);
                    positionData = (ModelParameter)jointData.LinearPositionStartLimit;
                    BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))).CopyTo(freedomData, 4);
                    linearJointBytes.Add(freedomData);
                    linearJointBytes.Add(processJointAttributes(jointDataObject));
                }
                object[] tempArray     = linearJointBytes.ToArray();
                byte[]   returnedArray = new byte[tempArray.Length];
                tempArray.CopyTo(returnedArray, 0);
                return(returnedArray);
            }
            catch (Exception e) {
                //catches problems
                MessageBox.Show(e.Message + "\n\n\n" + e.StackTrace);
                return(null);
            }
        }
示例#27
0
        private byte[] ProcessCylindricalJoint(RigidBodyJoint cylindricalJoint)
        {
            try
            {
                List <byte> cylindricalJointBytes = new List <byte>();

                //Adds ID to signify that it's a cylindrical joint
                cylindricalJointBytes.AddRange(BitConverter.GetBytes((ushort)2));

                foreach (AssemblyJoint joint in cylindricalJoint.Joints)
                {
                    //Adds the ID of the parent STL to the output array
                    STLData parentSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceOne.Name), out parentSTL);
                    byte[] parentIDBytes = BitConverter.GetBytes((uint)(parentSTL.getID()));
                    cylindricalJointBytes.AddRange(parentIDBytes);
                    //Adds the ID of the child STL to the output array
                    STLData childSTL = new STLData();
                    STLDictionary.TryGetValue(NameFilter(joint.OccurrenceTwo.Name), out childSTL);
                    byte[] childIDBytes = BitConverter.GetBytes((uint)(childSTL.getID()));
                    cylindricalJointBytes.AddRange(childIDBytes);
                    //Adds the vector normal to the plane of rotation
                    cylindricalJoint.GetJointData(out object GeometryOne, out object GeometryTwo, out NameValueMap nameMap);

                    /* Circle vectorCircle = (Circle)GeometryTwo;
                     * byte[] vectorJointData = new byte[12];
                     * BitConverter.GetBytes((float)vectorCircle.Center.X).CopyTo(vectorJointData, 0);
                     * BitConverter.GetBytes((float)vectorCircle.Center.Y).CopyTo(vectorJointData, 4);
                     * BitConverter.GetBytes((float)vectorCircle.Center.Z).CopyTo(vectorJointData, 8);
                     * cylindricalJointBytes.AddRange(vectorJointData);
                     *///Adds the vector parallel to the movement
                    MessageBox.Show(GeometryTwo.GetType().ToString());
                    //Adds the vector parallel to movement
                    Line   vectorLine      = (Line)GeometryTwo;
                    byte[] vectorJointData = new byte[12];
                    BitConverter.GetBytes((float)vectorLine.RootPoint.X).CopyTo(vectorJointData, 0);
                    BitConverter.GetBytes((float)vectorLine.RootPoint.Y).CopyTo(vectorJointData, 4);
                    BitConverter.GetBytes((float)vectorLine.RootPoint.Z).CopyTo(vectorJointData, 8);
                    cylindricalJointBytes.AddRange(vectorJointData);
                    //Adds the point of connection relative to the parent part
                    byte[] transJointData             = new byte[12];
                    AssemblyJointDefinition jointData = joint.Definition;
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.X).CopyTo(transJointData, 0);
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.Y).CopyTo(transJointData, 4);
                    BitConverter.GetBytes((float)jointData.OriginTwo.Point.Z).CopyTo(transJointData, 8);
                    cylindricalJointBytes.AddRange(transJointData);
                    //Adds the degrees of freedom
                    List <byte>    freedomData       = new List <byte>();
                    ModelParameter positionData      = (ModelParameter)jointData.AngularPosition;
                    double         relataivePosition = positionData._Value;
                    if (jointData.HasLinearPositionEndLimit)
                    {
                        positionData = (ModelParameter)jointData.LinearPositionEndLimit;
                        freedomData.AddRange(BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))));
                    }
                    if (jointData.HasLinearPositionStartLimit)
                    {
                        positionData = (ModelParameter)jointData.LinearPositionStartLimit;
                        freedomData.AddRange(BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))));
                    }
                    if (jointData.HasAngularPositionLimits)
                    {
                        positionData = (ModelParameter)jointData.AngularPositionEndLimit;
                        freedomData.AddRange(BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))));
                        positionData = (ModelParameter)jointData.AngularPositionStartLimit;
                        freedomData.AddRange(BitConverter.GetBytes((float)(Math.Abs(relataivePosition) - Math.Abs(positionData._Value))));
                    }
                    if (freedomData != null)
                    {
                        cylindricalJointBytes.AddRange(freedomData);
                    }
                }
                return(cylindricalJointBytes.ToArray());
            }
            catch (Exception e)
            {
                //catches problems
                MessageBox.Show(e.Message + "\n\n\n" + e.StackTrace);
                return(null);
            }
        }
示例#28
0
        public void Test()
        {
            double nu       = 0.6;
            double theta    = -0.2;
            double sigma    = 0.2;
            double rate     = 0.02;
            double dy       = 0.01;
            double s0       = 1;
            double maturity = 2.0;
            double strike   = 1.2;
            Vector mat      = new Vector(1) + maturity;
            Vector k        = new Vector(1) + strike;

            // Calculates the theoretical value of the call.
            double theoreticalPrice = VarianceGammaOptionsCalibration.VGCall(theta, sigma, nu,
                                                                             maturity, strike,
                                                                             dy, s0, rate);

            Engine.MultiThread = true;
            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim   = 50000;
            int n_steps = 512;

            ModelParameter paramStrike = new ModelParameter(strike, "strike");

            paramStrike.VarName = "strike";
            rov.Symbols.Add(paramStrike);

            ModelParameter paramRate = new ModelParameter(rate, "rfrate");

            paramRate.VarName = "rfrate";
            rov.Symbols.Add(paramRate);

            AFunction payoff = new AFunction(rov);

            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            VarianceGamma process = new VarianceGamma(s0, theta, sigma, nu, rate, dy);

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);

            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;

            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "payoff(v1)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity;
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;

            double samplePrice = price.value;
            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            Console.WriteLine("Theoretical Price = " + theoreticalPrice);
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.Less(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#29
0
        public void Test()
        {
            Engine.MultiThread = true;

            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim = 10000;
            int n_steps = 512;
            double a = 0.2;
            double DR = 0.02;
            double r0 = 0.015;
            double a1 = 1.0;
            double sigma1 = 0.01;
            double a2 = 0.1;
            double sigma2 = 0.0165;
            double correlation = 0.6;
            double maturityOpt = 5.0;
            double strike = 0.927;
            double tau = 2.0;

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");
            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");
            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pa = new ModelParameter(a, "a");
            Pa.VarName = "a";
            rov.Symbols.Add(Pa);

            ModelParameter PDR = new ModelParameter(DR, "PDR");
            PDR.VarName = "DR";
            rov.Symbols.Add(PDR);

            ModelParameter Pr0 = new ModelParameter(r0, "r0");
            Pr0.VarName = "r0";
            rov.Symbols.Add(Pr0);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");
            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            AFunction zerorate = new AFunction(rov);
            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)("(1-exp(-a*x1))*DR + r0");
            rov.Symbols.Add(zerorate);
            HW2ProcessType pt = new HW2ProcessType();

            // Set the short rate process.
            pt = HW2ProcessType.ShortRate;
            StocasticProcessHW2 process1 = new StocasticProcessHW2(rov, pt);

            process1.zero_rate_curve = "@zr";
            process1._a = (ModelParameter)a1;
            process1._b = (ModelParameter)sigma1;
            rov.Processes.AddProcess(process1);

            // Set the mean reversion process.
            pt = HW2ProcessType.Unobservable;
            StocasticProcessHW2 process2 = new StocasticProcessHW2(rov, pt);

            process2._a = (ModelParameter)a2;
            process2._b = (ModelParameter)sigma2;
            rov.Processes.AddProcess(process2);

            // Set the correlation.
            rov.Processes.r[0, 1] = (RightValue)correlation;

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@v1";

            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "max(bond(TT;TT+tau;@v1)-strike;0)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturityOpt;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;
            double sampleMean = price.value;
            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);
            double theoreticalPrice = HW2BondCall(zerorate, maturityOpt, maturityOpt + tau, strike,
                                                  a1, sigma1, a2, sigma2, correlation);

            Console.WriteLine("\nTheoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + sampleMean.ToString());
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());

            bool result;
            double fact = 4.0;
            result = (Math.Abs(sampleMean - theoreticalPrice) < fact * sampleDevSt);

            Assert.IsTrue(result);
        }
        /// <summary>
        /// Initializes the object based on the serialized data.
        /// </summary>
        /// <param name="info">The SerializationInfo that holds the serialized object data.</param>
        /// <param name="context">The StreamingContext that contains contextual
        /// information about the source.</param>
        public ModelParameterDateSequence(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            // Set the default for GenerateSequenceFromStartDate and FollowFrequency
            GenerateSequenceFromStartDate = true;
            FollowFrequency = true;

            int serialializedVersion;

            try
            {
                serialializedVersion = info.GetInt32("_VersionDateSequence");
            }
            catch
            {
                serialializedVersion = 0;
            }

            if (serialializedVersion < 2)
            {
                #region No expressions
                try
                {
                    this.StartDate = new DateTime(info.GetInt64("_StartDate"));
                    this.EndDate   = new DateTime(info.GetInt64("_EndDate"));
                }
                catch (Exception)
                {
                    // In case the calibration time was serialized in a different way.
                    this.StartDate = info.GetDateTime("_StartDate");
                    this.EndDate   = info.GetDateTime("_EndDate");
                }

                int   frequency  = info.GetInt32("_Frequency");
                Array enumValues = Enum.GetValues(typeof(DateFrequency));
                foreach (DateFrequency value in enumValues)
                {
                    if ((int)value == frequency)
                    {
                        Frequency = value;
                        break;
                    }
                }

                if (serialializedVersion >= 1)
                {
                    // Introduction of ExcludeStartDate
                    bool exclude = info.GetBoolean("_ExcludeStartDate");
                    SkipPeriods = exclude ? new ModelParameter(1) : new ModelParameter((double)0);
                }
                else
                {
                    SkipPeriods = new ModelParameter((double)0);
                }

                #endregion // No expressions
            }
            else
            {
                if (serialializedVersion < 4)
                {
                    string   tmpS = info.GetString("_StartDateExpression");
                    DateTime tmpD;
                    if (DateTime.TryParseExact(tmpS, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out tmpD))
                    {
                        StartDate = tmpD;
                    }
                    else
                    {
                        StartDateExpression = new ModelParameter(tmpS);
                    }

                    tmpS = info.GetString("_EndDateExpression");
                    if (DateTime.TryParseExact(tmpS, "yyyy-MM-dd", CultureInfo.CurrentCulture, DateTimeStyles.None, out tmpD))
                    {
                        EndDate = tmpD;
                    }
                    else
                    {
                        EndDateExpression = new ModelParameter(tmpS);
                    }
                }
                else
                {
                    StartDateExpression = (ModelParameter)info.GetValue("_StartDateExpression", typeof(ModelParameter));
                    EndDateExpression   = (ModelParameter)info.GetValue("_EndDateExpression", typeof(ModelParameter));
                    SetupExportedIDs();
                }

                FrequencyExpression = info.GetString("_FrequencyExpression");

                if (serialializedVersion >= 3)
                {
                    // FollowFrequency and GenerateSequenceFromStartDate in version 3
                    FollowFrequency = info.GetBoolean("_FollowFrequency");
                    GenerateSequenceFromStartDate = info.GetBoolean("_GenerateSequenceFromStartDate");
                }

                // Skip Periods introduced in version 5
                if (serialializedVersion < 5)
                {
                    bool exclude = info.GetBoolean("_ExcludeStartDate");
                    SkipPeriods = exclude ? new ModelParameter(1) : new ModelParameter((double)0);
                }
                else
                {
                    SkipPeriods = (ModelParameter)info.GetValue("_SkipPeriods", typeof(ModelParameter));
                }

                if (serialializedVersion < 6)
                {
                    VectorReferenceExpr = string.Empty;
                }
                else
                {
                    VectorReferenceExpr = info.GetString("_VectorReferenceExpr");
                    SkipPeriodsArray    = ObjectSerialization.GetValue <ModelParameter>(info, "_SkipPeriodsArray", new ModelParameter(0.0));
                }
            }
        }
        public void Test()
        {
            Engine.MultiThread = true;

            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);

            AFunction zerorate = new AFunction(rov);

            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)0.05;

            rov.Symbols.Add(zerorate);

            int    n_sim       = 4000;
            double maturityOpt = 6.5;

            // Simulation steps for a year. With stepPerYear = 150 the test will be passed.
            // But notice that the price calculated through Monte Carlo is unstable when
            // changing this value, even till 1000 steps per year.
            int    stepsPerYear = 150;
            int    n_steps      = stepsPerYear * ((int)maturityOpt);
            double strike       = 0.01;
            double tau          = 0.5;

            SquaredGaussianModel process = new SquaredGaussianModel();

            process.a1     = (ModelParameter)0.1;
            process.sigma1 = (ModelParameter)0.01;
            process.zr     = (ModelParameter)"@zr";

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);

            rov.Processes.AddProcess(s);

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");

            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");

            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");

            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@V1";

            // Set the payoff.
            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "tau*max(rate(TT;tau;@v1) - strike; 0)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)(maturityOpt + tau);
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price   = rov.m_ResultList[0] as ResultItem;
            double     mcPrice = price.value;
            double     mcDevST = price.stdDev / Math.Sqrt((double)n_sim);

            Caplet cplt = new Caplet();
            Vector Mat, fwd, Rk;
            Vector capMatV;
            double delta_k;
            double capMat;

            delta_k = 0.5;
            capMat  = maturityOpt + tau;
            int nmat = 2 * ((int)capMat) + 1;

            Mat    = new Vector(nmat);
            fwd    = new Vector(nmat);
            Mat[0] = 0;
            fwd[0] = zerorate.Evaluate(0);
            for (int k = 1; k < nmat; k++)
            {
                Mat[k] = tau * ((double)k);
                fwd[k] = zerorate.Evaluate(Mat[k]) * Mat[k] - zerorate.Evaluate(Mat[k - 1]) * Mat[k - 1];
            }

            fwd        = fwd / tau;
            Rk         = new Vector(1);
            Rk[0]      = strike;
            capMatV    = new Vector(2);
            capMatV[0] = maturityOpt;
            capMatV[1] = maturityOpt + tau;
            Matrix caplet = cplt.PGSMCaplets(process, Mat, fwd, Rk, delta_k, capMatV);

            double theoreticalPrice = caplet[1, 0] - caplet[0, 0];

            Console.WriteLine("\nTheoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + mcPrice);
            Console.WriteLine("Standard Deviation = " + mcDevST);

            double tol = 4.0 * mcDevST;

            Assert.Less(Math.Abs(theoreticalPrice - mcPrice), tol);
        }
示例#32
0
        /// <summary>
        /// Creates Activity
        /// </summary>
        /// <returns>True if successful</returns>
        public static async Task <dynamic> CreateActivity()
        {
            Bearer bearer   = (await Get2LeggedTokenAsync(new Scope[] { Scope.CodeAll })).ToObject <Bearer>();
            string nickName = ConsumerKey;

            AppBundlesApi appBundlesApi = new AppBundlesApi();

            appBundlesApi.Configuration.AccessToken = bearer.AccessToken;
            PageString appBundles = await appBundlesApi.AppBundlesGetItemsAsync();

            string appBundleID = string.Format("{0}.{1}+{2}", nickName, APPNAME, ALIAS);

            if (!appBundles.Data.Contains(appBundleID))
            {
                if (!System.IO.File.Exists(LocalAppPackageZip))
                {
                    return(new Output(Output.StatusEnum.Error, "Bundle not found at " + LocalAppPackageZip));
                }
                // create new bundle
                AppBundle appBundleSpec = new AppBundle(APPNAME, null, EngineName, null, null, APPNAME, null, APPNAME);
                AppBundle newApp        = await appBundlesApi.AppBundlesCreateItemAsync(appBundleSpec);

                if (newApp == null)
                {
                    return(new Output(Output.StatusEnum.Error, "Cannot create new app"));
                }
                // create alias
                Alias aliasSpec = new Alias(1, null, ALIAS);
                Alias newAlias  = await appBundlesApi.AppBundlesCreateAliasAsync(APPNAME, aliasSpec);

                // upload the zip bundle
                RestClient  uploadClient = new RestClient(newApp.UploadParameters.EndpointURL);
                RestRequest request      = new RestRequest(string.Empty, Method.POST);
                request.AlwaysMultipartFormData = true;
                foreach (KeyValuePair <string, object> x in newApp.UploadParameters.FormData)
                {
                    request.AddParameter(x.Key, x.Value);
                }
                request.AddFile("file", LocalAppPackageZip);
                request.AddHeader("Cache-Control", "no-cache");
                var res = await uploadClient.ExecuteTaskAsync(request);
            }
            ActivitiesApi activitiesApi = new ActivitiesApi();

            activitiesApi.Configuration.AccessToken = bearer.AccessToken;
            PageString activities = await activitiesApi.ActivitiesGetItemsAsync();

            string activityID = string.Format("{0}.{1}+{2}", nickName, ACTIVITY_NAME, ALIAS);

            if (!activities.Data.Contains(activityID))
            {
                // create activity
                string         commandLine  = string.Format(@"$(engine.path)\\inventorcoreconsole.exe /i $(args[InputIPT].path) /al $(appbundles[{0}].path) $(args[InputParams].path)", APPNAME);
                ModelParameter iptFile      = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "Input Ipt File", true, inputFileName);
                ModelParameter result       = new ModelParameter(false, false, ModelParameter.VerbEnum.Put, "Resulting Ipt File", true, outputFileName);
                ModelParameter inputParams  = new ModelParameter(false, false, ModelParameter.VerbEnum.Get, "Input params", false, "params.json");
                Activity       activitySpec = new Activity(
                    new List <string> {
                    commandLine
                },
                    new Dictionary <string, ModelParameter>()
                {
                    { "InputIPT", iptFile },
                    { "InputParams", inputParams },
                    { "ResultIPT", result },
                },
                    EngineName,
                    new List <string>()
                {
                    string.Format("{0}.{1}+{2}", nickName, APPNAME, ALIAS)
                },
                    null,
                    ACTIVITY_NAME,
                    null,
                    ACTIVITY_NAME
                    );
                Activity newActivity = await activitiesApi.ActivitiesCreateItemAsync(activitySpec);

                Alias aliasSpec = new Alias(1, null, ALIAS);
                Alias newAlias  = await activitiesApi.ActivitiesCreateAliasAsync(ACTIVITY_NAME, aliasSpec);
            }
            return(new Output(Output.StatusEnum.Sucess, "Activity created"));
        }
示例#33
0
 public Bacteria(ModelParameter parameter) : base(parameter)
 {
 }
示例#34
0
        public void Test()
        {
            double nu = 0.6;
            double theta = -0.2;
            double sigma = 0.2;
            double rate = 0.02;
            double dy = 0.01;
            double s0 = 1;
            double maturity = 2.0;
            double strike = 1.2;
            Vector mat = new Vector(1) + maturity;
            Vector k = new Vector(1) + strike;

            // Calculates the theoretical value of the call.
            double theoreticalPrice = VarianceGammaOptionsCalibration.VGCall(theta, sigma, nu,
                                                                             maturity, strike,
                                                                             dy, s0, rate);

            Engine.MultiThread = true;
            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim = 50000;
            int n_steps = 512;

            ModelParameter paramStrike = new ModelParameter(strike, "strike");
            paramStrike.VarName = "strike";
            rov.Symbols.Add(paramStrike);

            ModelParameter paramRate = new ModelParameter(rate, "rfrate");
            paramRate.VarName = "rfrate";
            rov.Symbols.Add(paramRate);

            AFunction payoff = new AFunction(rov);
            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            VarianceGamma process = new VarianceGamma(s0, theta, sigma, nu, rate, dy);

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;

            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "payoff(v1)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;

            double samplePrice = price.value;
            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            Console.WriteLine("Theoretical Price = " + theoreticalPrice);
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;
            Assert.Less(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#35
0
        public void TestSimulation()
        {
            Engine.MultiThread = true;

            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;
            int n_sim = 10000;
            int n_steps = 512;
            double strike = 90.0;
            double maturity = 2.0;
            double rate = 0.1;
            double dy = 0.05;
            double volatility = 0.2;
            double S0 = 100;

            ModelParameter Pstrike = new ModelParameter(strike, string.Empty, "strike");
            rov.Symbols.Add(Pstrike);

            ModelParameter PS0 = new ModelParameter(S0, string.Empty, "S0");
            rov.Symbols.Add(PS0);

            AFunction payoff = new AFunction(rov);
            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            AFunction rfunc = new AFunction(rov);
            rfunc.VarName = "r";
            rfunc.m_IndependentVariables = 1;
            rfunc.m_Value = (RightValue)rate;
            rov.Symbols.Add(rfunc);

            AFunction qfunc = new AFunction(rov);
            qfunc.VarName = "q";
            qfunc.m_IndependentVariables = 1;
            qfunc.m_Value = (RightValue)dy;
            rov.Symbols.Add(qfunc);

            AFunction volfunc = new AFunction(rov);
            volfunc.VarName = "localvol";
            volfunc.m_IndependentVariables = 2;
            volfunc.m_Value = (RightValue)volatility;
            rov.Symbols.Add(volfunc);

            DupireProcess process = new DupireProcess();
            process.s0 = (ModelParameter)"S0";
            process.r = (ModelParameter)"@r";
            process.q = (ModelParameter)"@q";
            process.localVol = (ModelParameter)"@localvol";

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;
            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "payoff(v1)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);
            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);
            ResultItem price = rov.m_ResultList[0] as ResultItem;
            double samplePrice = price.value;
            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            // Calculation of the theoretical value of the call.
            double theoreticalPrice = BlackScholes.Call(rate, S0, strike, volatility, maturity, dy);
            Console.WriteLine("Theoretical Price  = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price  = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;
            Assert.LessOrEqual(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
        public void Test()
        {
            Engine.MultiThread = true;

            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);

            AFunction zerorate = new AFunction(rov);
            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)0.05;

            rov.Symbols.Add(zerorate);

            int n_sim = 10000;
            double maturityOpt = 6.5;

            // Simulation steps for a year. With stepPerYear = 150 the test will be passed.
            // But notice that the price calculated through Monte Carlo is unstable when
            // changing this value, even till 1000 steps per year.
            int stepsPerYear = 500;
            int n_steps = stepsPerYear * ((int)maturityOpt);
            double strike = 100.0;
            double tau = 0.5;

            SquaredGaussianModel process = new SquaredGaussianModel();
            process.a1 = (ModelParameter)0.1;
            process.sigma1 = (ModelParameter)0.01;
            process.zr = (ModelParameter)"@zr";

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");
            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");
            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");
            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@V1";

            // Set the payoff.
            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "max(strike - Bond(TT;TT+tau;@v1); 0)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturityOpt;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;
            double mcPrice = price.value;
            double mcDevST = price.stdDev / Math.Sqrt(2.0 * ((double)n_sim));

            Caplet cplt = new Caplet();
            Vector Mat;
            Vector fwd;
            Vector Rk;
            Vector capMatV;
            double deltaK;
            double capMat;
            deltaK = 0.5;
            capMat = maturityOpt + tau;
            int nmat = 2 * ((int)capMat) + 1;
            Mat = new Vector(nmat);
            fwd = new Vector(nmat);
            Mat[0] = 0;
            fwd[0] = zerorate.Evaluate(0);
            for (int k = 1; k < nmat; k++)
            {
                Mat[k] = tau * ((double)k);
                fwd[k] = zerorate.Evaluate(Mat[k]) * Mat[k] - zerorate.Evaluate(Mat[k - 1]) * Mat[k - 1];
            }

            fwd = fwd / tau;
            Rk = new Vector(1);
            Rk[0] = (1 / strike - 1.0) / tau;
            capMatV = new Vector(2);
            capMatV[0] = maturityOpt;
            capMatV[1] = maturityOpt + tau;
            Matrix caplet = cplt.PGSMCaplets(process, Mat, fwd, Rk, deltaK, capMatV);
            Console.WriteLine("rows = " + caplet.R);
            Console.WriteLine("columns = " + caplet.C);

            double theoreticalPrice = caplet[1, 0] - caplet[0, 0];

            Console.WriteLine("\nTheoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + mcPrice);
            Console.WriteLine("Standard Deviation = " + mcDevST);

            double tol = 4.0 * mcDevST;
            Assert.Less(Math.Abs(theoreticalPrice - mcPrice), tol);
        }
示例#37
0
        public void Test()
        {
            Engine.MultiThread = true;
            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim = 50000;
            int n_steps = 512;
            double strike = 100.0;
            double tau = 5.0;
            double rate = 0.1;
            double dy = 0.07;

            ModelParameter pStrike = new ModelParameter(strike, "strike");
            pStrike.VarName = "strike";
            rov.Symbols.Add(pStrike);

            ModelParameter pRate = new ModelParameter(rate, "rfrate");
            pRate.VarName = "rfrate";
            rov.Symbols.Add(pRate);

            AFunction payoff = new AFunction(rov);
            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            HestonProcess process = new HestonProcess();
            process.r = (ModelParameter)rate;
            process.q = (ModelParameter)dy;
            process.k = (ModelParameter)2.5;
            process.theta = (ModelParameter)0.4;
            process.sigma = (ModelParameter)0.2;
            process.S0 = (ModelParameter)100.0;
            process.V0 = (ModelParameter)0.3;

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;

            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "payoff(v1a)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)tau;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;

            double samplePrice = price.value;
            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            // Calculates the theoretical value of the call.
            Vector param = new Vector(5);
            param[0] = process.k.V();
            param[1] = process.theta.V();
            param[2] = process.sigma.V();
            param[3] = 0.0;
            param[4] = process.V0.V();
            HestonCall hestonCall = new HestonCall();
            double thPrice = hestonCall.HestonCallPrice(param, process.S0.V(),
                                                        tau, strike, rate, dy);
            Console.WriteLine("Theoretical Price = " + thPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.Less(Math.Abs(thPrice - samplePrice), tol);
        }
示例#38
0
        public void Test()
        {
            Engine.MultiThread = true;

            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int    n_sim       = 10000;
            int    n_steps     = 512;
            double a           = 0.2;
            double DR          = 0.02;
            double r0          = 0.015;
            double a1          = 1.0;
            double sigma1      = 0.01;
            double a2          = 0.1;
            double sigma2      = 0.0165;
            double correlation = 0.6;
            double maturityOpt = 5.0;
            double strike      = 0.927;
            double tau         = 2.0;

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");

            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");

            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pa = new ModelParameter(a, "a");

            Pa.VarName = "a";
            rov.Symbols.Add(Pa);

            ModelParameter PDR = new ModelParameter(DR, "PDR");

            PDR.VarName = "DR";
            rov.Symbols.Add(PDR);

            ModelParameter Pr0 = new ModelParameter(r0, "r0");

            Pr0.VarName = "r0";
            rov.Symbols.Add(Pr0);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");

            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            AFunction zerorate = new AFunction(rov);

            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)("(1-exp(-a*x1))*DR + r0");
            rov.Symbols.Add(zerorate);
            HW2ProcessType pt = new HW2ProcessType();

            // Set the short rate process.
            pt = HW2ProcessType.ShortRate;
            StocasticProcessHW2 process1 = new StocasticProcessHW2(rov, pt);

            process1.zero_rate_curve = "@zr";
            process1._a = (ModelParameter)a1;
            process1._b = (ModelParameter)sigma1;
            rov.Processes.AddProcess(process1);

            // Set the mean reversion process.
            pt = HW2ProcessType.Unobservable;
            StocasticProcessHW2 process2 = new StocasticProcessHW2(rov, pt);

            process2._a = (ModelParameter)a2;
            process2._b = (ModelParameter)sigma2;
            rov.Processes.AddProcess(process2);

            // Set the correlation.
            rov.Processes.r[0, 1] = (RightValue)correlation;

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@v1";

            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "max(bond(TT;TT+tau;@v1)-strike;0)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturityOpt;
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price            = rov.m_ResultList[0] as ResultItem;
            double     sampleMean       = price.value;
            double     sampleDevSt      = price.stdDev / Math.Sqrt((double)n_sim);
            double     theoreticalPrice = HW2BondCall(zerorate, maturityOpt, maturityOpt + tau, strike,
                                                      a1, sigma1, a2, sigma2, correlation);

            Console.WriteLine("\nTheoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + sampleMean.ToString());
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());

            bool   result;
            double fact = 4.0;

            result = (Math.Abs(sampleMean - theoreticalPrice) < fact * sampleDevSt);

            Assert.IsTrue(result);
        }
        void ApplyParametersFilter(
            Dictionary <Parameter, ListViewItem> paramDict,
            ListView listView,
            ParamFilterEnum filter)
        {
            foreach (Parameter parameter in paramDict.Keys)
            {
                switch (filter)
                {
                case ParamFilterEnum.kAll:
                    break;

                case ParamFilterEnum.kKey:
                    if (!parameter.IsKey)
                    {
                        if (paramDict[parameter].ListView != null)
                        {
                            paramDict[parameter].Remove();
                        }
                        continue;
                    }
                    break;

                case ParamFilterEnum.kNonKey:
                    if (parameter.IsKey)
                    {
                        if (paramDict[parameter].ListView != null)
                        {
                            paramDict[parameter].Remove();
                        }
                        continue;
                    }
                    break;

                case ParamFilterEnum.kRenamed:
                    if (parameter.Type != ObjectTypeEnum.kModelParameterObject)
                    {
                        if (paramDict[parameter].ListView != null)
                        {
                            paramDict[parameter].Remove();
                        }
                        continue;
                    }

                    ModelParameter mparameter = parameter as ModelParameter;

                    if (!mparameter.Renamed)
                    {
                        if (paramDict[parameter].ListView != null)
                        {
                            paramDict[parameter].Remove();
                        }
                        continue;
                    }
                    break;

                default:
                    break;
                }

                if (paramDict[parameter].ListView == null)
                {
                    ListViewItem item = paramDict[parameter];
                    listView.Items.Add(item);
                }
            }
        }
示例#40
0
        public void Test()
        {
            // Tests HW1 dynamics comparing the price of a call option on a bond
            // calculated through simulation and the theoretical one.
            Engine.MultiThread = true;
            Document doc = new Document();
            ProjectROV rov = new ProjectROV(doc);
            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;

            int n_sim = 20000;
            int n_steps = 1024;
            double a = 0.2;
            double DR = 0.02;
            double r0 = 0.015;
            double a1 = 0.02;
            double sigma1 = 0.01;
            double maturityOpt = 5.0;
            double strike = 0.98192;
            double tau = 1.0;

            ModelParameter PT = new ModelParameter(maturityOpt, "TT");
            PT.VarName = "TT";
            rov.Symbols.Add(PT);

            ModelParameter Ptau = new ModelParameter(tau, "tau");
            Ptau.VarName = "tau";
            rov.Symbols.Add(Ptau);

            ModelParameter Pa = new ModelParameter(a, "a");
            Pa.VarName = "a";
            rov.Symbols.Add(Pa);

            ModelParameter PDR = new ModelParameter(DR, "PDR");
            PDR.VarName = "DR";
            rov.Symbols.Add(PDR);

            ModelParameter Pr0 = new ModelParameter(r0, "r0");
            Pr0.VarName = "r0";
            rov.Symbols.Add(Pr0);

            ModelParameter Pstrike = new ModelParameter(strike, "strike");
            Pstrike.VarName = "strike";
            rov.Symbols.Add(Pstrike);

            AFunction zerorate = new AFunction(rov);
            zerorate.VarName = "zr";
            zerorate.m_IndependentVariables = 1;
            zerorate.m_Value = (RightValue)("(1-exp(-a*x1))*DR + r0");
            rov.Symbols.Add(zerorate);

            HW1 process = new HW1(a1, sigma1, "@zr");

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);
            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;
            rfi.ActualizationType = EActualizationType.Stochastic;
            rfi.m_deterministicRF = (ModelParameter)"@V1";

            OptionTree op = new OptionTree(rov);
            op.PayoffInfo.PayoffExpression = "Max(bond(TT;TT+tau;@v1)-strike;0)";

            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturityOpt;
            op.PayoffInfo.European = true;
            rov.Map.Root = op;

            rov.NMethods.Technology = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber = n_sim;
            rov.NMethods.SimulationSteps = n_steps;

            ROVSolver solver = new ROVSolver();
            solver.BindToProject(rov);
            solver.DoValuation(-1);

            if (rov.HasErrors)
            {
                Console.WriteLine(rov.m_RuntimeErrorList[0]);
            }

            Assert.IsFalse(rov.HasErrors);

            ResultItem price = rov.m_ResultList[0] as ResultItem;
            double samplePrice = price.value;

            double sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            // Calculation of the theoretical value of the call.
            CapHW1 cap = new CapHW1(zerorate);

            double d1 = cap.D1(a1, sigma1, maturityOpt, maturityOpt + tau, strike);
            double d2 = cap.D2(a1, sigma1, maturityOpt, maturityOpt + tau, strike);
            double theoreticalPrice = ZCB(zerorate, maturityOpt + tau) * SpecialFunctions.NormCdf(d1) - strike * ZCB(zerorate, maturityOpt) * SpecialFunctions.NormCdf(d2);

            Console.WriteLine("Theoretical Price = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            Assert.Less(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#41
0
        public void TestCalibration()
        {
            InterestRateMarketData IData = InterestRateMarketData.FromFile("../../TestData/IRMD-sample.xml");
            CallPriceMarketData    HData = CallPriceMarketData.FromFile("../../TestData/CallData-sample.xml");
            //InterestRateMarketData IData = InterestRateMarketData.FromFile("../../../EquityModels.Tests/TestData/IRMD-EU-30102012-close.xml");
            //CallPriceMarketData HData = CallPriceMarketData.FromFile("../../../EquityModels.Tests/TestData/30102012-SX5E_Index-HestonData.xml");
            //CallPriceMarketData HData = ObjectSerialization.ReadFromXMLFile("../../../EquityModels.Tests/TestData/FTSE.xml") as CallPriceMarketData;


            List <object> l = new List <object>();

            l.Add(IData.DiscountingCurve);
            l.Add(HData);

            DupireEstimator           DE       = new DupireEstimator();
            DupireCalibrationSettings settings = new DupireCalibrationSettings();

            settings.LocalVolatilityCalculation = LocalVolatilityCalculation.Method1;


            //settings.LocalVolatilityCalculation = LocalVolatilityCalculation.QuantLib;
            EstimationResult res = DE.Estimate(l, settings);
            //int nmat = HData.Maturity.Length;
            //int nstrike = HData.Strike.Length;

            int i = 5; // Maturity.
            int j = 4; // Strike.

            Engine.MultiThread = true;

            Document   doc = new Document();
            ProjectROV rov = new ProjectROV(doc);

            doc.Part.Add(rov);
            doc.DefaultProject.NMethods.m_UseAntiteticPaths = true;
            int    n_sim   = 10000;
            int    n_steps = 500;
            double strike  = HData.Strike[j];
            //double volatility = HData.Volatility[i, j];

            /*
             * PFunction2D.PFunction2D impvolfunc = new PFunction2D.PFunction2D(rov);
             * impvolfunc = res.Objects[3] as PFunction2D.PFunction2D;
             * impvolfunc.VarName = "impvol";
             * rov.Symbols.Add(impvolfunc);
             * double volatility = impvolfunc.Evaluate(HData.Maturity[i], HData.Strike[j]);
             */
            double volatility = 0.2;
            double maturity   = HData.Maturity[i];

            ModelParameter Pstrike = new ModelParameter(strike, string.Empty, "strike");

            rov.Symbols.Add(Pstrike);
            AFunction payoff = new AFunction(rov);

            payoff.VarName = "payoff";
            payoff.m_IndependentVariables = 1;
            payoff.m_Value = (RightValue)("max(x1 - strike ; 0)");
            rov.Symbols.Add(payoff);

            bool           found;
            double         S0  = PopulateHelper.GetValue("S0", res.Names, res.Values, out found);
            ModelParameter PS0 = new ModelParameter(S0, string.Empty, "S0");

            rov.Symbols.Add(PS0);
            PFunction rfunc = new PFunction(rov);

            rfunc         = res.Objects[0] as PFunction;
            rfunc.VarName = "r";
            rov.Symbols.Add(rfunc);

            PFunction qfunc = new PFunction(rov);

            qfunc         = res.Objects[1] as PFunction;
            qfunc.VarName = "q";
            rov.Symbols.Add(qfunc);

            PFunction2D.PFunction2D volfunc = new PFunction2D.PFunction2D(rov);
            volfunc         = res.Objects[2] as PFunction2D.PFunction2D;
            volfunc.VarName = "localvol";
            rov.Symbols.Add(volfunc);
            DupireProcess process = new DupireProcess();

            process.s0       = (ModelParameter)"S0";
            process.r        = (ModelParameter)"@r";
            process.q        = (ModelParameter)"@q";
            process.localVol = (ModelParameter)"@localvol";
            double rate = rfunc.Evaluate(maturity);
            double dy   = qfunc.Evaluate(maturity);

            StochasticProcessExtendible s = new StochasticProcessExtendible(rov, process);

            rov.Processes.AddProcess(s);

            // Set the discounting.
            RiskFreeInfo rfi = rov.GetDiscountingModel() as RiskFreeInfo;

            rfi.ActualizationType = EActualizationType.RiskFree;
            rfi.m_deterministicRF = rate;
            OptionTree op = new OptionTree(rov);

            op.PayoffInfo.PayoffExpression          = "payoff(v1)";
            op.PayoffInfo.Timing.EndingTime.m_Value = (RightValue)maturity;
            op.PayoffInfo.European = true;
            rov.Map.Root           = op;

            rov.NMethods.Technology      = ETechType.T_SIMULATION;
            rov.NMethods.PathsNumber     = n_sim;
            rov.NMethods.SimulationSteps = n_steps;
            ROVSolver solver = new ROVSolver();

            solver.BindToProject(rov);
            solver.DoValuation(-1);
            if (rov.HasErrors)
            {
                rov.DisplayErrors();
            }

            Assert.IsFalse(rov.HasErrors);
            ResultItem price       = rov.m_ResultList[0] as ResultItem;
            double     samplePrice = price.value;
            double     sampleDevSt = price.stdDev / Math.Sqrt((double)n_sim);

            Console.WriteLine("Surf = " + volfunc.Expr);

            // Calculation of the theoretical value of the call.
            double theoreticalPrice = BlackScholes.Call(rate, S0, strike, volatility, maturity, dy);

            Console.WriteLine("Theoretical Price  = " + theoreticalPrice.ToString());
            Console.WriteLine("Monte Carlo Price  = " + samplePrice);
            Console.WriteLine("Standard Deviation = " + sampleDevSt.ToString());
            double tol = 4.0 * sampleDevSt;

            doc.WriteToXMLFile("Dupire.fair");
            Assert.LessOrEqual(Math.Abs(theoreticalPrice - samplePrice), tol);
        }
示例#42
0
		protected ModelValue			DetermineParameterValue(ModelParameter parameter)
		{
			ModelValues values = new ModelValues();
			values.Add(parameter.Values);

			//Parameter values, can be specified in numerous ways:
			//	1.  Value list - simply choose one of them
			//	2.  Expression - generate value that meets the criteria (ie: <, >, !=, etc)
			//	3.  Variable - simply obtain the value by calling a method/field

			//#3. Variable - simply obtain the value by calling a method/field
			if(parameter.Variable != null)
			{
                object current = parameter.Variable.CachedValue;
				if(current is IEnumerable && !typeof(IEnumerable).IsAssignableFrom(parameter.Type))
				{
 					foreach(object v in (IEnumerable)current)
						values.Add(new ModelValue(v));
				}
				else
				{
					values.Add(new ModelValue(current));
				}
			}

			//First ensure we have a set of values/requirements to choose from
			if(values.Count <= 0)
				throw new ModelException(parameter, "No values specified to choose from");

			//Note: Since we allow the operator on the individual values, this is a little more complex.
			//Note: We allow multiple operators, not just one, (ie: x > 5, < 10, and != 7). 
			//This gives you great power and flexibility in expressions, but means we have to work a 
			//little hard in determing a value that meets the requirements

			//#1.  Value list - simply choose one of them
			//Note: Bitmask is already exploded into combinations
			ModelValues equalvalues = values.FindOperator(ModelValueOperator.Equal);

			//#2.  Expression - generate value that meets the criteria (ie: <, >, !=, etc)
			//Note: Since we allow the operator on the individual values, this is a little more complex.
			//Note: We allow multiple operators, not just one, (ie: x > 5, < 10, and != 7). 
			//This gives you great power and flexibility in expressions, but means we have to work a 
			//little hard in determing a value that meets the requirements.
			int min = Int32.MinValue;
			int max = Int32.MaxValue;

			//Adjust our parameter, simplier to loop over all of them
			foreach(ModelValue value in values.FindOperator(ModelValueOperator.Equal, false).FindOperator(ModelValueOperator.NotEqual, false))
			{
				//To keep this simple, we just support integers (for now).
				if(!(value.Value is int || value.Value is Nullable<int>))
					throw new ModelException(parameter, "Generated value range must be specified in terms of integers, not '" + value.Type + "'");

				//Simplify our life
				int v = (int)value.Value;
				
				//Adjust Max (if there is one)
				switch(value.Operator)
				{
					case ModelValueOperator.LessThanOrEqual:
						if(v < max)
							max = v;
						break;
				
					case ModelValueOperator.GreaterThanOrEqual:
						if(v > min)
							min = v;
						break;

					case ModelValueOperator.LessThan:
						if(v-1 < max && v > Int32.MinValue/*prevent underflow*/)
							max = v-1;
						break;
				
					case ModelValueOperator.GreaterThan:
						if(v+1 > min && v < Int32.MaxValue/*prevent overflow*/)
							min = v+1;
						break;
				};
			}

			//Choose a new value, within the specified range
			//Note: We retry in case it equals one of the existing invalid values (ie: !=)
			while(true)
			{
				ModelValue choice = null;
				if(equalvalues.Count > 0)
				{
					//Simple: Choose one of the specified values
					choice = new ModelValue(equalvalues.Choose(this).Value);
				}
				else
				{
					//Otherwise: Choose a value within in the range
					//Note: Random.Next = min <= x < max (so we have to add one)
					int index = _options.Random.Next(min, max < Int32.MaxValue ? max + 1 : max);	//Prevent overflow
                    choice = new ModelValue(index);
				}

				//As soon as we find a value, within the range, (and not in the invalid list), were done
				bool valid = true;
				foreach(ModelValue invalid in values.FindOperator(ModelValueOperator.NotEqual))
				{
					if(invalid.Evaluate(choice.Value, ModelValueOperator.Equal))
						valid = false;
				}

				if(valid)
					return choice;
			}
		}