コード例 #1
0
        /// <summary>
        /// Get the product details for the given product code - Call to WS016R and filter the products
        /// </summary>
        /// <param name="productCode">The given product code</param>
        /// <returns>DataSet of product details</returns>
        private DataTable retrieveProductDetails(string productCode)
        {
            DataSet       dsProductList = new DataSet();
            DataTable     dtProduct     = new DataTable();
            DataView      dvProduct     = new DataView();
            TalentProduct talProduct    = new TalentProduct();
            DESettings    settings      = Environment.Settings.DESettings;
            ErrorObj      err           = new ErrorObj();
            ErrorModel    errModel      = new ErrorModel();
            string        filter;

            talProduct.Settings = settings;
            talProduct.De.PriceAndAreaSelection = Environment.Settings.DefaultValues.PriceAndAreaSelection;
            talProduct.De.Src         = GlobalConstants.SOURCE;
            talProduct.De.StadiumCode = Environment.Settings.DefaultValues.CorporateStadium;

            err      = talProduct.ProductList();
            errModel = Data.PopulateErrorObject(err, talProduct.ResultDataSet.Tables[GlobalConstants.STATUS_RESULTS_TABLE_NAME], settings);
            if (!errModel.HasError)
            {
                dsProductList       = talProduct.ResultDataSet;
                filter              = "ProductCode = '" + productCode + "'";
                dvProduct           = new DataView(dsProductList.Tables["ProductListResults"]);
                dvProduct.RowFilter = filter;
                dtProduct           = dvProduct.ToTable();
            }
            return(dtProduct);
        }
コード例 #2
0
ファイル: ActionFilters.cs プロジェクト: adv-hack/ETicketing
            public override void OnException(HttpActionExecutedContext context)
            {
                Dictionary <string, string> @params = new Dictionary <string, string>();
                DESettings          settings = default(DESettings);
                HttpResponseMessage objReponse = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                string sourceClass, sourceMethod, logCode, logFilter1, logFilter2, logFilter5, logContent;

                @params  = Utilities.GetParams(context.Request.GetRequestContext().Url.Request.GetQueryNameValuePairs());
                settings = Utilities.GetDESettings(@params);

                // log error into DB-tbl_logs
                sourceClass  = context.Exception.Source;
                sourceMethod = context.Exception.TargetSite.ReflectedType.Name + "." + context.Exception.TargetSite.Name;
                logCode      = TalentSystemDefaults.GlobalConstants.LOG_ERROR_CODE;
                logFilter1   = settings.BusinessUnit;
                logFilter2   = context.Request.RequestUri.ToString();
                logFilter5   = context.Exception.StackTrace;
                logContent   = context.Exception.Message;

                var objLogInserted = TalentSystemDefaults.Utilities.InsertErrorLog(settings, sourceClass, sourceMethod, logCode, logFilter1, logFilter2, "", "", logFilter5, logContent);

                objReponse.Content = new StringContent(context.Exception.Message);
                objReponse.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
                context.Response = objReponse;

                base.OnException(context);
            }
