예제 #1
0
        public void StoreAmazonFeedbackData(IDatabaseCustomerMarketPlace databaseCustomerMarketPlace, DatabaseAmazonFeedbackData data, MP_CustomerMarketplaceUpdatingHistory historyRecord)
        {
            if (data == null)
            {
                WriteToLog("StoreAmazonUserData: invalid data to store", WriteLogType.Error);
                return;
            }

            MP_CustomerMarketPlace customerMarketPlace = GetCustomerMarketPlace(databaseCustomerMarketPlace.Id);

            var feedBack = new MP_AmazonFeedback {
                CustomerMarketPlace = customerMarketPlace,
                Created             = data.Submitted,
                UserRaining         = data.UserRaining,
                HistoryRecord       = historyRecord
            };

            if (data.FeedbackByPeriod != null && data.FeedbackByPeriod.Count > 0)
            {
                feedBack.FeedbackByPeriodItems.AddAll(data.FeedbackByPeriod.Values.Select(f => new MP_AmazonFeedbackItem {
                    AmazonFeedback = feedBack,
                    Count          = f.Count,
                    Negative       = f.Negative,
                    Positive       = f.Positive,
                    Neutral        = f.Neutral,
                    TimePeriod     = GetTimePeriod(TimePeriodFactory.Create(f.TimePeriod))
                }).ToList());
            }

            customerMarketPlace.AmazonFeedback.Add(feedBack);

            _CustomerMarketplaceRepository.Update(customerMarketPlace);
        }
예제 #2
0
        private static TreeStorageValuationResults <T> TrinomialStorageValuation <T>(
            DateTime valuationDateTime,
            DateTime storageStartDateTime,
            DateTime storageEndDateTime,
            object ratchets,
            string injectWithdrawInterpolation,
            double injectionCostRate,
            double cmdtyConsumedOnInjection,
            double withdrawalCostRate,
            double cmdtyConsumedOnWithdrawal,
            double currentInventory,
            object forwardCurveIn,
            object spotVolatilityCurveIn,
            double meanReversion,
            object interestRateCurve,
            object numGlobalGridPointsIn,
            object numericalToleranceIn)
            where T : ITimePeriod <T>
        {
            double numericalTolerance = StorageExcelHelper.DefaultIfExcelEmptyOrMissing(numericalToleranceIn, 1E-10,
                                                                                        "Numerical_tolerance");

            var storage = StorageExcelHelper.CreateCmdtyStorageFromExcelInputs <T>(storageStartDateTime,
                                                                                   storageEndDateTime, ratchets, injectWithdrawInterpolation, injectionCostRate, cmdtyConsumedOnInjection,
                                                                                   withdrawalCostRate, cmdtyConsumedOnWithdrawal, numericalTolerance);

            T currentPeriod = TimePeriodFactory.FromDateTime <T>(valuationDateTime);

            TimeSeries <T, double> forwardCurve        = StorageExcelHelper.CreateDoubleTimeSeries <T>(forwardCurveIn, "Forward_curve");
            TimeSeries <T, double> spotVolatilityCurve = StorageExcelHelper.CreateDoubleTimeSeries <T>(spotVolatilityCurveIn, "Spot_volatility_curve");

            // TODO input settlement dates
            int numGridPoints =
                StorageExcelHelper.DefaultIfExcelEmptyOrMissing <int>(numGlobalGridPointsIn, 100, "Num_global_grid_points");

            double timeDelta = 1.0 / 365.0; // TODO remove this hard coding

            Func <Day, double> interpolatedInterestRates =
                StorageExcelHelper.CreateLinearInterpolatedInterestRateFunc(interestRateCurve, ExcelArg.InterestRateCurve.Name);

            TreeStorageValuationResults <T> valuationResults = TreeStorageValuation <T>
                                                               .ForStorage(storage)
                                                               .WithStartingInventory(currentInventory)
                                                               .ForCurrentPeriod(currentPeriod)
                                                               .WithForwardCurve(forwardCurve)
                                                               .WithOneFactorTrinomialTree(spotVolatilityCurve, meanReversion, timeDelta)
                                                               .WithCmdtySettlementRule(period => period.First <Day>()) // TODO get rid if this
                                                               .WithAct365ContinuouslyCompoundedInterestRate(interpolatedInterestRates)
                                                               .WithFixedNumberOfPointsOnGlobalInventoryRange(numGridPoints)
                                                               .WithLinearInventorySpaceInterpolation()
                                                               .WithNumericalTolerance(numericalTolerance)
                                                               .Calculate();

            return(valuationResults);
        }
