Ejemplo n.º 1
0
        private static int GetBest(string method, Dictionary <string, IEnumerable <ForecastResult> > forecast, float actual)
        {
            if (forecast == null || !forecast.Any())
            {
                return(0);
            }
            ForecastResult best   = null;
            float          minErr = float.MaxValue;

            foreach (var fr in forecast[method])
            {
                // TODO: MAPE ?
                var currErr = Math.Abs(fr.Result[0] - actual);
                if (currErr < minErr)
                {
                    minErr = currErr;
                    best   = fr;
                }
            }

            return(best?.WindowOffset ?? 0);
        }
Ejemplo n.º 2
0
        } // pure static class

        /// <summary>
        /// Raw-level ARIMA forecasting function.
        /// </summary>
        /// <param name="data"> UNMODIFIED, list of double numbers representing time-series with constant time-gap </param>
        /// <param name="forecastSize"> integer representing how many data points AFTER the data series to be
        ///        forecasted </param>
        /// <param name="params"> ARIMA parameters </param>
        /// <returns> a ForecastResult object, which contains the forecasted values and/or error message(s) </returns>
        //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
        //ORIGINAL LINE: public static TimeSeries.Forecast.TimeSeries.Arima.struct.ForecastResult forecast_arima(final double[] data, final int forecastSize, TimeSeries.Forecast.TimeSeries.Arima.struct.ArimaParams params)
        public static ForecastResult forecast_arima(double[] data, int forecastSize, ArimaParams @params)
        {
            try
            {
                int p = @params.p;

                int d = @params.d;

                int         q = @params.q;
                int         P = @params.P;
                int         D = @params.D;
                int         Q = @params.Q;
                int         m = @params.m;
                ArimaParams paramsForecast    = new ArimaParams(p, d, q, P, D, Q, m);
                ArimaParams paramsXValidation = new ArimaParams(p, d, q, P, D, Q, m);
                // estimate ARIMA model parameters for forecasting
                ArimaModel fittedModel = ArimaSolver.estimateARIMA(paramsForecast, data, data.Length, data.Length + 1);

                // compute RMSE to be used in confidence interval computation
                double rmseValidation = ArimaSolver.computeRMSEValidation(data, ForecastUtil.testSetPercentage, paramsXValidation);
                fittedModel.RMSE = rmseValidation;
                ForecastResult forecastResult = fittedModel.Forecast(forecastSize);

                // populate confidence interval
                forecastResult.Sigma2AndPredicationInterval = fittedModel.Params;

                // add logging messages
                forecastResult.Log("{" + "\"Best ModelInterface Param\" : \"" + fittedModel.Params.summary() + "\"," + "\"Forecast Size\" : \"" + forecastSize + "\"," + "\"Input Size\" : \"" + data.Length + "\"" + "}");

                // successfully built ARIMA model and its forecast
                return(forecastResult);
            }
            catch (Exception ex)
            {
                // failed to build ARIMA model
                throw new Exception("Failed to build ARIMA forecast: " + ex.Message);
            }
        }
Ejemplo n.º 3
0
        private double[] CommonTestSimpleForecast(string name, double[] trainingData, double[] trueForecastData, int forecastSize, int p, int d, int q, int P, int D, int Q, int m)
        {
            //Make forecast
            ForecastResult forecastResult = ArimaForecaster.forecast_arima(trainingData, forecastSize, new ArimaParams(p, d, q, P, D, Q, m));

            //Get forecast data and confidence intervals
            double[] forecast = forecastResult.Forecast;
            double[] upper    = forecastResult.ForecastUpperConf;
            double[] lower    = forecastResult.ForecastLowerConf;

            //Building output
            StringBuilder sb = new StringBuilder();

            sb.Append(name).Append("  ****************************************************\n");
            sb.Append("Input Params { ").Append("p: ").Append(p).Append(", d: ").Append(d).Append(", q: ").Append(q).Append(", P: ").Append(P).Append(", D: ").Append(D).Append(", Q: ").Append(Q).Append(", m: ").Append(m).Append(" }");
            sb.Append("\n\nFitted Model RMSE: ").Append(dbl2str(forecastResult.RMSE));
            sb.Append("\n\n      TRUE DATA    |     LOWER BOUND          FORECAST       UPPER BOUND\n");

            for (int i = 0; i < forecast.Length; ++i)
            {
                sb.Append(dbl2str(trueForecastData[i])).Append("    | ").Append(dbl2str(lower[i])).Append("   ").Append(dbl2str(forecast[i])).Append("   ").Append(dbl2str(upper[i])).Append("\n");
            }

            sb.Append("\n");

            //Compute RMSE against true forecast data
            double temp = 0.0;

            for (int i = 0; i < forecast.Length; ++i)
            {
                temp += Math.Pow(forecast[i] - trueForecastData[i], 2);
            }
            double rmse = Math.Pow(temp / forecast.Length, 0.5);

            sb.Append("RMSE = ").Append(dbl2str(rmse)).Append("\n\n");
            Console.WriteLine(sb.ToString());
            return(forecast);
        }