コード例 #3
0
ファイル: ActionFilters.cs プロジェクト: adv-hack/ETicketing
            public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
            {
                Dictionary <string, string> @params = new Dictionary <string, string>();
                DESettings          settings        = default(DESettings);
                bool                agentLoggedIn   = false;
                HttpResponseMessage response        = new HttpResponseMessage(HttpStatusCode.OK);

                @params  = Utilities.GetParams(actionContext.Request.GetRequestContext().Url.Request.GetQueryNameValuePairs());
                settings = Utilities.GetDESettings(@params);
                if (settings.BusinessUnit == string.Empty || settings.BusinessUnit == null)
                {
                    settings.BusinessUnit = settings.DefaultBusinessUnit;
                }
                agentLoggedIn = Utilities.CheckAgentLogin(settings);
                //uncomment to test the authorization
                //agentLoggedIn = False
                if (!agentLoggedIn)
                {
                    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
                else
                {
                    base.OnAuthorization(actionContext);
                    actionContext.RequestContext.RouteData.Values.Add("AgentName", settings.AgentName);
                    actionContext.RequestContext.RouteData.Values.Add("CompanyName", settings.Company);
                }
            }
コード例 #4
0
ファイル: Utilities.cs プロジェクト: adv-hack/ETicketing
        /// <summary>
        /// XML Comment
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="sessionID"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static DataTable RetrieveAgentDetailsFromSessionID(DESettings settings, string sessionID)
        {
            tbl_agent tblAgent        = new tbl_agent(ref settings);
            DataTable tblAgentDetails = new DataTable();

            tblAgentDetails = tblAgent.RetrieveAgentDetailsFromSessionID(sessionID);
            return(tblAgentDetails);
        }
コード例 #5
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="settings"></param>
 /// <remarks></remarks>
 public tbl_payment_type(ref DESettings settings)
     : base(settings)
 {
     if (settings.VariableKey1 != string.Empty)
     {
         paymentTypeCode = settings.VariableKey1;
     }
 }
コード例 #6
0
 /// <summary>
 /// Logs and sets error message
 /// </summary>
 /// <param name="returnCode"></param>
 /// <param name="settings"></param>
 /// <param name="model"></param>
 private void LogsErrorMessage(DESettings settings, ref ErrorModel model)
 {
     if (model.HasError && !string.IsNullOrEmpty(model.ReturnCode))
     {
         model.ErrorMessage = AddErrorMessageText(model.ReturnCode, settings);
         settings.Logging.ErrorObjectLog("BusinessObjects.Data.DataSettings.cs - PopulateErrorObject | - " + settings.ModuleName, model.ReturnCode, model.ErrorMessage + " " + model.TechnicalErrorMessage);
     }
 }
コード例 #7
0
 public DLDatabaseAudit(DESettings settings, Dictionary <string, string> filters = null)
     : base(settings, filters)
 {
     if (string.IsNullOrEmpty(settings.BusinessUnit))
     {
         settings.BusinessUnit = settings.DefaultBusinessUnit;
     }
 }
コード例 #8
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="settings"></param>
 /// <remarks></remarks>
 public tbl_activity_template_type(ref DESettings settings)
     : base(settings)
 {
     businessUnit = settings.BusinessUnit;
     if (settings.VariableKey1 != string.Empty)
     {
         Name = settings.VariableKey1;
     }
 }
コード例 #9
0
 public DatabaseUpdatesModel(DESettings settings)
 {
     // VBConversions Note: Non-static class variable initialization is below.  Class variables cannot be initially assigned non-static values in C#.
     BusinessUnits     = new List <SelectListItem>();
     ConnectionStrings = new List <SelectListItem>();
     this.settings     = settings;
     objAudit          = new tbl_config_detail_audit(ref settings);
     Initialise();
 }
コード例 #10
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="settings"></param>
 /// <remarks></remarks>
 public tbl_payment_type_bu(ref DESettings settings)
     : base(settings)
 {
     businessUnit = settings.BusinessUnit;
     if (settings.VariableKey1 != string.Empty)
     {
         paymentTypeCode = settings.VariableKey1;
     }
 }
コード例 #11
0
ファイル: DLModules.cs プロジェクト: adv-hack/ETicketing
 public DLModules(DESettings settings, Dictionary <string, string> filters = null)
     : base(settings, filters)
 {
     //Modules page need to retrieve business units, before that talent data acccess need to retrieve
     //connection details using destination database, and for that it uses default business unit
     if (string.IsNullOrEmpty(settings.BusinessUnit))
     {
         settings.BusinessUnit = settings.DefaultBusinessUnit;
     }
 }
コード例 #12
0
        /// <summary>
        /// Adds text to ErrorModel object
        /// </summary>
        /// <param name="returnCode"></param>
        /// <param name="settings"></param>
        /// <returns>Error text for model</returns>
        private string AddErrorMessageText(string returnCode, DESettings settings)
        {
            if (returnCode.Equals("TBL-DNError") || returnCode.Equals("TBL-ResultSetError"))
            {
                returnCode = "*ALL";
            }
            TalentErrorMessages errorMessage = new TalentErrorMessages("ENG", settings.BusinessUnit,
                                                                       settings.Partner, settings.FrontEndConnectionString);

            return(errorMessage.GetErrorMessage(returnCode).ERROR_MESSAGE);
        }
コード例 #13
0
ファイル: Settings.cs プロジェクト: adv-hack/ETicketing
        public DESettings GetBasicSettingsObject(bool withBusinessUnit = true)
        {
            DESettings settings = new DESettings();

            if (withBusinessUnit)
            {
                settings.BusinessUnit = BusinessUnit;
            }
            settings.FrontEndConnectionString = FrontEndConnectionString;
            settings.DestinationDatabase      = GlobalConstants.SQL2005DESTINATIONDATABASE;
            return(settings);
        }
コード例 #14
0
        /// <summary>
        ///  Get template override criterias
        /// </summary>
        /// <returns>A data set of results for all the template overrides</returns>
        private DataSet retriveOverrideCriterias()
        {
            DataSet dsResults = new DataSet();
            TalentTemplateOverride talTemplateOverride = new TalentTemplateOverride();
            DESettings             settings            = Environment.Settings.DESettings;
            ErrorObj err = new ErrorObj();

            talTemplateOverride.Settings          = settings;
            talTemplateOverride.DeTemplate.Source = GlobalConstants.SOURCE;
            err       = talTemplateOverride.GetTemplateOverrideCriterias();
            dsResults = talTemplateOverride.ResultDataSet;
            return(dsResults);
        }
コード例 #15
0
        /// <summary>
        /// This methid retrieves Businessunits
        /// </summary>
        /// <returns>The formed template override view model</returns>
        public TemplateOverrideViewModel RetrieveBusinessUnitList()
        {
            TemplateOverrideViewModel viewModel = new TemplateOverrideViewModel(getContentAndAttributes: true);
            DESettings settings = Environment.Settings.DESettings;

            tbl_url_bu tblUrlBu = new tbl_url_bu(settings);
            DataTable  dtBUs    = tblUrlBu.GetDistinctEBusinessBUs();

            List <string> businessUnits = dtBUs.AsEnumerable().Select(r => r.Field <string>("BUSINESS_UNIT")).ToList();
            Dictionary <string, string> businessUnitsHash = businessUnits.ToDictionary(businessUnit => businessUnit);

            viewModel.BusinessUnitList = businessUnitsHash;
            return(viewModel);
        }
コード例 #16
0
        /// <summary>
        /// Get the available packages for the given available product code - Call to WS002R
        /// </summary>
        /// <param name="productCode">The hospitality product code</param>
        /// <returns>DataSet of available corporate hospitality packages and components</returns>
        private DataSet retrieveHospitalityPackages(string productCode)
        {
            DataSet       dsResults  = new DataSet();
            TalentProduct talProduct = new TalentProduct();
            DESettings    settings   = Environment.Settings.DESettings;
            ErrorObj      err        = new ErrorObj();

            talProduct.Settings        = settings;
            talProduct.De.ProductCode  = productCode;
            talProduct.De.BusinessUnit = settings.BusinessUnit;
            err       = talProduct.ProductHospitality();
            dsResults = talProduct.ResultDataSet;
            return(dsResults);
        }
コード例 #17
0
        /// <summary>
        /// Get the available products groups fixtures - Call to PG002S
        /// </summary>
        /// <param name="productGroupCode">The given product group code</param>
        /// <returns>DataSet of available corporate hospitality product groups fixtures</returns>
        private DataSet retrieveProductGroupFixtures(string productGroupCode)
        {
            DataSet       dsResults  = new DataSet();
            TalentProduct talProduct = new TalentProduct();
            DESettings    settings   = Environment.Settings.DESettings;
            ErrorObj      err        = new ErrorObj();

            talProduct.Settings            = settings;
            talProduct.De.Src              = GlobalConstants.SOURCE;
            talProduct.De.ProductGroupCode = productGroupCode;
            err       = talProduct.RetrieveProductGroupFixtures();
            dsResults = talProduct.ResultDataSet;
            return(dsResults);
        }
コード例 #18
0
        private HttpResponseMessage GetContent(DESettings settings, DLBase defaultList)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            string result = string.Empty;

            defaultList.Populate();
            DefaultListModel model = new DefaultListModel(defaultList.DEList);

            model.BackURL    = string.Format(model.BackURL, settings.BusinessUnit);
            result           = ViewRenderer.RenderView("~/Views/SystemDefaults/DefaultList.cshtml", model, null);
            response.Content = new StringContent(result);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return(response);
        }
