示例#1
0
        public MonthlySummary CalculateMonthlySummary(DateTime?month)
        {
            var selectedMonth = month ?? DateTime.UtcNow;

            var summary = new MonthlySummary()
            {
                AllExpenses = GetMonthlyExpenses(selectedMonth),
                AllIncomes  = GetMonthlyIncomes(selectedMonth)
            };

            return(summary);
        }
        public void TotalKwh_Should_Return_CorrentValue(decimal startValue, decimal endValue, decimal expected)
        {
            // arrange
            var monthlySummary = new MonthlySummary
            {
                KwhUsageAtMonthStart = startValue,
                KwhUsageAtMonthEnd   = endValue
            };

            // act
            var result = monthlySummary.TotalKwh();

            // assert
            Assert.Equal(expected, result);
        }
示例#3
0
        /// <summary>
        /// Calculate the Average open and close price for each symbols
        /// </summary>
        /// <param name="tickerData">Daily Data grouped by its ticker</param>
        /// <returns>Monthly Average Result</returns>
        public static string CalculateMonthlyAverage(IDictionary <string, IList <DailySummary> > tickerData)
        {
            //Create Monthly summary list for each ticker
            var tickerMonthlyAverageData = new Dictionary <string, List <MonthlySummary> >();

            foreach (KeyValuePair <string, IList <DailySummary> > item in tickerData)
            {
                var monthlySummaryData = new Dictionary <string, MonthlySummary>();
                foreach (var data in item.Value)
                {
                    string yearMonth = data.Date.ToString("yyyy-MM");
                    if (monthlySummaryData.ContainsKey(yearMonth))
                    {
                        monthlySummaryData[yearMonth].OpenSum  += data.Open;
                        monthlySummaryData[yearMonth].CloseSum += data.Close;
                        monthlySummaryData[yearMonth].Count    += 1;
                    }
                    else
                    {
                        monthlySummaryData[yearMonth] = new MonthlySummary
                        {
                            month    = yearMonth,
                            OpenSum  = data.Open,
                            CloseSum = data.Close,
                            Count    = 1
                        };
                    }
                }

                // now display //ticker - year-month - avgOpen -- avgClose
                foreach (var monthData in monthlySummaryData)
                {
                    if (tickerMonthlyAverageData.ContainsKey(item.Key))
                    {
                        tickerMonthlyAverageData[item.Key].Add(monthData.Value);
                    }
                    else
                    {
                        tickerMonthlyAverageData[item.Key] = new List <MonthlySummary> {
                            monthData.Value
                        };
                    }
                }
            }
            //Return Readable/formatted json
            return(JsonConvert.SerializeObject(tickerMonthlyAverageData, Formatting.Indented));
        }
        /// <summary>
        /// Attempts to calculate the avarage month from a list of monthly summaries with total amounts.
        /// Calculates the average month as the average total income and average total expenses in all months.
        /// </summary>
        /// <param name="monthSummaries">The list of monthly summaries with total amounts.</param>
        /// <param name="averageMonth">Returns the average month.</param>
        /// <returns>true if it was able to calculate the average month, false otherwise.</returns>
        public bool TryGetAverageMonth(IEnumerable <MonthlySummary> monthSummaries, out MonthlySummary averageMonth)
        {
            averageMonth = null;

            if (monthSummaries == null)
            {
                return(false);
            }

            averageMonth = new MonthlySummary()
            {
                Spent  = (long)monthSummaries.Select(m => m.Spent).Average(),
                Income = (long)monthSummaries.Select(m => m.Income).Average()
            };

            return(true);
        }
        /// <summary>
        /// Creates a new monthly summary view.
        /// </summary>
        /// <param name="sourceMonthlySummary">The source of the monthly summary.</param>
        /// <param name="description">Optiona description for the month.</param>
        /// <returns>A monthly summary to display to the user.</returns>
        public static MonthlySummaryView CreateFromMonthlySummary(MonthlySummary sourceMonthlySummary, string description = null)
        {
            if (sourceMonthlySummary == null)
            {
                return(null);
            }

            string summaryDescription = string.IsNullOrEmpty(description) ?
                                        string.Format("{0}-{1}", sourceMonthlySummary.Year, sourceMonthlySummary.Month) :
                                        description;

            MonthlySummaryView monthlySummary = new MonthlySummaryView(
                summaryDescription,
                income: CentoCentsToDollars(sourceMonthlySummary.Income),
                spent: CentoCentsToDollars(sourceMonthlySummary.Spent));

            return(monthlySummary);
        }
        public void TestAverageMonth(long[] totalIncomePerMonth, long expectedAverageIncome, long[] totalExpensesPerMonth, long expectedAverageExpenses)
        {
            ICollection <MonthlySummary> months = new List <MonthlySummary>();

            for (int i = 0; i < totalIncomePerMonth.Length; i++)
            {
                MonthlySummary monthlySummary = new MonthlySummary()
                {
                    Income = totalIncomePerMonth[i],
                    Spent  = totalExpensesPerMonth[i]
                };
                months.Add(monthlySummary);
            }

            IAverageMonthCalculator calculator = new AverageMonthCalculator();

            Assert.True(calculator.TryGetAverageMonth(months, out MonthlySummary averageMonth));
            Assert.NotNull(averageMonth);
            Assert.Equal(expectedAverageIncome, averageMonth.Income);
            Assert.Equal(expectedAverageExpenses, averageMonth.Spent);
        }
 static PeriodType()
 {
     // Define ordering of period types.
     WeeklySummary.SetToEncompass(DailySummary);
     MonthlySummary.SetToEncompass(WeeklySummary);
 }