예제 #3
0
        public void StoreEbayFeedbackData(IDatabaseCustomerMarketPlace databaseCustomerMarketPlace, DatabaseEbayFeedbackData data, MP_CustomerMarketplaceUpdatingHistory historyRecord)
        {
            if (data == null)
            {
                WriteToLog("StoreEbayUserData: invalid data to store", WriteLogType.Error);
                return;
            }

            MP_CustomerMarketPlace customerMarketPlace = GetCustomerMarketPlace(databaseCustomerMarketPlace.Id);

            var feedBack = new MP_EbayFeedback
            {
                CustomerMarketPlace = customerMarketPlace,
                Created             = data.Submitted,
                RepeatBuyerCount    = data.RepeatBuyerCount,
                RepeatBuyerPercent  = data.RepeatBuyerPercent,
                TransactionPercent  = data.TransactionPercent,
                UniqueBuyerCount    = data.UniqueBuyerCount,
                UniqueNegativeCount = data.UniqueNegativeCount,
                UniqueNeutralCount  = data.UniqueNeutralCount,
                UniquePositiveCount = data.UniquePositiveCount,
                HistoryRecord       = historyRecord
            };

            if (data.FeedbackByPeriod != null && data.FeedbackByPeriod.Count > 0)
            {
                feedBack.FeedbackByPeriodItems.AddAll(data.FeedbackByPeriod.Values.Select(f => new MP_EbayFeedbackItem
                {
                    EbayFeedback = feedBack,
                    Negative     = f.Negative,
                    Positive     = f.Positive,
                    Neutral      = f.Neutral,
                    TimePeriod   = GetTimePeriod(TimePeriodFactory.Create(f.TimePeriod))
                }).ToList());
            }

            if (data.RaitingByPeriod != null && data.RaitingByPeriod.Count > 0)
            {
                feedBack.RaitingByPeriodItems.AddAll(data.RaitingByPeriod.Values.Select(r => new MP_EbayRaitingItem
                {
                    EbayFeedback               = feedBack,
                    Communication              = r.Communication,
                    ItemAsDescribed            = r.ItemAsDescribed,
                    ShippingAndHandlingCharges = r.ShippingAndHandlingCharges,
                    ShippingTime               = r.ShippingTime,
                    TimePeriod = GetTimePeriod(TimePeriodFactory.Create(r.TimePeriod))
                }).ToList());
            }

            customerMarketPlace.EbayFeedback.Add(feedBack);

            _CustomerMarketplaceRepository.Update(customerMarketPlace);
        }
예제 #4
0
        protected IEnumerable <IAnalysisDataParameterInfo> GetFeedbacks(MP_CustomerMarketPlace mp, DateTime?history)
        {
            MP_AmazonFeedback feedbacks;

            if (history == null)
            {
                feedbacks = mp.AmazonFeedback
                            .OrderByDescending(x => x.Created)
                            .FirstOrDefault();
            }
            else
            {
                feedbacks = mp.AmazonFeedback
                            .Where(x => x.Created <= history)
                            .OrderByDescending(x => x.Created)
                            .FirstOrDefault();
            }            //if

            var feedBackParams = new List <IAnalysisDataParameterInfo>();

            if (feedbacks == null)
            {
                return(feedBackParams);
            }

            feedBackParams.Add(new AnalysisDataParameterInfo(TimePeriodFactory.Create(TimePeriodEnum.Zero), feedbacks.UserRaining, AggregationFunction.UserRating));

            foreach (MP_AmazonFeedbackItem afp in feedbacks.FeedbackByPeriodItems)
            {
                var timePeriod = TimePeriodFactory.CreateById(afp.TimePeriod.InternalId);

                var c = new AnalysisDataParameterInfo(timePeriod, afp.Count, AggregationFunction.NumberOfReviews);
                var g = new AnalysisDataParameterInfo(timePeriod, afp.Negative, AggregationFunction.NegativeFeedbackRate);
                var n = new AnalysisDataParameterInfo(timePeriod, afp.Neutral, AggregationFunction.NeutralFeedbackRate);
                var p = new AnalysisDataParameterInfo(timePeriod, afp.Positive, AggregationFunction.PositiveFeedbackRate);

                var     sum             = afp.Positive + afp.Neutral + afp.Negative;
                decimal positivePercent = sum != 0 ? ((afp.Positive ?? 0)) / (decimal)sum.Value : 0M;
                decimal neutralPercent  = sum != 0 ? ((afp.Neutral ?? 0)) / (decimal)sum.Value : 0M;
                decimal negativePercent = sum != 0 ? ((afp.Negative ?? 0)) / (decimal)sum.Value : 0M;
                var     pp = new AnalysisDataParameterInfo(timePeriod, positivePercent, AggregationFunction.PositiveFeedbackPercentRate);
                var     np = new AnalysisDataParameterInfo(timePeriod, neutralPercent, AggregationFunction.NeutralFeedbackPercentRate);
                var     gp = new AnalysisDataParameterInfo(timePeriod, negativePercent, AggregationFunction.NegativeFeedbackPercentRate);

                feedBackParams.AddRange(new[] { c, n, g, p, pp, np, gp });
            }             // for each

            return(feedBackParams);
        } // GetFeedbacks