コード例 #19
0
        /// <summary>
        /// Get the available hospitality product groups - Call to PG001S
        /// </summary>
        /// <returns>DataSet of available corporate hospitality product groups</returns>
        private DataSet retrieveProductGroups()
        {
            DataSet       dsResults  = new DataSet();
            TalentProduct talProduct = new TalentProduct();
            DESettings    settings   = Environment.Settings.DESettings;
            ErrorObj      err        = new ErrorObj();

            talProduct.Settings        = settings;
            talProduct.De.Src          = GlobalConstants.SOURCE;
            talProduct.De.BusinessUnit = settings.BusinessUnit;
            err       = talProduct.RetrieveProductGroups();
            dsResults = talProduct.ResultDataSet;
            return(dsResults);
        }
コード例 #20
0
ファイル: Utilities.cs プロジェクト: adv-hack/ETicketing
        /// <summary>
        /// XML Comment
        /// </summary>
        /// <param name="params"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static DESettings GetDESettings(Dictionary <string, string> @params)
        {
            DESettings settings = new DESettings();

            settings.FrontEndConnectionString = ConfigurationManager.ConnectionStrings["TalentEBusinessDBConnectionString"].ToString();
            settings.SessionID = @params["sessionid"];
            if (@params.ContainsKey("businessunit"))
            {
                settings.BusinessUnit = @params["businessunit"];
            }
            settings.DefaultBusinessUnit = ConfigurationManager.AppSettings.Get("DefaultBusinessUnit");
            if (@params.ContainsKey("listname"))
            {
                settings.ListName = @params["listname"];
            }
            if (@params.ContainsKey("modulename"))
            {
                settings.Module_Name = @params["modulename"];
            }
            else if (settings.Module_Name == string.Empty && settings.ListName != string.Empty)
            {
                settings.Module_Name = settings.ListName;
            }
            if (@params.ContainsKey("mode"))
            {
                settings.Mode = @params["mode"];
            }
            if (@params.ContainsKey("variablekey1"))
            {
                settings.VariableKey1 = @params["variablekey1"];
            }
            if (@params.ContainsKey("variablekey2"))
            {
                settings.VariableKey2 = @params["variablekey2"];
            }
            if (@params.ContainsKey("variablekey3"))
            {
                settings.VariableKey3 = @params["variablekey3"];
            }
            if (@params.ContainsKey("variablekey4"))
            {
                settings.VariableKey4 = @params["variablekey4"];
            }
            if (@params.ContainsKey("searchtext"))
            {
                settings.SearchText = @params["searchtext"];
            }
            return(settings);
        }
コード例 #21
0
        /// <summary>
        /// Get template overrides from the TM001 and TM002 files based on the given parameters
        /// </summary>
        /// <param name="inputModel">The given template override input model</param>
        /// <returns>A data set of results for all the template overrides</returns>
        private DataSet retrieveTemplateOverrides(TemplateOverrideInputModel inputModel)
        {
            DataSet dsResults = new DataSet();
            TalentTemplateOverride talTemplateOverride = new TalentTemplateOverride();
            DESettings             settings            = Environment.Settings.DESettings;
            ErrorObj err = new ErrorObj();

            talTemplateOverride.Settings = settings;
            talTemplateOverride.DeTemplate.BusinessUnit = inputModel.BusinessUnit;
            talTemplateOverride.DeTemplate.Mode         = inputModel.Mode;
            talTemplateOverride.DeTemplate.Source       = GlobalConstants.SOURCE;
            err       = talTemplateOverride.GetTemplateOverrideList();
            dsResults = talTemplateOverride.ResultDataSet;
            return(dsResults);
        }
コード例 #22
0
        /// <summary>
        /// Retrieve Data Capture Templates
        /// </summary>
        /// <returns>The Data Capture templates</returns>
        public TemplateOverrideViewModel RetrieveDataCaptureTemplateList(TemplateOverrideInputModel inputModelTemplateOverride)
        {
            TemplateOverrideViewModel viewModel = new TemplateOverrideViewModel(getContentAndAttributes: true);
            DESettings settings = Environment.Settings.DESettings;

            tbl_activity_templates tblActivityTemplates = new tbl_activity_templates(settings);
            DataTable dtActivityTemplates = tblActivityTemplates.GetByBU(inputModelTemplateOverride.BusinessUnit, Utilities.CheckForDBNull_Int(GlobalConstants.ACTIVITY_TEMPLATE_TYPE_HOSPITALITY_DATA_CAPTURE));

            viewModel.DataCaptureList = (from DataRow dr in dtActivityTemplates.Rows
                                         select new DataCaptureItem()
            {
                DataCaptureTemplateId = Utilities.ConvertStringToDecimal(dr["TEMPLATE_ID"].ToString()),
                DataCaptureTemplateDescription = dr["NAME"].ToString()
            }).OrderBy(s => s.DataCaptureTemplateDescription).ThenBy(s => s.DataCaptureTemplateId).ToList();
            return(viewModel);
        }