Ejemplo n.º 4
0
        public void test_run()
        {
            FinancialInstrument instr    = controller.get_instrument("SPFB.Si_090101_091231.txt");
            TradingStrategy     strategy = controller.get_strategy("Test5").Originator;

            strategy.subscribe_analyzer(new AnalyzerDirection());

            ForecastingModule forecastingModule = new ForecastingModule(strategy, instr);
            ForecastResult    result            = forecastingModule.run();

            //result.print();
            double profitExepted = -3419;

            int      numDeal = 5;
            TypeDeal expType = TypeDeal.Buy;
            DateTime expDateOpen = new DateTime(2009, 5, 13, 10, 49, 0);
            DateTime expDateClose = new DateTime(2009, 5, 13, 10, 53, 0);
            double   expOpenPrice = 32110, expClosePrice = 32094;

            TradeDeal tradeDeal = result.get_deal(numDeal);

            double   actOpenPrice     = tradeDeal.OpeningPrice;
            double   actClosePrice    = tradeDeal.ClosingPrice;
            DateTime actDateTimeOpen  = tradeDeal.DateTimeOpen;
            DateTime actDateTimeClose = tradeDeal.DateTimeClose;


            Assert.AreEqual(true,
                            profitExepted == result.CurProfit &&
                            tradeDeal.Opening == false &&
                            tradeDeal.Type == expType &&
                            actOpenPrice == expOpenPrice &&
                            actClosePrice == expClosePrice &&
                            actDateTimeOpen == expDateOpen &&
                            actDateTimeClose == expDateClose);
        }
Ejemplo n.º 5
0
        public async Task <IEnumerable <IForecastResult> > GetForecasts(IQuery <string, Forecast> currentQuery)
        {
            if (currentQuery == null)
            {
                throw new ArgumentNullException(ErrorMessages.ArgumentNullMessage(nameof(currentQuery)));
            }

            var tasksToExecute = currentQuery.Queries.Select(queryLocation => UrlProvider.SetLocation(queryLocation).GetUriAsString())
                                 .Select(urlToCall => Client.GetForecastAsync(urlToCall));

            var results = await Task.WhenAll(tasksToExecute).ConfigureAwait(false);

            return(results.Where(response => response.Any())
                   .Select(response => response.Single())
                   .Select(response =>
            {
                var tempResult = new ForecastResult(response.City.DisplayName);
                var Satisfied = response.Forecasts.Where(forecast => currentQuery.IsSatisfiedBy(forecast));
                tempResult.AddRange(Satisfied);
                return tempResult;
            }).
                   Where(matchedForecast => matchedForecast.ForecastData.Any()) // Filter out, if no match was found
                   .ToList());
        }