예제 #5
0
        private static IntrinsicStorageValuationResults <T> IntrinsicStorageVal <T>(
            DateTime valuationDateTime,
            DateTime storageStartDateTime,
            DateTime storageEndDateTime,
            object injectWithdrawConstraints,
            string injectWithdrawInterpolation,
            double injectionCostRate,
            double cmdtyConsumedOnInjection,
            double withdrawalCostRate,
            double cmdtyConsumedOnWithdrawal,
            double currentInventory,
            object forwardCurveIn,
            object interestRateCurve,
            object numGlobalGridPointsIn,
            object numericalToleranceIn)
            where T : ITimePeriod <T>
        {
            double numericalTolerance = StorageExcelHelper.DefaultIfExcelEmptyOrMissing(numericalToleranceIn, 1E-10,
                                                                                        "Numerical_tolerance");

            var storage = StorageExcelHelper.CreateCmdtyStorageFromExcelInputs <T>(storageStartDateTime,
                                                                                   storageEndDateTime, injectWithdrawConstraints, injectWithdrawInterpolation, injectionCostRate, cmdtyConsumedOnInjection,
                                                                                   withdrawalCostRate, cmdtyConsumedOnWithdrawal, numericalTolerance);

            T currentPeriod = TimePeriodFactory.FromDateTime <T>(valuationDateTime);

            TimeSeries <T, double> forwardCurve = StorageExcelHelper.CreateDoubleTimeSeries <T>(forwardCurveIn, "Forward_curve");

            // TODO input settlement dates and use interest rates
            int numGridPoints =
                StorageExcelHelper.DefaultIfExcelEmptyOrMissing <int>(numGlobalGridPointsIn, 100, "Num_global_grid_points");

            IntrinsicStorageValuationResults <T> valuationResults = IntrinsicStorageValuation <T>
                                                                    .ForStorage(storage)
                                                                    .WithStartingInventory(currentInventory)
                                                                    .ForCurrentPeriod(currentPeriod)
                                                                    .WithForwardCurve(forwardCurve)
                                                                    .WithCmdtySettlementRule(period => period.First <Day>())    // TODO get rid if this
                                                                    .WithDiscountFactorFunc((currentDate, cashFlowDate) => 1.0) // TODO add proper discounting
                                                                    .WithFixedNumberOfPointsOnGlobalInventoryRange(numGridPoints)
                                                                    .WithLinearInventorySpaceInterpolation()
                                                                    .WithNumericalTolerance(numericalTolerance)
                                                                    .Calculate();

            return(valuationResults);
        }