コード例 #23
0
        /// <summary>
        /// Create document for booking
        /// </summary>
        /// <param name="inputModel">The given hospitality booking enquiry input model</param>
        /// <returns>A data set of result with document creation status and path</returns>
        private DataSet createDocumentForBooking(HospitalityBookingEnquiryInputModel inputModel)
        {
            DataSet       dsResults  = new DataSet();
            TalentPackage talPackage = new TalentPackage();
            DESettings    settings   = Environment.Settings.DESettings;
            ErrorObj      err        = new ErrorObj();

            talPackage.Settings = settings;
            talPackage.DePackages.HospitalityBookingFilters = new HospitalityBookingFilters();
            talPackage.DePackages.BoxOfficeUser             = inputModel.LoggedInBoxOfficeUser;
            talPackage.DePackages.CallId         = inputModel.CallIdForDocumentProduction;
            talPackage.DePackages.CustomerNumber = inputModel.CustomerNumber;
            err       = talPackage.CreateHospitalityBookingDocument();
            dsResults = talPackage.ResultDataSet;
            return(dsResults);
        }
コード例 #24
0
        private HttpResponseMessage GetContent(DESettings settings, DatabaseUpdatesModel model = null, string action = "get")
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            string result = string.Empty;

            if (settings.Module_Name != string.Empty && settings.BusinessUnit != string.Empty)
            {
                if (model == null)
                {
                    model = new DatabaseUpdatesModel(settings);
                }
                result = ViewRenderer.RenderView("~/Views/DatabaseUpdates/DatabaseUpdates.cshtml", model, null);
            }
            response.Content = new StringContent(result);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
            return(response);
        }
コード例 #25
0
ファイル: Settings.cs プロジェクト: adv-hack/ETicketing
        private DESettings GetSettingsObject(bool withConnStringList = true)
        {
            DESettings settings = new DESettings();

            settings.BusinessUnit                  = BusinessUnit;
            settings.Partner                       = Partner;
            settings.FrontEndConnectionString      = FrontEndConnectionString;
            settings.DestinationDatabase           = GlobalConstants.SQL2005DESTINATIONDATABASE;
            settings.OriginatingSourceCode         = GlobalConstants.SOURCE;
            settings.CacheDependencyPath           = DefaultValues.CacheDependencyPath;
            settings.EcommerceModuleDefaultsValues = DefaultValues;
            settings.CanProcessFeesParallely       = DefaultValues.CanProcessFeesParallely;
            settings.AgentEntity                   = GetAgentEntity(DefaultValues.CacheDependencyPath);
            settings.StoredProcedureGroup          = DefaultValues.StoredProcedureGroup;
            if (HttpContext.Current.Session != null && Data.Session.Get("Agent") != null)
            {
                settings.IsAgent           = true;
                settings.OriginatingSource = GetOriginatingSource(Data.Session.Get("Agent").ToString());
            }
            if (withConnStringList)
            {
                settings.ConnectionStringList = GetConnectionStringList();
            }
            settings.LoginId         = GlobalConstants.GENERIC_CUSTOMER_NUMBER;
            settings.CurrentPageName = Page;

            //TODO: The BusinessLogic layer doesn't have the Profile object at the moment

            //if (HttpContext.Current.Profile != null)
            //{
            //    TalentProfileUser talProfileUser = (HttpContext.Current.Profile).User;
            //    if (talProfileUser != null && talProfileUser.Details != null)
            //    {
            //        if (!string.IsNullOrWhiteSpace(talProfileUser.Details.LoginID))
            //        {
            //            settings.LoginId = talProfileUser.Details.LoginID;
            //        }
            //    }
            //}

            //current page name
            //settings.CurrentPageName = (new FileInfo(Url)).Name.ToLower();
            //settings.DeliveryCountryCode = GetDeliveryCountryISOAlpha3Code();
            return(settings);
        }
コード例 #26
0
        /// <summary>
        /// Get details of Hospitality Product group Fixtures
        /// </summary>
        /// <param name="inputModel">The given hospitality product group input model</param>
        /// <returns>Hospitality Product group fixtures list</returns>
        public HospitalityProductGroupViewModel GetHospitalityProductGroupFixtures(HospitalityProductGroupInputModel inputModel)
        {
            HospitalityProductGroupViewModel viewModel   = new HospitalityProductGroupViewModel(getContentAndAttributes: true);
            DataSet               dsProductGroupFixtures = new DataSet();
            ErrorObj              err      = new ErrorObj();
            DEProductDetails      de       = new DEProductDetails();
            DESettings            settings = Environment.Settings.DESettings;
            List <ProductDetails> productGroupFixturesList = new List <ProductDetails>();

            dsProductGroupFixtures = retrieveProductGroupFixtures(inputModel.ProductGroupCode);
            viewModel.Error        = Data.PopulateErrorObject(err, dsProductGroupFixtures, settings, GlobalConstants.STATUS_RESULTS_TABLE_NAME, 2);

            if (!viewModel.Error.HasError)
            {
                productGroupFixturesList           = Data.PopulateObjectListFromTable <ProductDetails>(dsProductGroupFixtures.Tables["ProductGroupFixturesDeatils"]);
                viewModel.ProductGroupFixturesList = productGroupFixturesList;
            }
            return(viewModel);
        }
コード例 #27
0
        /// <summary>
        /// Retrieve Email Confirmation Templates
        /// </summary>
        /// <returns>The email confirmation templates</returns>
        public TemplateOverrideViewModel RetrieveEmailConfirmationList(TemplateOverrideInputModel inputModelTemplateOverride)
        {
            TemplateOverrideViewModel viewModel = new TemplateOverrideViewModel(getContentAndAttributes: true);
            DESettings settings = Environment.Settings.DESettings;

            tbl_email_templates tblEmailTemplates = new tbl_email_templates(settings);
            DataTable           dtEmailTemplates  = tblEmailTemplates.GetAll();
            DataView            dvEmailTemplates  = new DataView(dtEmailTemplates);

            dvEmailTemplates.RowFilter      = "BUSINESS_UNIT = '" + inputModelTemplateOverride.BusinessUnit + "' AND TEMPLATE_TYPE = '" + GlobalConstants.EMAIL_ORDER_CONFIRMATION + "' AND ACTIVE = 1";
            dtEmailTemplates                = dvEmailTemplates.ToTable();
            viewModel.EmailConfirmationList = (from DataRow dr in dtEmailTemplates.Rows
                                               select new EmailConfirmationItem()
            {
                SaleConfirmationEmailId = Utilities.ConvertStringToDecimal(dr["EMAILTEMPLATE_ID"].ToString()),
                SaleConfirmationEmailDescription = dr["NAME"].ToString()
            }).OrderBy(s => s.SaleConfirmationEmailDescription).ThenBy(s => s.SaleConfirmationEmailId).ToList();
            return(viewModel);
        }