示例#8
0
文件: Analyser.cs 项目: Cycli/Cycli
        public static MonthlySummary[] GetMonthlySummary(string userId)
        {
            List<MonthlySummary> mss = new List<MonthlySummary>();
            try
            {
                SQLiteDatabase db = new SQLiteDatabase();
                long startms = DbTime.ToDbSecs(DateTime.UtcNow.AddYears(-1));
                string sql = @"select r.StartDateTime, rr.time, rr.distance, rr.energy, rr.pedalstrokes, rr.heartbeats, (CASE WHEN rr.Status = 'Abandoned' THEN 1 ELSE 0 END) Dnf " +
                  "from cycli_race_riders rr, cycli_races r " +
                      "where rr.UserId=@u " +
                      "and r.RaceId = rr.RaceId " +
                      "and r.StartDateTime >= @st " +
                      "and not rr.Status = 'Invited'";

                DataTable dtSummary = db.GetDataTable(sql, "@u", userId, "@st", startms);

                // Group the results by month
                var drMonths = dtSummary.AsEnumerable().GroupBy(p =>
                {
                    DateTime t = DbTime.FromDbSecs(p.Field<long>("StartDateTime"));
                    return t.ToString("MMM-yy");
                });
                foreach (var drMonth in drMonths)
                {
                    // Remove zero values - they'll just set the averages artifically low

                    MonthlySummary ms = new MonthlySummary()
                    {
                        Month = drMonth.Key,
                        TotalRaces = drMonth.Count(),
                        DnfRaces = (int)drMonth.Sum(p => p.Field<long>("Dnf")),
                        TotalDistance = drMonth.Sum(p => p.Field<double>("distance")),
                        TotalTime = drMonth.Sum(p => p.Field<long>("time")),
                        TotalWork = (int)(drMonth.Sum(p => p.Field<long>("energy"))),
                        MeanDistance = drMonth.Where(p => p.Field<long>("energy") > 0).Sum(p => p.Field<double>("distance")),
                        MeanTime = (long)drMonth.Where(p => p.Field<long>("time") > 0).Sum(p => p.Field<long>("time")),
                        MeanWork = (int)(drMonth.Where(p => p.Field<long>("energy") > 0).Sum(p => p.Field<long>("energy")))
                    };
                    if (ms.TotalRaces > 0)
                    {
                        ms.MeanDistance /= ms.TotalRaces;
                        ms.MeanTime /= ms.TotalRaces;
                        ms.MeanWork /= ms.TotalRaces;
                    }

                    // Prevent div by zero where there is no data
                    long speedTime = Math.Max(1, drMonth.Where(p => p.Field<double>("distance") > 0).Sum(p => p.Field<long>("time")));
                    long cadenceTime = Math.Max(1, drMonth.Where(p => p.Field<long>("pedalstrokes") > 0).Sum(p => p.Field<long>("time")));
                    long heartrateTime = Math.Max(1, drMonth.Where(p => p.Field<long>("heartbeats") > 0).Sum(p => p.Field<long>("time")));
                    long powerTime = Math.Max(1, drMonth.Where(p => p.Field<long>("energy") > 0).Sum(p => p.Field<long>("time")));

                    ms.MeanSpeed = MPERMILLISEC_TO_KMH * drMonth.Where(p => p.Field<double>("distance") > 0)
                            .Sum(p => p.Field<double>("distance")) / speedTime;

                    ms.MeanPower = (int)(1000 * drMonth.Where(p => p.Field<long>("energy") > 0)
                                .Sum(p => p.Field<long>("energy")) / powerTime);
                    ms.MeanCadence = (int)(60000 * drMonth.Where(p => p.Field<long>("pedalstrokes") > 0)
                            .Sum(p => p.Field<long>("pedalstrokes")) / cadenceTime);
                    ms.MeanHeartrate = (int)(60000 * drMonth.Where(p => p.Field<long>("heartbeats") > 0)
                            .Sum(p => p.Field<long>("heartbeats")) / heartrateTime);

                    mss.Add(ms);
                }
            }
            catch (Exception ex1)
            {
            }
            return mss.ToArray();
        }
示例#9
0
 public static decimal TotalKwh(this MonthlySummary summary)
 {
     return(summary.KwhUsageAtMonthEnd - summary.KwhUsageAtMonthStart);
 }
        /// <summary>
        /// Handles the Click event of the MnuMonthlySummary control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private void MnuMonthlySummary_Click(object sender, RoutedEventArgs e)
        {
            MonthlySummary summary = Statistics.CalculateMonthlySummary(controller.Manager.Timesheet);

            MessageBox.Show("Number of days worked so far: " + summary.NumberOfDaysWorkedSoFar + "\nTotal hours so far: " + summary.TotalHoursWorkedSoFar + "\nAverage hours per day: " + summary.AverageHoursPerDay + "\nExpected hours per day: " + summary.ExpectedHoursPerDay, "Monthly Summary", MessageBoxButton.OK, MessageBoxImage.Information);
        }