예제 #6
0
        public override IEnumerable <IAnalysisDataParameterInfo> GetAggregations(MP_CustomerMarketPlace mp, DateTime?history)
        {
            DateTime relevantDate = GetRelevantDate(history);

            List <EkmAggregation> aggregations = Library.Instance.DB.Fill <EkmAggregation>(
                "LoadActiveEkmAggregations",
                CommandSpecies.StoredProcedure,
                new QueryParameter("MpID", mp.Id),
                new QueryParameter("RelevantDate", relevantDate)
                );

            var calculatedAggregations = new List <IAnalysisDataParameterInfo>();

            if (!aggregations.Any())
            {
                return(calculatedAggregations);
            }

            if (history.HasValue)
            {
                aggregations = aggregations.Where(x => x.TheMonth < history).ToList();
            }

            DateTime firstOfMonth = new DateTime(relevantDate.Year, relevantDate.Month, 1);

            var month   = TimePeriodFactory.Create(TimePeriodEnum.Month);
            var month3  = TimePeriodFactory.Create(TimePeriodEnum.Month3);
            var month6  = TimePeriodFactory.Create(TimePeriodEnum.Month6);
            var year    = TimePeriodFactory.Create(TimePeriodEnum.Year);
            var month15 = TimePeriodFactory.Create(TimePeriodEnum.Month15);
            var month18 = TimePeriodFactory.Create(TimePeriodEnum.Month18);
            var year2   = TimePeriodFactory.Create(TimePeriodEnum.Year2);
            var all     = TimePeriodFactory.Create(TimePeriodEnum.Lifetime);

            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, month, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, month3, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, month6, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, year, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, month15, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, month18, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, year2, firstOfMonth));
            calculatedAggregations.AddRange(GetAnalysisDataParameters(aggregations, all, firstOfMonth));
            return(calculatedAggregations);
        }        //GetAggregations
예제 #7
0
        public static TimeSeries <TIndex, TData> CreateTimeSeries <TIndex, TData>(object excelValues, string excelArgumentName,
                                                                                  TryCreateData <TData> tryCreateData)
            where TIndex : ITimePeriod <TIndex>
        {
            if (excelValues is ExcelMissing || excelValues is ExcelEmpty)
            {
                throw new ArgumentException(excelArgumentName + " hasn't been specified.");
            }

            if (!(excelValues is object[,] excelValuesArray))
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be of a range with 2 columns, the first containing dates, the second containing numbers.");
            }

            if (excelValuesArray.GetLength(1) != 2)
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be a range with 2 columns.");
            }

            var builder = new TimeSeries <TIndex, TData> .Builder();

            for (int i = 0; i < excelValuesArray.GetLength(0); i++)
            {
                if (excelValuesArray[i, 0] is ExcelEmpty || excelValuesArray[i, 0] is ExcelError)
                {
                    break;
                }

                object dataValueIn = excelValuesArray[i, 1];
                if (!tryCreateData(dataValueIn, out TData dataValue))
                {
                    throw new ArgumentException($"Value in the second column of row {i} for argument {excelArgumentName} cannot be converted to type {typeof(TData).Name}.");
                }

                DateTime curvePointDateTime = ObjectToDateTime(excelValuesArray[i, 0], $"Cannot create DateTime from value in first row of argument {excelArgumentName}.");
                TIndex   curvePointPeriod   = TimePeriodFactory.FromDateTime <TIndex>(curvePointDateTime);

                builder.Add(curvePointPeriod, dataValue);
            }

            return(builder.Build());
        }
예제 #8
0
        }         // AppendAggregations

        private void AppendFeedbacks(
            List <IAnalysisDataParameterInfo> target,
            MP_CustomerMarketPlace mp,
            DateTime?history
            )
        {
            MP_EbayFeedback feedbacks;

            if (history == null)
            {
                feedbacks = mp.EbayFeedback.OrderByDescending(x => x.Created).FirstOrDefault();
            }
            else
            {
                feedbacks = mp.EbayFeedback
                            .Where(x => x.Created <= history)
                            .OrderByDescending(x => x.Created)
                            .FirstOrDefault();
            }             // if

            if (feedbacks == null)
            {
                return;
            }

            feedbacks.FeedbackByPeriodItems.ForEach(afp => {
                ITimePeriod timePeriod = TimePeriodFactory.CreateById(afp.TimePeriod.InternalId);

                int sum = (afp.Positive ?? 0) + (afp.Neutral ?? 0) + (afp.Negative ?? 0);

                AddAnalysisItem(target, timePeriod, AggregationFunction.NumberOfReviews, sum);

                AddAnalysisItem(target, timePeriod, AggregationFunction.NegativeFeedbackRate, afp.Negative ?? 0);
                AddAnalysisItem(target, timePeriod, AggregationFunction.NeutralFeedbackRate, afp.Neutral ?? 0);
                AddAnalysisItem(target, timePeriod, AggregationFunction.PositiveFeedbackRate, afp.Positive ?? 0);

                AddAnalysisItem(target, timePeriod, AggregationFunction.PositiveFeedbackPercentRate, afp.Positive ?? 0, sum);
                AddAnalysisItem(target, timePeriod, AggregationFunction.NeutralFeedbackPercentRate, afp.Neutral ?? 0, sum);
                AddAnalysisItem(target, timePeriod, AggregationFunction.NegativeFeedbackPercentRate, afp.Negative ?? 0, sum);
            });
        }         // AppendFeedbacks