コード例 #28
0
        /// <summary>
        /// Get the available packages for the given available product code - Call to WS002R
        /// </summary>
        /// <param name="productCode">The hospitality product code</param>
        /// <returns>DataTable of available corporate hospitality packages</returns>
        private DataSet retrievePackageDetails(string productCode)
        {
            DataSet       dsTalProductDataSet   = new DataSet();
            DataTable     dtHospitalityPackages = new DataTable();
            TalentProduct talProduct            = new TalentProduct();
            DESettings    settings = Environment.Settings.DESettings;
            ErrorObj      err      = new ErrorObj();
            ErrorModel    errModel = new ErrorModel();

            talProduct.Settings       = settings;
            talProduct.De.ProductCode = productCode;

            err      = talProduct.ProductHospitality();
            errModel = Data.PopulateErrorObject(err, talProduct.ResultDataSet, settings, 4);
            if (!errModel.HasError)
            {
                dsTalProductDataSet = talProduct.ResultDataSet;
            }
            return(dsTalProductDataSet);
        }
コード例 #29
0
        /// <summary>
        /// Get the available products for the corporate hospitality stadium - Call to WS016R
        /// </summary>
        /// <param name="corporateStadiumCode">The given corporate stadium code</param>
        /// <returns>DataTable of available corporate hospitality products</returns>
        private DataTable retrieveCorporateStadiumProducts(string corporateStadiumCode)
        {
            DataTable     dtHospitalityProducts = new DataTable();
            DataSet       dsResults             = new DataSet();
            TalentProduct talProduct            = new TalentProduct();
            DESettings    settings = Environment.Settings.DESettings;
            ErrorObj      err      = new ErrorObj();

            talProduct.Settings = settings;
            talProduct.De.PriceAndAreaSelection = Environment.Settings.DefaultValues.PriceAndAreaSelection;
            talProduct.De.Src         = GlobalConstants.SOURCE;
            talProduct.De.StadiumCode = Environment.Settings.DefaultValues.CorporateStadium;
            err       = talProduct.ProductList();
            dsResults = talProduct.ResultDataSet;
            if (dsResults != null && dsResults.Tables.Count > 0)
            {
                dtHospitalityProducts = dsResults.Tables["ProductListResults"];
            }
            return(dtHospitalityProducts);
        }
コード例 #30
0
        /// <summary>
        /// Attempts to solve the Variance Gamma Optimization problem using
        /// <see cref="Heston.VarianceGammaOptimizationProblem"/>.
        /// </summary>
        /// <param name="data">
        /// The data to be used in order to perform the optimization.
        /// </param>
        /// <param name="settings">The parameter is not used.</param>
        /// <returns>The results of the optimization.</returns>
        public EstimationResult Estimate(List <object> data, IEstimationSettings settings = null, IController controller = null, Dictionary <string, object> properties = null)
        {
            EquitySpotMarketData       espmd = data[0] as EquitySpotMarketData;
            CallPriceMarketData        cpmd  = data[1] as CallPriceMarketData;
            DiscountingCurveMarketData dcmd  = data[2] as DiscountingCurveMarketData;
            EquityCalibrationData      ecd   = new EquityCalibrationData(cpmd, dcmd);

            this.s0 = espmd.Price;
            this.r  = espmd.RiskFreeRate;
            this.q  = espmd.DividendYield;

            this.k  = ecd.Hdata.Strike;
            this.m  = ecd.Hdata.Maturity;
            this.cp = ecd.Hdata.CallPrice;

            Vector x0 = (Vector) new double[] { -0.1, 0.2, 0.1 };
            IOptimizationAlgorithm algorithm            = new QADE();
            OptimizationSettings   optimizationSettings = new DESettings();

            // Maximum number of iteration allowed.

            // Positive integer values print debug info.
            optimizationSettings.Verbosity = 1;

            // Tolerance.
            optimizationSettings.epsilon = 10e-5;
            var solution = algorithm.Minimize(new VarianceGammaOptimizationProblem(this.q, this.s0, this.k,
                                                                                   this.r, this.cp, this.m),
                                              optimizationSettings, x0);

            if (solution.errors)
            {
                return(new EstimationResult(solution.message));
            }

            var er = new EstimationResult();

            er.Names  = new string[] { "S0", "theta", "sigma", "nu", "rate", "dividend" };
            er.Values = new double[] { this.s0, solution.x[0], solution.x[1], solution.x[2], this.r, this.q };
            return(er);
        }