Ejemplo n.º 6
0
        //public List<sp_Forecast_GetDailyAvereageProductTransactions_Result> GetDailyAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetDailyAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetDailyTimeSpecificAvereageProductTransactions_Result> GetDailyTimeSpecificAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetDailyTimeSpecificAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetWeeklyAverageTransactions_Result> GetWeeklyAverageTransactions()
        //{
        //    var result = db.sp_Forecast_GetWeeklyAverageTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetWeeklyAvereageProductTransactions_Result> GetWeeklyAvereageProductTransactions()
        //{
        //    var result = db.sp_Forecast_GetWeeklyAvereageProductTransactions();
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountYearDayByProductId_Result> GetProductCountYearDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountYearDayByProductId(productId);
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountMonthDayByProductId_Result> GetProductCountMonthDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountMonthDayByProductId(productId);
        //    return result.ToList();
        //}

        //public List<sp_Forecast_GetProductCountDayByProductId_Result> GetProductCountDayByProductId(int productId)
        //{
        //    var result = db.sp_Forecast_GetProductCountDayByProductId(productId);
        //    return result.ToList();
        //}
        #endregion

        #region R_Related

        public ForecastResult ForecastByMethod(int branchId, int productId, string method, string dataType, int periods)
        {
            ForecastResult forecastResult = new ForecastResult();

            //Methods method1 = (Methods)Enum.Parse(typeof(Methods), method, true);
            DataPeriod datatype1 = (DataPeriod)Enum.Parse(typeof(DataPeriod), dataType, true);

            //int productId = 1;
            //Methods method = Methods.rwf; //meanf(YYMMDD,MMDD,MMWWDD,DD), rtw, rtw(with Drift), Moving AVG,ets, Arima, HoltWinters, msts
            //DataPeriod dataType = DataPeriod.Daily;
            //int periods = 50;

            var values = GetCorrespondingDataByPeriod(datatype1, productId);

            //FFCEntities db = new FFCEntities();
            //var list = db.sp_Forecast_GetProductCountYearDayByProductId(productId).ToList();
            //List<double> values = list.Select(r => Double.Parse(r.Count.ToString())).ToList();
            //REngine.SetEnvironmentVariables(@"C:\Program Files\R\R-2.13.1\bin\i386");

            //SetupPath();
            //Log();

            REngine.SetEnvironmentVariables();

            // There are several options to initialize the engine, but by default the following suffice:
            REngine engine = REngine.GetInstance();

            //engine.Initialize();

            // .NET Framework array to R vector.
            //NumericVector testTs = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99, 1000 });
            //NumericVector testTs = engine.CreateNumericVector(new double[] { 10, 20, 30, 40, 50 });
            NumericVector data = engine.CreateNumericVector(values);

            engine.SetSymbol("data", data);
            //auto arima for monthly
            engine.Evaluate("tsValue <- ts(data, frequency=160, start=c(2013.5))");
            engine.Evaluate("library(forecast)");
            engine.Evaluate(String.Format("Fit <- {0}(tsValue)", method.ToString())); // Fit <- Arima(tsValue)
            //MethodManipulation(engine, method);
            engine.Evaluate(String.Format("fcast <- forecast(Fit, h={0})", periods));

            string image = PlotForecast(engine, method.ToString());

            //var a = engine.Evaluate("fcast <- forecast(tsValue, h=5)").AsCharacter();
            NumericVector forecasts = engine.Evaluate("fcast$mean").AsNumeric();

            //NumericVector forecasts = engine.Evaluate("fcast$lower[,2]").AsNumeric();

            forecastResult.BranchId       = branchId;
            forecastResult.ProductId      = productId;
            forecastResult.Method         = db.Forecast_Methods.Where(r => r.ForecastIdentifier == method).Select(a => a.ForecastMethod).FirstOrDefault();
            forecastResult.DatePeriod     = datatype1.ToString();
            forecastResult.ForecastPeriod = periods;
            forecastResult.Values         = forecasts.ToList();
            forecastResult.ImagePath      = "~/Content/Images/" + image;

            //foreach (var item in forecasts)
            //{
            //    Console.WriteLine(item);
            //}

            //engine.Dispose();

            return(forecastResult);
        }
        /// <summary>
        /// Gets the best weather of the forecast that is 5 times of three hours periods.
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>

        public static ForecastResult GetBestWeather(string destination, string json, int daysrange)
        {
            var                      result         = JsonConvert.DeserializeObject <WeatherForecast>(json);
            WeatherForecast          forecast       = result;
            ForecastResult           bestweather    = new ForecastResult();
            var                      currentWeather = string.Empty;
            var                      choosenWeather = string.Empty;
            Dictionary <int, string> _storedWeather = new Dictionary <int, string>();

            // Here we got the selected daysrange we have choosen by the slider in the frontend.
            int timespan = FormatFunction.GetTimespan(daysrange);

            //  Here we get the weather of the forecast list from the json object and store it in a dictionary
            for (var i = 0; i < timespan; i++)
            {
                if (forecast.list[i].weather[0].Main == WeatherType.Clear.ToString())
                {
                    // Gets the current weather if weather is Clear
                    var key = i;
                    currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                    choosenWeather = currentWeather;
                    GetCurrentBestWeather(key, bestweather, forecast);
                    break;
                }
                else
                {
                    if (forecast.list[i].weather[0].Main == WeatherType.Clouds.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }

                    if (forecast.list[i].weather[0].Main == WeatherType.Fog.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }

                    if (forecast.list[i].weather[0].Main == WeatherType.Drizzle.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }

                    if (forecast.list[i].weather[0].Main == WeatherType.Rain.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }

                    if (forecast.list[i].weather[0].Main == WeatherType.Thunderstorm.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }

                    if (forecast.list[i].weather[0].Main == WeatherType.Snow.ToString())
                    {
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        _storedWeather.Add(i, currentWeather);
                    }
                }
            }

            if (choosenWeather != WeatherType.Clear.ToString())
            {
                var firstcloud = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Clouds.ToString());
                //If best weather is cloads
                if (firstcloud.Value != null)
                {
                    foreach (var item in _storedWeather)
                    {
                        if (item.Value == firstcloud.Value)
                        {
                            choosenWeather = WeatherType.Clouds.ToString();
                            var key = item.Key;
                            GetCurrentBestWeather(key, bestweather, forecast);
                            break;
                        }
                    }
                }

                if (choosenWeather != WeatherType.Clouds.ToString())
                {
                    //If best weather is fog
                    var firstfog = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Fog.ToString());
                    if (firstfog.Value != null)
                    {
                        foreach (var item in _storedWeather)
                        {
                            if (item.Value == firstfog.Value)
                            {
                                choosenWeather = WeatherType.Fog.ToString();
                                var key = item.Key;
                                GetCurrentBestWeather(key, bestweather, forecast);
                                break;
                            }
                        }
                    }
                }

                if (choosenWeather != WeatherType.Clouds.ToString())
                {
                    if (choosenWeather != WeatherType.Fog.ToString())
                    {
                        //If best weather is drizzle
                        var firstdrizzle = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Drizzle.ToString());
                        if (firstdrizzle.Value != null)
                        {
                            foreach (var item in _storedWeather)
                            {
                                if (item.Value == firstdrizzle.Value)
                                {
                                    choosenWeather = WeatherType.Drizzle.ToString();
                                    var key = item.Key;
                                    GetCurrentBestWeather(key, bestweather, forecast);
                                    break;
                                }
                            }
                        }
                    }
                }

                if (choosenWeather != WeatherType.Drizzle.ToString())
                {
                    if (choosenWeather != WeatherType.Fog.ToString())
                    {
                        if (choosenWeather != WeatherType.Clouds.ToString())
                        {
                            //If best weather is rain
                            var firstrain = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Rain.ToString());
                            if (firstrain.Value != null)
                            {
                                foreach (var item in _storedWeather)
                                {
                                    if (item.Value == firstrain.Value)
                                    {
                                        choosenWeather = WeatherType.Rain.ToString();
                                        var key = item.Key;
                                        GetCurrentBestWeather(key, bestweather, forecast);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (choosenWeather != WeatherType.Rain.ToString())
                {
                    if (choosenWeather != WeatherType.Drizzle.ToString())
                    {
                        if (choosenWeather != WeatherType.Fog.ToString())
                        {
                            if (choosenWeather != WeatherType.Clouds.ToString())
                            {
                                //If best weather is thunderstorm
                                var firstthunderstorm = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Thunderstorm.ToString());
                                if (firstthunderstorm.Value != null)
                                {
                                    foreach (var item in _storedWeather)
                                    {
                                        if (item.Value == firstthunderstorm.Value)
                                        {
                                            choosenWeather = WeatherType.Thunderstorm.ToString();
                                            var key = item.Key;
                                            GetCurrentBestWeather(key, bestweather, forecast);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (choosenWeather != WeatherType.Thunderstorm.ToString())
                {
                    if (choosenWeather != WeatherType.Rain.ToString())
                    {
                        if (choosenWeather != WeatherType.Drizzle.ToString())
                        {
                            if (choosenWeather != WeatherType.Fog.ToString())
                            {
                                if (choosenWeather != WeatherType.Clouds.ToString())
                                {
                                    //If best weather is snow
                                    var firstsnow = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Snow.ToString());
                                    foreach (var item in _storedWeather)
                                    {
                                        if (item.Value == firstsnow.Value)
                                        {
                                            choosenWeather = WeatherType.Snow.ToString();
                                            var key = item.Key;
                                            GetCurrentBestWeather(key, bestweather, forecast);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(bestweather);
        }
        /// <summary>
        /// Gets the worst weather of the forecast that is 8 times of three hours periods.
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>

        public static ForecastResult GetWorstWeather(string destination, string json, int daysrange)
        {
            var                      result             = JsonConvert.DeserializeObject <WeatherForecast>(json);
            WeatherForecast          forecast           = result;
            ForecastResult           worstweather       = new ForecastResult();
            var                      currentWeather     = string.Empty;
            var                      currentDescription = string.Empty;
            var                      choosenWeather     = string.Empty;
            Dictionary <int, string> _storedWeather     = new Dictionary <int, string>();

            // Here we got the selected daysrange we have choosen by the slider in the frontend.
            int timespan = FormatFunction.GetTimespan(daysrange);

            //  Here we get the weather of the forecast list from the json object and store it in a dictionary                                                                    */
            if (forecast != null)
            {
                for (var i = 0; i < timespan; i++)
                {
                    if (forecast.list[i].weather[0].Main == WeatherType.Snow.ToString())
                    {
                        var key = i;
                        currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                        choosenWeather = currentWeather;
                        GetCurrentWorstWeather(key, worstweather, forecast);
                    }
                    else
                    {
                        if (forecast.list[i].weather[0].Main == WeatherType.Clear.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }

                        if (forecast.list[i].weather[0].Main == WeatherType.Clouds.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }

                        if (forecast.list[i].weather[0].Main == WeatherType.Fog.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }

                        if (forecast.list[i].weather[0].Main == WeatherType.Drizzle.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }

                        if (forecast.list[i].weather[0].Main == WeatherType.Rain.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }

                        if (forecast.list[i].weather[0].Main == WeatherType.Thunderstorm.ToString())
                        {
                            currentWeather = string.Format("{0}", forecast.list[i].weather[0].Main);
                            _storedWeather.Add(i, currentWeather);
                        }
                    }
                }

                // If thunderstorm is the worst weather in the forecast
                if (choosenWeather != WeatherType.Snow.ToString())
                {
                    // Here we got the first thunderstorm in the forecast
                    var firstthunderstorm = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Thunderstorm.ToString());
                    if (firstthunderstorm.Value != null)
                    {
                        foreach (var item in _storedWeather)
                        {
                            // Here we will got the matching item to the first thunderstorm object in the forecast
                            if (item.Value == firstthunderstorm.Value)
                            {
                                // Now we set a value of choosenWeather
                                choosenWeather = WeatherType.Thunderstorm.ToString();
                                var key = item.Key;
                                // Here we sets the values to the returning object worstweather
                                GetCurrentWorstWeather(key, worstweather, forecast);
                                break;
                            }
                        }
                    }
                }

                // If rain is the worst weather in the forecast
                if (choosenWeather != WeatherType.Snow.ToString())
                {
                    if (choosenWeather != WeatherType.Thunderstorm.ToString())
                    {
                        var firstrain = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Rain.ToString());

                        if (firstrain.Value != null)
                        {
                            foreach (var item in _storedWeather)
                            {
                                if (item.Value == firstrain.Value)
                                {
                                    choosenWeather = WeatherType.Rain.ToString();
                                    var key = item.Key;
                                    GetCurrentWorstWeather(key, worstweather, forecast);
                                    break;
                                }
                            }
                        }
                    }
                }


                if (choosenWeather != WeatherType.Snow.ToString())
                {
                    if (choosenWeather != WeatherType.Thunderstorm.ToString())
                    {
                        if (choosenWeather != WeatherType.Rain.ToString())
                        {
                            // If Drizzle is the worst weather in the forecast
                            var firstDrizzle = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Drizzle.ToString());

                            if (firstDrizzle.Value != null)
                            {
                                foreach (var item in _storedWeather)
                                {
                                    if (item.Value == firstDrizzle.Value)
                                    {
                                        choosenWeather = WeatherType.Drizzle.ToString();
                                        var key = item.Key;
                                        GetCurrentWorstWeather(key, worstweather, forecast);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                if (choosenWeather != WeatherType.Snow.ToString())
                {
                    if (choosenWeather != WeatherType.Thunderstorm.ToString())
                    {
                        if (choosenWeather != WeatherType.Rain.ToString())
                        {
                            if (choosenWeather != WeatherType.Drizzle.ToString())
                            {
                                // If fog is the worst weather at the forecast
                                var firstFog = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Fog.ToString());

                                if (firstFog.Value != null)
                                {
                                    foreach (var item in _storedWeather)
                                    {
                                        if (item.Value == firstFog.Value)
                                        {
                                            choosenWeather = WeatherType.Fog.ToString();
                                            var key = item.Key;
                                            GetCurrentWorstWeather(key, worstweather, forecast);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (choosenWeather != WeatherType.Snow.ToString())
                {
                    if (choosenWeather != WeatherType.Thunderstorm.ToString())
                    {
                        if (choosenWeather != WeatherType.Rain.ToString())
                        {
                            if (choosenWeather != WeatherType.Drizzle.ToString())
                            {
                                if (choosenWeather != WeatherType.Fog.ToString())
                                {
                                    // If it is clouds as the worst weather at the forecast
                                    var firstcloud = _storedWeather.FirstOrDefault(x => x.Value == WeatherType.Clouds.ToString());

                                    foreach (var item in _storedWeather)
                                    {
                                        if (item.Value == firstcloud.Value)
                                        {
                                            choosenWeather = WeatherType.Clouds.ToString();
                                            var key = item.Key;
                                            GetCurrentWorstWeather(key, worstweather, forecast);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(worstweather);
        }
Ejemplo n.º 9
0
        public ForecastResult Forecast(DateTime forecastDate)
        {
            int year = forecastDate.Year;

            State[]                states     = GetStates().ToArray();
            Poll[]                 polls      = GetPolls(forecastDate).ToArray();
            Candidate[]            candidates = GetCandidates(year).ToArray();
            StateElectionHistory[] history    = GetElectionHistory().ToArray();

            (decimal partisanSwing, string currentPartisanship) =
                GenerateSwing(forecastDate, GetElectionDate(forecastDate));

            Dictionary <string, int> votes = candidates.ToDictionary(candidate => candidate.Name, candidate => 0);

            var finalResult = new ForecastResult();

            foreach (State state in states)
            {
                StateElectionHistory stateHistory = history.FirstOrDefault(h => h.State == state.Name);
                if (stateHistory != null)
                {
                    IEnumerable <StateElectionHistory.Election> elections =
                        stateHistory.Elections.Where(e => e.Year < year).ToArray();

                    var stateLean = new Dictionary <string, decimal>();
                    foreach (Candidate candidate in candidates)
                    {
                        decimal runningTotal = 0;
                        decimal totalWeight  = 0;
                        foreach (StateElectionHistory.Election election in elections)
                        {
                            var weight = (decimal)System.Math.Pow(10.0 / (year - election.Year), 2);
                            totalWeight  += weight;
                            runningTotal +=
                                (election.Results.FirstOrDefault(r => r.Party == candidate.Party)?.Pct ?? 0) * weight;
                        }

                        Poll[] statePolls = polls.Where(p => p.State == state.Name).ToArray();
                        if (statePolls.Any())
                        {
                            foreach (Poll poll in statePolls)
                            {
                                (decimal result, decimal weight) = GetGuassian(poll, candidate.Name, forecastDate);
                                runningTotal += result;
                                totalWeight  += weight;
                            }
                        }

                        decimal endPct = runningTotal / totalWeight;
                        endPct += currentPartisanship == candidate.Party ? partisanSwing : -partisanSwing;

                        stateLean.Add(candidate.Party, endPct);
                    }

                    string    winningParty = stateLean.FirstOrDefault(l => l.Value == stateLean.Values.Max()).Key;
                    Candidate winner       = candidates.FirstOrDefault(c => c.Party == winningParty);
                    if (winner != null)
                    {
                        votes[winner.Name] += state.EcVotes;

                        finalResult.Results.Add(new CandidateResult
                        {
                            State      = state.Name,
                            Candidate  = winner.Name,
                            WinPercent = 100
                        });
                    }
                }
            }

            finalResult.Results.Add(new CandidateResult
            {
                State      = "",
                Candidate  = votes.FirstOrDefault(v => v.Value == votes.Values.Max()).Key,
                WinPercent = 100
            });

            return(finalResult);
        }
Ejemplo n.º 10
0
 private static void ShowForecast(ForecastResult result)
 {
     Console.WriteLine($"Date: {result.Date} Temperature: {result.TemperatureC} Summary: {result.Summary} Golfable? {(result.CanYouPlayGolf ? "Yes" : "No")}");
 }