예제 #9
0
        public static DoubleTimeSeries <T> CreateDoubleTimeSeries <T>(object excelValues, string excelArgumentName)
            where T : ITimePeriod <T>
        {
            if (excelValues is ExcelMissing || excelValues is ExcelEmpty)
            {
                throw new ArgumentException(excelArgumentName + " hasn't been specified.");
            }

            if (!(excelValues is object[,] excelValuesArray))
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be of a range with 2 columns, the first containing dates, the second containing numbers.");
            }

            if (excelValuesArray.GetLength(1) != 2)
            {
                throw new ArgumentException(excelArgumentName + " has been incorrectly entered. Argument value should be a range with 2 columns.");
            }

            var builder = new DoubleTimeSeries <T> .Builder();

            for (int i = 0; i < excelValuesArray.GetLength(0); i++)
            {
                if (excelValuesArray[i, 0] is ExcelEmpty || excelValuesArray[i, 0] is ExcelError)
                {
                    break;
                }

                if (!(excelValuesArray[i, 1] is double doubleValue))
                {
                    throw new ArgumentException($"Value in the second column of row {i} for argument {excelArgumentName} is not a number.");
                }

                DateTime curvePointDateTime = ObjectToDateTime(excelValuesArray[i, 0], $"Cannot create DateTime from value in first row of argument {excelArgumentName}.");
                T        curvePointPeriod   = TimePeriodFactory.FromDateTime <T>(curvePointDateTime);

                builder.Add(curvePointPeriod, doubleValue);
            }

            return(builder.Build());
        }
예제 #10
0
        private int GetFeedbackByPeriod(FeedbackPeriodType[] feedbackPeriodType, TimePeriodEnum period)
        {
            if (feedbackPeriodType == null || feedbackPeriodType.Length == 0)
            {
                return(0);
            }

            var tp = TimePeriodFactory.Create(period);

            int days = tp.DaysInPeriod;

            FeedbackPeriodType rez = feedbackPeriodType.FirstOrDefault(p => p.PeriodInDays == days);

            Debug.Assert(rez != null);

            if (rez == null)
            {
                return(0);
            }

            return(rez.Count);
        }
예제 #11
0
        }                                                            // UWPriority

        public override IEnumerable <IAnalysisDataParameterInfo> GetAggregations(MP_CustomerMarketPlace mp, DateTime?history)
        {
            DateTime relevantDate = GetRelevantDate(history);
            DateTime firstOfMonth = new DateTime(relevantDate.Year, relevantDate.Month, 1);

            var month   = TimePeriodFactory.Create(TimePeriodEnum.Month);
            var month3  = TimePeriodFactory.Create(TimePeriodEnum.Month3);
            var month6  = TimePeriodFactory.Create(TimePeriodEnum.Month6);
            var year    = TimePeriodFactory.Create(TimePeriodEnum.Year);
            var month15 = TimePeriodFactory.Create(TimePeriodEnum.Month15);
            var month18 = TimePeriodFactory.Create(TimePeriodEnum.Month18);
            var year2   = TimePeriodFactory.Create(TimePeriodEnum.Year2);
            var all     = TimePeriodFactory.Create(TimePeriodEnum.Lifetime);

            var calculatedAggregations = new List <IAnalysisDataParameterInfo>();

            if (InternalId == new Guid("AE85D6FC-DBDB-4E01-839A-D5BD055CBAEA"))
            {
                List <HmrcAggregation> aggregations = Library.Instance.DB.Fill <HmrcAggregation>(
                    "LoadActiveHmrcAggregations",
                    CommandSpecies.StoredProcedure,
                    new QueryParameter("MpID", mp.Id),
                    new QueryParameter("RelevantDate", relevantDate)
                    );

                if (!aggregations.Any())
                {
                    return(calculatedAggregations);
                }

                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, month, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, month3, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, month6, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, year, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, month15, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, month18, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, year2, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersHmrc(aggregations, all, firstOfMonth));
            }
            else
            {
                List <ChannelGrabberAggregation> aggregations = Library.Instance.DB.Fill <ChannelGrabberAggregation>(
                    "LoadActiveChanngelGrabberAggregations",
                    CommandSpecies.StoredProcedure,
                    new QueryParameter("MpID", mp.Id),
                    new QueryParameter("RelevantDate", relevantDate)
                    );

                if (!aggregations.Any())
                {
                    return(calculatedAggregations);
                }

                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, month, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, month3, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, month6, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, year, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, month15, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, month18, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, year2, firstOfMonth));
                calculatedAggregations.AddRange(GetAnalysisDataParametersCG(aggregations, all, firstOfMonth));
            }

            return(calculatedAggregations);
        }        //GetAggregations