コード例 #31
0
        /// <summary>
        /// Attempts a calibration through <see cref="SwaptionHW1OptimizationProblem"/>
        /// using swaption matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            PFunction zr = new PFunction(null);
            // Loads the zero rate.
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            double deltak = dataset.SwaptionTenor;

            var swaptionsFiltering = settings as SwaptionsFiltering;

            if (swaptionsFiltering == null)
                swaptionsFiltering = new SwaptionsFiltering();//creates a default

            int maturitiesCount = dataset.OptionMaturity.Count(x => x >= swaptionsFiltering.MinSwaptionMaturity && x <= swaptionsFiltering.MaxSwaptionMaturity);
            int durationsCount = dataset.SwapDuration.Count(x => x >= swaptionsFiltering.MinSwapDuration && x <= swaptionsFiltering.MaxSwapDuration);

            Console.WriteLine(string.Format("Calibrating on {0} swaptions prices [#maturiries x #durations]=[{1} x {2}]", maturitiesCount * durationsCount, maturitiesCount,durationsCount));

            if (maturitiesCount * durationsCount == 0)
                return new EstimationResult("No swaptions satisfying criteria found, please relax filters");

            Matrix swaptionsVolatility = new Matrix(maturitiesCount, durationsCount);// dataset.SwaptionsVolatility;
            Vector optionMaturity = new Vector(maturitiesCount);// dataset.OptionMaturity;
            Vector swapDuration = new Vector(durationsCount);// dataset.SwapDuration;

            //Build filtered matrix and vectors
            int fm=0;
            for (int m = 0; m < dataset.OptionMaturity.Length; m++)
            {
                int fd=0;
                if (dataset.OptionMaturity[m] >= swaptionsFiltering.MinSwaptionMaturity && dataset.OptionMaturity[m] <= swaptionsFiltering.MaxSwaptionMaturity)
                {
                    for (int d = 0; d < dataset.SwapDuration.Length; d++)
                    {
                        if (dataset.SwapDuration[d] >= swaptionsFiltering.MinSwapDuration && dataset.SwapDuration[d] <= swaptionsFiltering.MaxSwapDuration)
                        {
                            swaptionsVolatility[fm, fd] = dataset.SwaptionsVolatility[m, d];
                            swapDuration[fd] = dataset.SwapDuration[d];
                            fd++; }
                    }

                    optionMaturity[fm] = dataset.OptionMaturity[m];
                    fm++;
                }

            }

            SwaptionsBlackModel swbm = new SwaptionsBlackModel(zr);

            Matrix fsr;
            var blackSwaptionPrice = 1000.0 * swbm.SwaptionsSurfBM(optionMaturity, swapDuration, swaptionsVolatility, deltak, out fsr);

            Console.WriteLine("SwaptionHWEstimator: Black model prices");
            Console.WriteLine(blackSwaptionPrice);

            SwaptionHW1 swhw1 = new SwaptionHW1(zr);
            SwaptionHW1OptimizationProblem problem = new SwaptionHW1OptimizationProblem(swhw1, blackSwaptionPrice, optionMaturity, swapDuration, deltak);

            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 20;
            o.MaxIter = 5;
            o.Verbosity = 1;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 0.1, 0.1 });
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-8;
            o.h = 10e-8;
            o.MaxIter = 1000;

            // We can permit this, given it is fast.
            o.accourate_numerical_derivatives = true;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            double obj = problem.Obj(solution.x);

            return result;
        }
コード例 #32
0
        /// <summary>
        /// Attempts a calibration through <see cref="PelsserCappletOptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;
            EstimationResult result;
            if ((dataset.ZRMarket == null) || (dataset.CapVolatility == null))
            {
                result = new EstimationResult();
                result.ErrorMessage = "Not enough data to calibrate.\n" +
                    "The estimator needs a ZRMarket and a CapVolatility " +
                    "defined inside InterestRateMarketData";
                return result;
            }

            // Backup the dates
            DateTime effectiveDate = DateTime.Now.Date;
            DateTime valuationDate = DateTime.Now.Date;
            if (Document.ActiveDocument != null)
            {
                effectiveDate = Document.ActiveDocument.ContractDate;
                valuationDate = Document.ActiveDocument.SimulationStartDate;
            }

            // Creates the Context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            Function zr = new PFunction(null);
            zr.VarName = "zr";
            // Load the zr.
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            prj.Symbols.Add(zr);

            BlackModel bm = new BlackModel(zr);

            double deltak = dataset.CapTenor;

            Matrix capVol = dataset.CapVolatility;
            Vector capMat = dataset.CapMaturity;
            Vector capK = dataset.CapRate;

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Matrix calculated with black.
            Matrix blackCaps = new Matrix(capMat.Length, capK.Length);
            for (int m = 0; m < capMat.Length; m++)
            {
                for (int s = 0; s < capK.Length; s++)
                {
                    bool skip = false;
                    if (preferences != null)
                    {
                        if (capK[s] < preferences.MinCapRate || capK[s] > preferences.MaxCapRate ||
                           capMat[m] < preferences.MinCapMaturity || capMat[m] > preferences.MaxCapMaturity)
                                {skip = true; }
                    }

                    if (capVol[m, s] == 0 || skip)
                        blackCaps[m, s] = 0;
                    else
                        blackCaps[m, s] = bm.Cap(capK[s], capVol[m, s], deltak, capMat[m]);
                }
            }

            if (blackCaps.IsNAN())
            {
                Console.WriteLine("Black caps matrix has non real values:");
                Console.WriteLine(blackCaps);
                throw new Exception("Cannot calculate Black caps");
            }

            // Maturity goes from 0 to the last item with step deltaK.
            Vector maturity = new Vector((int)(1.0 + capMat[capMat.Length - 1] / deltak));
            for (int l = 0; l < maturity.Length; l++)
                maturity[l] = deltak * l;

            Vector fwd = new Vector(maturity.Length - 1);
            for (int i = 0; i < fwd.Length; i++)
            {
                fwd[i] = bm.Fk(maturity[i + 1], deltak);
            }

            // Creates a default Pelsser model.
            Pelsser.SquaredGaussianModel model = new Pelsser.SquaredGaussianModel();
            model.a1 = (ModelParameter)0.014;
            model.sigma1 = (ModelParameter)0.001;
            model.zr = (ModelParameter)"@zr";
            StochasticProcessExtendible iex = new StochasticProcessExtendible(prj, model);
            prj.Processes.AddProcess(iex);

            prj.Parse();

            DateTime t0 = DateTime.Now;
            Caplet cp = new Caplet();

            PelsserCappletOptimizationProblem problem = new PelsserCappletOptimizationProblem(prj, cp, maturity, fwd, capK, deltak, capMat, blackCaps);

            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 35;
            o.TargetCost = 0.0025;
            o.MaxIter = 10;
            o.Verbosity = Math.Max(1, Engine.Verbose);
            o.controller = controller;
            // Parallel evaluation is not supported for this calibration.
            o.Parallel = false;
            o.Debug = true;
            SolutionInfo solution = null;

            Vector x0 = (Vector)new double[] { 0.1, 0.1 };

            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-7;
            o.h = 10e-7;
            o.MaxIter = 1000;
            o.Debug = true;
            o.Verbosity = Math.Max(1, Engine.Verbose);

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);

            if (solution.errors)
                return new EstimationResult(solution.message);

            Console.WriteLine(solution);

            string[] names = new string[] { "alpha1", "sigma1" };
            result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();
            result.Objects = new object[1];
            result.Objects[0] = solution.obj;
            //result.Fit = solution.obj;//Uncomment in 1.6
            // Restore the dates
            if (Document.ActiveDocument != null)
            {
                Document.ActiveDocument.ContractDate = effectiveDate;
                Document.ActiveDocument.SimulationStartDate = valuationDate;
            }

            return result;
        }
コード例 #33
0
        /// <summary>
        /// Attempts to solve the Heston optimization problem using
        /// <see cref="Heston.HestonOptimizationProblem"/>.
        /// </summary>
        /// <param name="marketData">Data to be used in order to perform the optimization.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">IController.</param>
        /// <returns>The results of the optimization.</returns>
        public EstimationResult Estimate(List<object> marketData, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            DateTime t0 = DateTime.Now;
            var interestDataSet = (CurveMarketData)marketData[0];
            CallPriceMarketData callDataSet = (CallPriceMarketData)marketData[1];
            EquityCalibrationData equityCalData = new EquityCalibrationData(callDataSet, interestDataSet);
            var spotPrice = (DVPLI.MarketDataTypes.Scalar)marketData[2];

            Setup(equityCalData, settings);

            var calSettings = settings as HestonCalibrationSettings;
            // Creates the context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            // Optimization problem instance.
            Vector matBound = new Vector(2);
            Vector strikeBound = new Vector(2);
            if (calSettings != null)
            {
                matBound[0] = calSettings.MinMaturity;
                matBound[1] = calSettings.MaxMaturity;
                strikeBound[0] = calSettings.MinStrike;
                strikeBound[1] = calSettings.MaxStrike;
            }
            else
            {
                //use defaults
                matBound[0] = 1.0 / 12;// .25;
                matBound[1] = 6;// 10; //Up to 6Y maturities
                strikeBound[0] = 0.4;
                strikeBound[1] = 1.6;
            }
            Console.WriteLine(callDataSet);
            /*
            //CBA TEST
            matBound[0] = 1;// .25;
            matBound[1] = 3.5;// 10; //Up to 6Y maturities
            strikeBound[0] = 0.5;// 0.5;
            strikeBound[1] = 2;//1.5;
            */
            HestonCallOptimizationProblem problem = NewOptimizationProblem(equityCalData, matBound, strikeBound);
            int totalOpts = problem.numCall + problem.numPut;
            Console.WriteLine("Calibration based on "+totalOpts+ " options. (" + problem.numCall + " call options and "+problem.numPut+" put options).");

            IOptimizationAlgorithm solver = new  QADE();
            //IOptimizationAlgorithm solver = new MultiLevelSingleLinkage();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.controller = controller;

            // If true the optimization algorithm will operate in parallel.
            o.Parallel = Engine.MultiThread;
            o.h = 10e-8;
            o.epsilon = 10e-8;

            SolutionInfo solution = null;

            double minObj=double.MaxValue;
            Vector minX= null;
            int Z = 1;
            //if (problem.GetType() == typeof(Heston.HestonCallSimulationOptimizationProblem))
            //    Z = 2;

            for(int z=0;z<Z;z++)
            {
                if (solver.GetType() == typeof(MultiLevelSingleLinkage))
                {
                    o.NP = 50;
                    o.MaxIter = 25;
                    o.MaxGamma = 6;
                }
                else
                {
                    o.NP = 60;
                    o.MaxIter = 35;
                }
                o.Verbosity = 1;
            Vector x0 = null;// new Vector(new double[] { 0.5, 0.5, 0.8, -0.5, 0.05 });

            // GA
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return null;

            o.options = "qn";
            o.MaxIter = 500;// 1000;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
            {
                solution = solver2.Minimize(problem, o, x0);
            }
            if (solution.errors)
                return null;

            if (solution.obj < minObj)
            {
                minObj = solution.obj;
                minX = solution.x.Clone();
            }
            }

            solution.obj = minObj;
            solution.x = minX;

            //Displays pricing error structure
            HestonCallOptimizationProblem.displayObjInfo = true;
            problem.Obj(solution.x);
            HestonCallOptimizationProblem.displayObjInfo = false;
            Console.WriteLine("Calibration Time (s)\t" + (DateTime.Now - t0).TotalSeconds);

            return BuildEstimate(spotPrice,interestDataSet, callDataSet, equityCalData, solution);
        }