예제 #12
0
        }         // GetAggregations

        private void AppendAggregations(
            List <IAnalysisDataParameterInfo> target,
            List <EbayAggregation> ag,
            TimePeriodEnum timePeriod,
            DateTime firstOfMonth
            )
        {
            ITimePeriod time = TimePeriodFactory.Create(timePeriod);

            if (time.TimePeriodType != TimePeriodEnum.Lifetime)
            {
                ag = ag.Where(x => x.TheMonth > firstOfMonth.AddMonths(-time.MonthsInPeriod)).ToList();
            }

            var parameterInfos = new List <IAnalysisDataParameterInfo>();

            AddAnalysisItem(parameterInfos, time, AggregationFunction.Turnover, ag.Sum(x => x.Turnover));

            AddAnalysisItem(
                parameterInfos,
                time,
                AggregationFunction.AverageSumOfOrder,
                ag.Sum(x => x.AverageSumOfOrderNumerator),
                ag.Sum(x => x.AverageSumOfOrderDenominator)
                );

            AddAnalysisItem(
                parameterInfos,
                time,
                AggregationFunction.AverageItemsPerOrder,
                ag.Sum(x => x.AverageItemsPerOrderNumerator),
                ag.Sum(x => x.AverageItemsPerOrderDenominator)
                );

            AddAnalysisItem(
                parameterInfos,
                time,
                AggregationFunction.CancelledOrdersCount,
                ag.Sum(x => x.CancelledOrdersCount)
                );

            AddAnalysisItem(parameterInfos, time, AggregationFunction.NumOfOrders, ag.Sum(x => x.NumOfOrders));

            AddAnalysisItem(
                parameterInfos,
                time,
                AggregationFunction.OrdersCancellationRate,
                ag.Sum(x => x.OrdersCancellationRateNumerator),
                ag.Sum(x => x.OrdersCancellationRateDenominator)
                );

            AddAnalysisItem(parameterInfos, time, AggregationFunction.TotalItemsOrdered, ag.Sum(x => x.TotalItemsOrdered));

            AddAnalysisItem(parameterInfos, time, AggregationFunction.TotalSumOfOrders, ag.Sum(x => x.TotalSumOfOrders));

            if (time.MonthsInPeriod <= MonthsInYear)
            {
                AddAnalysisItem(
                    parameterInfos,
                    time,
                    AggregationFunction.TotalSumOfOrdersAnnualized,
                    ag.Sum(x => x.TotalSumOfOrders) * (MonthsInYear / (decimal)time.MonthsInPeriod)
                    );
            }             // if

            target.AddRange(parameterInfos);
        }         // AppendAggregations