コード例 #34
0
        /// <summary>
        /// Attempts a calibration through <see cref="CapsHW1OptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">The controller which may be used to cancel the process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            PFunction zr = new PFunction(null);
            zr.VarName = "zr";

            var preferences = settings as Fairmat.Calibration.CapVolatilityFiltering;

            // Loads ZR
            double[,] zrvalue = (double[,])ArrayHelper.Concat(dataset.ZRMarketDates.ToArray(), dataset.ZRMarket.ToArray());
            zr.Expr = zrvalue;

            BlackModel bm = new BlackModel(zr);

            double deltak = dataset.CapTenor;

            if (dataset.CapVolatility == null)
                return new EstimationResult("Cap not available at requested date");

            Matrix capVolatility = dataset.CapVolatility;
            Vector capMaturity = dataset.CapMaturity;
            Vector capRate = dataset.CapRate;
            double a = 0.1;
            double sigma = 0.1;

            // Matrix calculated with Black.
            Matrix blackCaps = new Matrix(capMaturity.Length, capRate.Length);
            Matrix logic = new Matrix(capMaturity.Length, capRate.Length);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    blackCaps[m, s] = bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                    if (double.IsNaN(blackCaps[m, s]))
                    {
                        bm.Cap(capRate[s], capVolatility[m, s], deltak, capMaturity[m]);
                        throw new Exception("Malformed black caps");
                    }

                    if (blackCaps[m, s] == 0.0)
                    {
                        logic[m, s] = 0.0;
                    }
                    else
                    {
                        logic[m, s] = 1.0;
                    }

                    //filter
                    if (preferences != null)
                    {
                        if (capRate[s] < preferences.MinCapRate || capRate[s] > preferences.MaxCapRate ||
                            capMaturity[m]<preferences.MinCapMaturity|| capMaturity[m]>preferences.MaxCapMaturity)
                                {logic[m, s] = 0; blackCaps[m, s] = 0;}
                    }

                }
            }

            DateTime t0 = DateTime.Now;
            CapHW1 hw1Caps = new CapHW1(zr);
            Matrix caps = hw1Caps.HWMatrixCaps(capMaturity, capRate, a, sigma, deltak);

            for (int m = 0; m < capMaturity.Length; m++)
            {
                for (int s = 0; s < capRate.Length; s++)
                {
                    caps[m, s] = logic[m, s] * caps[m, s];
                }
            }

            CapsHW1OptimizationProblem problem = new CapsHW1OptimizationProblem(hw1Caps, blackCaps, capMaturity, capRate, deltak);
            Vector provaparam = new Vector(2);

            var solver = new QADE();

            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 20;
            o.MaxIter = 10;
            o.Verbosity = 1;
            o.Parallel = false;
            SolutionInfo solution = null;
            Vector x0 = new Vector(new double[] { 0.05, 0.01 });
            o.controller = controller;
            solution = solver.Minimize(problem, o, x0);

            o.epsilon = 10e-8;
            o.h = 10e-8;

            o.MaxIter = 100;
            solution = solver2.Minimize(problem, o, solution.x);
            if (solution.errors)
                return new EstimationResult(solution.message);
            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = new string[] { "Alpha", "Sigma" };

            //solution.x[0] *= 3;

            EstimationResult result = new EstimationResult(names, solution.x);

            result.ZRX = (double[])dataset.ZRMarketDates.ToArray();
            result.ZRY = (double[])dataset.ZRMarket.ToArray();

            return result;
        }
コード例 #35
0
        /// <summary>
        /// Attempts to solve the Variance Gamma Optimization problem using
        /// <see cref="Heston.VarianceGammaOptimizationProblem"/>.
        /// </summary>
        /// <param name="data">
        /// The data to be used in order to perform the optimization.
        /// </param>
        /// <param name="settings">The parameter is not used.</param>
        /// <returns>The results of the optimization.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            EquitySpotMarketData espmd = data[0] as EquitySpotMarketData;
            CallPriceMarketData cpmd = data[1] as CallPriceMarketData;
            DiscountingCurveMarketData dcmd = data[2] as DiscountingCurveMarketData;
            EquityCalibrationData ecd = new EquityCalibrationData(cpmd, dcmd);
            this.s0 = espmd.Price;
            this.r = espmd.RiskFreeRate;
            this.q = espmd.DividendYield;

            this.k = ecd.Hdata.Strike;
            this.m = ecd.Hdata.Maturity;
            this.cp = ecd.Hdata.CallPrice;

            Vector x0 = (Vector)new double[] { -0.1, 0.2, 0.1 };
            IOptimizationAlgorithm algorithm = new QADE();
            OptimizationSettings optimizationSettings = new DESettings();

            // Maximum number of iteration allowed.

            // Positive integer values print debug info.
            optimizationSettings.Verbosity = 1;

            // Tolerance.
            optimizationSettings.epsilon = 10e-5;
            var solution = algorithm.Minimize(new VarianceGammaOptimizationProblem(this.q, this.s0, this.k,
                                                                          this.r, this.cp, this.m),
                                                                          optimizationSettings, x0);

            if (solution.errors)
                return new EstimationResult(solution.message);

            var er = new EstimationResult();
            er.Names= new string[]{"S0","theta","sigma","nu","rate","dividend"};
            er.Values = new double[] {this.s0,solution.x[0],solution.x[1],solution.x[2],this.r,this.q};
            return er;
        }
コード例 #36
0
        /// <summary>
        /// Attempts a calibration through <see cref="CapsCIROptimizationProblem"/>
        /// using caps matrices.
        /// </summary>
        /// <param name="data">The data to be used in order to perform the calibration.</param>
        /// <param name="settings">The parameter is not used.</param>
        /// <param name="controller">A controller used for the optimization process.</param>
        /// <returns>The results of the calibration.</returns>
        public EstimationResult Estimate(List<object> data, IEstimationSettings settings = null, IController controller = null, Dictionary<string, object> properties = null)
        {
            InterestRateMarketData dataset = data[0] as InterestRateMarketData;

            // Creates the context.
            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);

            CapCIROptimizationProblem problem = new CapCIROptimizationProblem(dataset);
            IOptimizationAlgorithm solver = new QADE();
            IOptimizationAlgorithm solver2 = new SteepestDescent();

            DESettings o = new DESettings();
            o.NP = 50;
            o.MaxIter = 50;
            o.Verbosity = 1;
            o.Parallel = false;
            o.controller = controller;
            SolutionInfo solution = null;

            Vector x0 = new Vector(new double[] { 1, 0.01, 0.05 });
            solution = solver.Minimize(problem, o, x0);
            if (solution.errors)
                return new EstimationResult(solution.message);

            o.epsilon = 10e-10;
            o.h = 10e-10;
            o.MaxIter = 1000;

            if (solution != null)
                solution = solver2.Minimize(problem, o, solution.x);
            else
                solution = solver2.Minimize(problem, o, x0);

            if (solution.errors)
                return new EstimationResult(solution.message);

            Console.WriteLine("Solution:");
            Console.WriteLine(solution);
            string[] names = CIR.parameterNames;
            Vector values = new Vector(4);
            values[Range.New(0, 2)] = solution.x;
            values[3] = problem.r0;

            EstimationResult result = new EstimationResult(names, values);

            return result;
        }