예제 #13
0
        public static CmdtyStorage <T> CreateCmdtyStorageFromExcelInputs <T>(DateTime storageStartDateTime,
                                                                             DateTime storageEndDateTime,
                                                                             object injectWithdrawConstraintsIn,
                                                                             string injectWithdrawInterpolationIn,
                                                                             double injectionCostRate,
                                                                             double cmdtyConsumedOnInjection,
                                                                             double withdrawalCostRate,
                                                                             double cmdtyConsumedOnWithdrawal,
                                                                             double newtonRaphsonAccuracy)
            where T : ITimePeriod <T>
        {
            T storageStart = TimePeriodFactory.FromDateTime <T>(storageStartDateTime);
            T storageEnd   = TimePeriodFactory.FromDateTime <T>(storageEndDateTime);

            if (injectWithdrawConstraintsIn is ExcelMissing || injectWithdrawConstraintsIn is ExcelEmpty)
            {
                throw new ArgumentException("Inject/withdraw constraints haven't been specified.");
            }

            if (!(injectWithdrawConstraintsIn is object[,] injectWithdrawArray))
            {
                throw new ArgumentException("Inject/withdraw constraints have been incorrectly entered. Argument value should be of a range with 4 columns, the first containing dates, the rest containing numbers.");
            }

            if (injectWithdrawArray.GetLength(1) != 4)
            {
                throw new ArgumentException("Inject/withdraw constraints have been incorrectly entered. Argument value should be a range 4 columns.");
            }

            var injectWithdrawGrouped = TakeWhileNotEmptyOrError(injectWithdrawArray).Select((row, i) => new
            {
                period       = ObjectToDateTime(row[0], $"Row {i + 1} of inject/withdraw/inventory constrains contains invalid date time in 1st column."),
                inventory    = ObjectToDouble(row[1], $"Row {i + 1} of inject/withdraw/inventory constraints contains invalid inventory in 2nd column as is not a number."),
                injectRate   = ObjectToDouble(row[2], $"Row {i + 1} of inject/withdraw/inventory constraints contains invalid injection rate in 3rd column as is not a number."),
                withdrawRate = ObjectToDouble(row[3], $"Row {i + 1} of inject/withdraw/inventory constraints contains invalid withdrawal in 4th column as is not a number.")
            }).GroupBy(arg => arg.period);

            var injectWithdrawConstraints = new List <InjectWithdrawRangeByInventoryAndPeriod <T> >();

            foreach (var injectWithdrawGroup in injectWithdrawGrouped)
            {
                T period = TimePeriodFactory.FromDateTime <T>(injectWithdrawGroup.Key);
                IEnumerable <InjectWithdrawRangeByInventory> injectWithdrawByInventory = injectWithdrawGroup.Select(arg =>
                                                                                                                    new InjectWithdrawRangeByInventory(arg.inventory, new InjectWithdrawRange(-arg.withdrawRate, arg.injectRate)));
                injectWithdrawConstraints.Add(new InjectWithdrawRangeByInventoryAndPeriod <T>(period, injectWithdrawByInventory));
            }

            InterpolationType interpolationType;

            if (injectWithdrawInterpolationIn == "PiecewiseLinear")
            {
                interpolationType = InterpolationType.PiecewiseLinear;
            }
            else if (injectWithdrawInterpolationIn == "Polynomial")
            {
                interpolationType = InterpolationType.PolynomialWithParams(newtonRaphsonAccuracy);
            }
            else
            {
                throw new ArgumentException($"Value of Inject_withdraw_interpolation '{injectWithdrawInterpolationIn}' not recognised. Must be either 'PiecewiseLinear' or 'Polynomial'.");
            }

            CmdtyStorage <T> storage = CmdtyStorage <T> .Builder
                                       .WithActiveTimePeriod(storageStart, storageEnd)
                                       .WithTimeAndInventoryVaryingInjectWithdrawRates(injectWithdrawConstraints, interpolationType)
                                       .WithPerUnitInjectionCost(injectionCostRate)
                                       .WithFixedPercentCmdtyConsumedOnInject(cmdtyConsumedOnInjection)
                                       .WithPerUnitWithdrawalCost(withdrawalCostRate)
                                       .WithFixedPercentCmdtyConsumedOnWithdraw(cmdtyConsumedOnWithdrawal)
                                       .WithNoCmdtyInventoryLoss()
                                       .WithNoInventoryCost()
                                       .MustBeEmptyAtEnd()
                                       .Build();

            return(storage);
        }
        public void FromDateTime_MonthTypeParameter_EqualsExpected(DateTime dateTime, Month expectedMonth)
        {
            var month = TimePeriodFactory.FromDateTime <Month>(dateTime);

            Assert.AreEqual(expectedMonth, month);
        }