public void RemoveTrendlines_SignalIsSentToRepositoryToRemoveAllItems() { //Arrange IEnumerable <TrendlineDto> trendlineDtos = null; Trendline trendline1 = getDefaultTrendline(); Trendline trendline2 = getDefaultTrendline(); trendline2.Id = 2; Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); mockedRepository. Setup(r => r.RemoveTrendlines(It.IsAny <IEnumerable <TrendlineDto> >())). Callback <IEnumerable <TrendlineDto> >((col) => trendlineDtos = col).Verifiable(); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); service.RemoveTrendlines(new Trendline [] { trendline1, trendline2 }); //Assert IEnumerable <TrendlineDto> expectedTrendlineDtos = new TrendlineDto[] { trendline1.ToDto(), trendline2.ToDto() }; mockedRepository.Verify(r => r.RemoveTrendlines(It.IsAny <IEnumerable <TrendlineDto> >()), Times.Exactly(1)); Assert.IsTrue(trendlineDtos.HasEqualItems(expectedTrendlineDtos)); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object from source Excel file Workbook workbook = new Workbook(dataDir + "source.xlsx"); // Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Access the first chart inside the worksheet Chart chart = worksheet.Charts[0]; // Calculate the Chart first to get the Equation Text of Trendline chart.Calculate(); // Access the Trendline Trendline trendLine = chart.NSeries[0].TrendLines[0]; // Read the Equation Text of Trendline Console.WriteLine("Equation Text: " + trendLine.DataLabels.Text); // ExEnd:1 }
/// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { double currentEMALong = EMA(mALongLen)[0]; double currentEMAMed = EMA(mAMedLen)[0]; double currentEMAShort = EMA(mAShortLen)[0]; if (((currentEMAMed > currentEMALong) || (currentEMAShort > currentEMALong))) { Trendline.Set(currentEMALong); PlotColors[0][0] = uptick; //if(CrossBelow(EMA(mAShortLen),currentEMALong,7)) if (currentEMAShort < currentEMALong) { PlotColors[0][0] = downtick; } } else if ((currentEMAMed < currentEMALong) || (currentEMAShort < currentEMALong)) { Trendline.Set(currentEMALong); PlotColors[0][0] = downtick; } else { Trendline.Set(currentEMALong); PlotColors[0][0] = Color.Green; } }
private static object GetTimeRemaining(ModelBase model) { var viewModel = (ProgressFieldViewModel)model; if (viewModel.Target == 0) { return(TimeSpan.MaxValue); } if (viewModel._progressStart == null) { viewModel._progressStart = DateTime.UtcNow; return(TimeSpan.MaxValue); } var elapsed = DateTime.UtcNow - viewModel._progressStart.GetValueOrDefault(); var elapsedMilliseconds = elapsed.TotalMilliseconds; lock (viewModel._elapsedSample) { if (elapsedMilliseconds - viewModel._elapsedSample[viewModel._sampleIndex] > (1000 / SampleCount)) { viewModel._elapsedSample[viewModel._sampleIndex] = elapsedMilliseconds; viewModel._progressSample[viewModel._sampleIndex] = (double)viewModel.Current; viewModel._sampleIndex = (viewModel._sampleIndex + 1) % SampleCount; var trendline = new Trendline(viewModel._progressSample, viewModel._elapsedSample); viewModel._estimatedMilliseconds = trendline.GetY(viewModel.Target); } } var remainingMilliseconds = viewModel._estimatedMilliseconds - elapsedMilliseconds; return(TimeSpan.FromMilliseconds(remainingMilliseconds)); }
static void TrendlineLabel(Workbook workbook) { #region #TrendlineLabel Worksheet worksheet = workbook.Worksheets["chartTask3"]; workbook.Worksheets.ActiveWorksheet = worksheet; // Create a chart and specify its location. Chart chart = worksheet.Charts.Add(ChartType.ScatterMarkers); chart.SelectData(worksheet["C2:F3"], ChartDataDirection.Row); chart.TopLeftCell = worksheet.Cells["H2"]; chart.BottomRightCell = worksheet.Cells["N14"]; // Display a polynomial trendline. chart.Series[0].Trendlines.Add(ChartTrendlineType.Polynomial); // Customize the trendline. Trendline tline = chart.Series[0].Trendlines[0]; tline.DisplayEquation = true; tline.CustomName = "Trend"; tline.DisplayRSquare = true; tline.Outline.SetSolidFill(Color.Red); // Format the trend label. TrendlineLabel tlabel = tline.Label; tlabel.Font.Name = "Tahoma"; tlabel.Font.Italic = true; tlabel.Fill.SetGradientFill(ShapeGradientType.Linear, Color.Orange, Color.White); // Position the label in the right quarter of the chart area. tlabel.Layout.Left.SetPosition(LayoutMode.Edge, 0.75); #endregion #TrendlineLabel }
static void TrendlineCustomization(Workbook workbook) { #region #TrendlineCustomization Worksheet worksheet = workbook.Worksheets["chartTask3"]; workbook.Worksheets.ActiveWorksheet = worksheet; // Create a chart and specify its location. Chart chart = worksheet.Charts.Add(ChartType.ScatterMarkers); chart.SelectData(worksheet["C2:F3"], ChartDataDirection.Row); chart.TopLeftCell = worksheet.Cells["H2"]; chart.BottomRightCell = worksheet.Cells["N14"]; // Set the minimum and maximum values for the chart value axis. Axis axis = chart.PrimaryAxes[1]; axis.Scaling.AutoMax = false; axis.Scaling.AutoMin = false; axis.Scaling.Min = 0.6; axis.Scaling.Max = 1.0; chart.PrimaryAxes[1].MajorGridlines.Visible = false; // Display a polynomial trendline. chart.Series[0].Trendlines.Add(ChartTrendlineType.Polynomial); // Customize the trendline. Trendline tline = chart.Series[0].Trendlines[0]; tline.DisplayEquation = true; tline.CustomName = "Trend"; tline.DisplayRSquare = true; tline.Backward = 1; tline.Forward = 2; tline.Outline.SetSolidFill(Color.Red); #endregion #TrendlineCustomization }
private IEnumerable <Trendline> GetTrendlines(int assetId, int timeframeId, IEnumerable <TrendlineDto> dtos) { IEnumerable <Trendline> trendlines = dtos.Select(dto => Trendline.FromDto(dto)); IEnumerable <TrendRange> trendRanges = GetTrendRanges(assetId, timeframeId); Dictionary <int, ExtremumGroup> extremumGroupsMap = GetExtremumGroupsMap(assetId, timeframeId); Dictionary <int, Trendline> trendlinesMap = new Dictionary <int, Trendline>(); foreach (var trendline in trendlines) { ExtremumGroup baseEG; ExtremumGroup counterEG; extremumGroupsMap.TryGetValue(trendline.BaseExtremumGroupId, out baseEG); extremumGroupsMap.TryGetValue(trendline.CounterExtremumGroupId, out counterEG); trendline.BaseExtremumGroup = baseEG; trendline.CounterExtremumGroup = counterEG; trendlinesMap.Add(trendline.Id, trendline); } foreach (var trendRange in trendRanges) { Trendline trendline; trendlinesMap.TryGetValue(trendRange.TrendlineId, out trendline); if (trendline != null) { trendline.AddTrendRange(trendRange); } } return(trendlinesMap.Values); }
public Trendline GetTrendlineById(int id) { _repository = new EFTrendlineRepository(); var dto = _repository.GetTrendlineById(id); return(Trendline.FromDto(dto)); }
public static void Run() { //Source directory string sourceDir = RunExamples.Get_SourceDirectory(); // Create workbook object from source Excel file Workbook workbook = new Workbook(sourceDir + "sampleGetEquationTextOfChartTrendLine.xlsx"); // Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Access the first chart inside the worksheet Chart chart = worksheet.Charts[0]; // Calculate the Chart first to get the Equation Text of Trendline chart.Calculate(); // Access the Trendline Trendline trendLine = chart.NSeries[0].TrendLines[0]; // Read the Equation Text of Trendline Console.WriteLine("Equation Text: " + trendLine.DataLabels.Text); Console.WriteLine("GetEquationTextOfChartTrendLine executed successfully."); }
public void RemoveTrendline_ThisItemIsRemovedFromCache() { //Arrange IEnumerable <TrendlineDto> trendlineDtos = null; TrendlineDto trendlineDto = getDefaultTrendlineDto(); Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); mockedRepository.Setup(r => r.GetTrendlineById(1)).Returns(trendlineDto); mockedRepository. Setup(r => r.RemoveTrendlines(It.IsAny <IEnumerable <TrendlineDto> >())). Callback <IEnumerable <TrendlineDto> >((col) => trendlineDtos = col).Verifiable(); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); Trendline trendline = service.GetTrendlineById(1); TrendlineDto nullTrendline = null; service.RemoveTrendline(trendline); mockedRepository.Setup(r => r.GetTrendlineById(1)).Returns(nullTrendline); //Assert Trendline actualTrendline = service.GetTrendlineById(1); Assert.IsNull(actualTrendline); }
public void TestExample() { double[] x = new[] { 1.0, 2.0, 3.0 }; double[] y = new[] { 3.0, 5.0, 6.5 }; var trendline = new Trendline(x, y); Assert.That(Math.Round(trendline.GetY(0.0), 3), Is.EqualTo(1.333)); Assert.That(Math.Round(trendline.GetY(3.14), 3), Is.EqualTo(6.828)); }
public void TestLinear() { // y = 2x + 1 double[] x = new[] { 1.0, 2.0, 3.0 }; double[] y = new[] { 3.0, 5.0, 7.0 }; var trendline = new Trendline(x, y); Assert.That(trendline.GetX(0.0), Is.EqualTo(-0.5)); Assert.That(trendline.GetY(0.0), Is.EqualTo(1.0)); Assert.That(trendline.GetY(137.23), Is.EqualTo(275.46)); }
/// <summary> /// Initializes the ChartControl's data and sets the Chart type. /// </summary> protected void InitializeChartData() { ChartSeries series1 = new ChartSeries(" Rupees "); series1.Type = ChartSeriesType.Scatter; series1.Text = series1.Name; double[] yValue = new double[] { 7.66, 8.03, 8.41, 8.97, 8.77, 8.20, 8.16, 7.89, 8.68, 9.48, 10.11, 11.36, 12.34, 12.60, 12.95, 13.91, 16.21, 17.50, 22.72, 28.14, 31.26, 31.39, 32.43, 35.52, 36.36, 41.33, 43.12, 45.00, 47.23, 48.62, 46.60, 45.28, 44.01, 45.17, 41.20, 43.41, 48.32, 45.65, 46.61, 53.34, 58.53 }; int j = 0; for (int i = 1973; i <= 2013; i++) { series1.Points.Add(i, yValue[j]); j += 1; } series1.Style.Font.Facename = "Segoe UI"; series1.Style.Font.Size = 10; Trendline trendline = new Trendline(); trendline.Name = "Linear"; trendline.Style = DashStyle.Solid; series1.Trendlines.Add(trendline); this.chartControl1.Series.Add(series1); this.chartControl1.PrimaryXAxis.TickSize = new Size(1, 1); this.chartControl1.PrimaryYAxis.TickSize = new Size(1, 1); this.chartControl1.PrimaryXAxis.Font = new Font("Segoe UI", 10, FontStyle.Regular); this.chartControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel5.Dock = System.Windows.Forms.DockStyle.Right; this.comboBox1.DataSource = Enum.GetValues(typeof(TrendlineType)); this.comboBox2.Items.AddRange(new object[] { "2", "3", "4", "5", "6" }); foreach (string line in Enum.GetNames(typeof(DashStyle))) { this.comboBox3.Items.Add(line); } this.checkBox1.Checked = true; }
// Function that creates the plot public static void plotChart(string columnTitle) { Range chartRange; object misValue = System.Reflection.Missing.Value; // Creates the chart ChartObjects xlCharts = (ChartObjects)ExcelExecutions.xlWorksheet.ChartObjects(Type.Missing); ChartObject myChart = xlCharts.Add(250, 50, 600, 350); Chart xlChart = myChart.Chart; xlChart.ChartType = XlChartType.xlXYScatter; // Gets the range for the column title Range XcolumnTitleLocation = findCell(ExcelExecutions.xTitle); Range YcolumnTitleLocation = findCell(columnTitle); // The title for the x- and y-axis Axis xAxis = xlChart.Axes(XlAxisType.xlCategory, XlAxisGroup.xlPrimary) as Axis; Axis yAxis = xlChart.Axes(XlAxisType.xlValue, XlAxisGroup.xlPrimary) as Axis; xAxis.HasTitle = true; yAxis.HasTitle = true; xAxis.AxisTitle.Text = XcolumnTitleLocation.Value; yAxis.AxisTitle.Text = YcolumnTitleLocation.Value; // The values for the chart string xColumnPrefix = ExcelExecutions.columnNames[XcolumnTitleLocation.Column - 1]; string yColumnPrefix = ExcelExecutions.columnNames[YcolumnTitleLocation.Column - 1]; Range xValues = ExcelExecutions.xlWorksheet.Range[xColumnPrefix + "2", (xColumnPrefix + ExcelExecutions.xlRange.Rows.Count.ToString())]; Range yvalues = ExcelExecutions.xlWorksheet.Range[yColumnPrefix + "2", (yColumnPrefix + ExcelExecutions.xlRange.Rows.Count.ToString())]; // Assigns the value to the chart SeriesCollection seriesCollection = xlChart.SeriesCollection(); Series pointPlot = seriesCollection.NewSeries(); pointPlot.XValues = xValues; pointPlot.Name = columnTitle; pointPlot.Values = yvalues; // Creates trendline(regression) Trendlines trendlines = (Trendlines)pointPlot.Trendlines(Type.Missing); Trendline linearRegression = trendlines.Add(XlTrendlineType.xlLinear); linearRegression.DisplayEquation = true; linearRegression.DisplayRSquared = true; saveChart(xlChart, pointPlot.Name); }
public void GetTrendlineById_ReturnsNull_IfThereIsNoItemWithGivenCombination() { //Arrange Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); TrendlineDto returnedDto = null; mockedRepository.Setup(r => r.GetTrendlineById(1)).Returns(returnedDto); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); //Assert Trendline baseTrendline = service.GetTrendlineById(1); Assert.IsNull(baseTrendline); }
public void Process_IfNewTrendlineAndStartIndexLaterThanGivenItem_NothingHappens() { //Arrange Mock <IProcessManager> mockManager = null; // getDefaultMockManager(4); //Extremum baseMaster = new Extremum(getDefaultAtsSettings(), ExtremumType.PeakByClose, 4); //Extremum secondMaster = new Extremum(getDefaultAtsSettings(), ExtremumType.PeakByClose, 10); //Act Trendline trendline = new Trendline(null); TrendlineProcessor processor = new TrendlineProcessor(mockManager.Object); //processor.Process(trendline, //Assert Assert.Fail("Not implemented yet"); }
public void GetTrendlineById_ReturnsProperItem_IfItemExists() { //Arrange Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); TrendlineDto trendlineDto = new TrendlineDto() { Id = 1, AssetId = DEFAULT_ASSET_ID, TimeframeId = DEFAULT_TIMEFRAME_ID, SimulationId = DEFAULT_SIMULATION_ID, StartIndex = 50, StartLevel = 1.1234, FootholdLevel = 1.1412, FootholdIndex = 72, LastUpdateIndex = 77, Value = 1.23 }; mockedRepository.Setup(r => r.GetTrendlineById(1)).Returns(trendlineDto); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); var actualTrendline = service.GetTrendlineById(1); //Assert Trendline expectedTrendline = new Trendline(trendlineDto); bool areEqual = expectedTrendline.Equals(actualTrendline); Assert.IsTrue(areEqual); }
public SlopeInfo(List <ExtractedValue> extractedValues) { var calculus = new MathCalculus(); var trendline = new Trendline(); if (extractedValues.Count != 0) { NominalValues = extractedValues; NominalTrendline = trendline.GetTrendline(extractedValues); Growth = calculus.CalculateGrowth(extractedValues); GrowthTrendline = trendline.GetTrendline(Growth); NominalMedian = calculus.CalculateMedian(extractedValues); GrowthMedian = calculus.CalculateMedian(Growth); NominalDeviation = calculus.CalculateDeviation(extractedValues); GrowthDeviation = calculus.CalculateDeviation(Growth); LastThreeYearsGrowth = calculus.CalculateLastThreeYearsGrowth(Growth); LastThreeYearsTrendLine = trendline.GetTrendline(LastThreeYearsGrowth); LastFiveYearsGrowth = calculus.CalculateLastFiveYearsGrowth(extractedValues); LastTenYearsGrowth = calculus.CalculateLastTenYearsGrowth(extractedValues); } }
public void UpdateTrendlines_AllItemsPassedToMethodArePassedToRepository() { //Arrange IEnumerable <TrendlineDto> trendlineDtos = null; Trendline trendline = getDefaultTrendline(); Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); mockedRepository. Setup(r => r.UpdateTrendlines(It.IsAny <IEnumerable <TrendlineDto> >())). Callback <IEnumerable <TrendlineDto> >((col) => trendlineDtos = col).Verifiable(); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); service.UpdateTrendline(trendline); //Assert IEnumerable <TrendlineDto> expectedTrendlineDtos = new TrendlineDto[] { trendline.ToDto() }; mockedRepository.Verify(r => r.UpdateTrendlines(It.IsAny <IEnumerable <TrendlineDto> >()), Times.Exactly(1)); Assert.IsTrue(trendlineDtos.HasEqualItems(expectedTrendlineDtos)); }
public void GetTrendlines_ReturnsProperCollectionOfTrendlines() { //Arrange Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); List <TrendlineDto> dtos = new List <TrendlineDto>(); TrendlineDto trendlineDto1 = new TrendlineDto() { Id = 1, AssetId = DEFAULT_ASSET_ID, TimeframeId = DEFAULT_TIMEFRAME_ID, SimulationId = DEFAULT_SIMULATION_ID, StartIndex = 50, StartLevel = 1.1234, FootholdLevel = 1.1412, FootholdIndex = 72, LastUpdateIndex = 77, Value = 1.23 }; TrendlineDto trendlineDto2 = new TrendlineDto() { Id = 2, AssetId = DEFAULT_ASSET_ID, TimeframeId = DEFAULT_TIMEFRAME_ID, SimulationId = DEFAULT_SIMULATION_ID, StartIndex = 64, StartLevel = 1.1276, FootholdLevel = 1.1412, FootholdIndex = 72, LastUpdateIndex = 77, Value = 1.49 }; TrendlineDto trendlineDto3 = new TrendlineDto() { Id = 3, AssetId = DEFAULT_ASSET_ID, TimeframeId = DEFAULT_TIMEFRAME_ID, SimulationId = DEFAULT_SIMULATION_ID, StartIndex = 81, StartLevel = 1.1315, FootholdLevel = 1.1412, FootholdIndex = 72, LastUpdateIndex = 77, Value = 2.16 }; dtos.AddRange(new TrendlineDto[] { trendlineDto1, trendlineDto2, trendlineDto3 }); mockedRepository.Setup(r => r.GetTrendlines(DEFAULT_ASSET_ID, DEFAULT_TIMEFRAME_ID, DEFAULT_SIMULATION_ID)).Returns(dtos); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); var actualSimultations = service.GetTrendlines(DEFAULT_ASSET_ID, DEFAULT_TIMEFRAME_ID, DEFAULT_SIMULATION_ID); //Assert List <Trendline> expectedTrendlines = new List <Trendline>(); Trendline trendline1 = new Trendline(trendlineDto1); Trendline trendline2 = new Trendline(trendlineDto2); Trendline trendline3 = new Trendline(trendlineDto3);; expectedTrendlines.AddRange(new Trendline[] { trendline1, trendline2, trendline3 }); bool areEqual = expectedTrendlines.HasEqualItems(actualSimultations); Assert.IsTrue(areEqual); }
public void Constructor_fromDto_hasCorrectProperties() { //Act. var trendlineDto = new TrendlineDto() { Id = UTDefaulter.DEFAULT_ID, AssetId = UTDefaulter.DEFAULT_ASSET_ID, TimeframeId = UTDefaulter.DEFAULT_TIMEFRAME_ID, SimulationId = UTDefaulter.DEFAULT_SIMULATION_ID, StartIndex = UTDefaulter.DEFAULT_START_INDEX, StartLevel = UTDefaulter.DEFAULT_START_LEVEL, FootholdIndex = UTDefaulter.DEFAULT_FOOTHOLD_INDEX, FootholdLevel = UTDefaulter.DEFAULT_FOOTHOLD_LEVEL, FootholdSlaveIndex = UTDefaulter.DEFAULT_FOOTHOLD_SLAVE_INDEX, FootholdIsPeak = UTDefaulter.DEFAULT_FOOTHOLD_IS_PEAK, EndIndex = null, Value = UTDefaulter.DEFAULT_VALUE, LastUpdateIndex = UTDefaulter.DEFAULT_LAST_UPDATE_INDEX }; var trendline = new Trendline(trendlineDto); //Assert. Assert.AreEqual(UTDefaulter.DEFAULT_ID, trendline.Id); Assert.AreEqual(UTDefaulter.DEFAULT_ASSET_ID, trendline.AssetId); Assert.AreEqual(UTDefaulter.DEFAULT_TIMEFRAME_ID, trendline.TimeframeId); Assert.AreEqual(UTDefaulter.DEFAULT_SIMULATION_ID, trendline.SimulationId); Assert.AreEqual(UTDefaulter.DEFAULT_START_INDEX, trendline.StartIndex); Assert.AreEqual(UTDefaulter.DEFAULT_START_LEVEL, trendline.StartLevel); Assert.AreEqual(UTDefaulter.DEFAULT_FOOTHOLD_INDEX, trendline.FootholdIndex); Assert.AreEqual(UTDefaulter.DEFAULT_FOOTHOLD_LEVEL, trendline.FootholdLevel); Assert.AreEqual(UTDefaulter.DEFAULT_FOOTHOLD_SLAVE_INDEX, trendlineDto.FootholdSlaveIndex); Assert.AreEqual(UTDefaulter.DEFAULT_FOOTHOLD_IS_PEAK, trendlineDto.FootholdIsPeak); Assert.AreEqual(UTDefaulter.DEFAULT_VALUE, trendline.Value); Assert.IsNull(trendline.EndIndex); Assert.AreEqual(UTDefaulter.DEFAULT_LAST_UPDATE_INDEX, trendline.LastUpdateIndex); }
private Trendline getDefaultTrendline() { AtsSettings settings = new AtsSettings(DEFAULT_ASSET_ID, DEFAULT_TIMEFRAME_ID, DEFAULT_SIMULATION_ID); Price basePrice = getPrice(DEFAULT_START_INDEX); Extremum baseMaster = new Extremum(basePrice, ExtremumType.PeakByClose); ExtremumGroup baseGroup = new ExtremumGroup(baseMaster, null); TrendlinePoint basePoint = new TrendlinePoint(baseGroup, DEFAULT_START_LEVEL); Price secondPrice = getPrice(DEFAULT_FOOTHOLD_INDEX); Extremum secondMaster = new Extremum(secondPrice, ExtremumType.PeakByClose); ExtremumGroup secondGroup = new ExtremumGroup(secondMaster, null); TrendlinePoint footholdPoint = new TrendlinePoint(secondGroup, DEFAULT_FOOTHOLD_LEVEL); Trendline trendline = new Trendline(settings, basePoint, footholdPoint); trendline.Id = DEFAULT_ID; trendline.Value = DEFAULT_VALUE; trendline.LastUpdateIndex = DEFAULT_LAST_UPDATE_INDEX; trendline.FootholdSlaveIndex = DEFAULT_FOOTHOLD_SLAVE_INDEX; trendline.CurrentIsPeak = DEFAULT_CURRENT_IS_PEAK; return(trendline); }
public void GetTrendlineById_ReturnsAlwaysTheSameInstance() { //Arrange Mock <ITrendlineRepository> mockedRepository = new Mock <ITrendlineRepository>(); List <TrendlineDto> dtos = new List <TrendlineDto>(); TrendlineDto trendlineDto1 = new TrendlineDto() { Id = 1, AssetId = DEFAULT_ASSET_ID, TimeframeId = DEFAULT_TIMEFRAME_ID, SimulationId = DEFAULT_SIMULATION_ID, StartIndex = 50, StartLevel = 1.1234, FootholdLevel = 1.1412, FootholdIndex = 72, LastUpdateIndex = 77, Value = 1.23 }; dtos.AddRange(new TrendlineDto[] { trendlineDto1 }); mockedRepository.Setup(r => r.GetTrendlines(DEFAULT_ASSET_ID, DEFAULT_TIMEFRAME_ID, DEFAULT_SIMULATION_ID)).Returns(dtos); //Act TrendlineService service = new TrendlineService(mockedRepository.Object); //Assert Trendline baseTrendline = service.GetTrendlineById(1); Trendline comparedTrendline = service.GetTrendlineById(1); bool areTheSame = (baseTrendline == comparedTrendline); Assert.IsTrue(areTheSame); }
public CompanyGrowthPrediction GetFutureValues(Guid companyId) { var companyInfo = _dao.GetCompanyInfo(companyId); var valuesList = new List <ExtractedValue>(); var valuesFiveYearsList = new List <ExtractedValue>(); var valuesThreeYearsList = new List <ExtractedValue>(); var incomeStatements = companyInfo.IncomeStatements.OrderBy(x => x.Year); var cashFlowStatements = companyInfo.CashFlowStatements.OrderBy(x => x.Year); var balanceSheets = companyInfo.BalanceSheets.OrderBy(x => x.Year); var KeyRatios = companyInfo.KeyRatios.OrderBy(x => x.Year); //(Net Income -Dividends - Depreciation & Amortization) / (Shareholders' Equity + Long-Term Debt) foreach (var item in incomeStatements) { var values = new ExtractedValue(); values.CompanyId = companyId; values.Year = item.Year; var netIncome = item.NetIncome; if (netIncome == null) { netIncome = 0; } var dividends = KeyRatios.Where(x => x.Year == item.Year).SingleOrDefault().DividendsPerShare; if (dividends == null) { dividends = 0; } var depreciationAndAmortization = cashFlowStatements.Where(x => x.Year == item.Year).SingleOrDefault().DepreciationAmortization; if (depreciationAndAmortization == null) { depreciationAndAmortization = 0; } var shareholdersEquity = balanceSheets.Where(x => x.Year == item.Year).SingleOrDefault().ShareholdersEquity; if (shareholdersEquity == null) { shareholdersEquity = 0; } var longTermDebt = balanceSheets.Where(x => x.Year == item.Year).SingleOrDefault().LongTermDebt; if (longTermDebt == null) { longTermDebt = 0; } var growthValue = (netIncome - (decimal)dividends - depreciationAndAmortization) / (shareholdersEquity + longTermDebt); values.Value = (double)growthValue; valuesList.Add(values); if (item.Year < incomeStatements.ToList()[(incomeStatements.ToList().Count - 5)].Year) { valuesFiveYearsList.Add(values); } if (item.Year < incomeStatements.ToList()[(incomeStatements.ToList().Count - 3)].Year) { valuesThreeYearsList.Add(values); } } var trendline = new Trendline(); var other = new OtherTrendlines(); var valuesTrendline = trendline.GetTrendline(valuesList); var slope = valuesTrendline.Slope; var intercept = valuesTrendline.Intercept; var estimatedValue = (DateTime.Now.Year + 1) * slope + intercept; var valuesTrendline5Years = trendline.GetTrendline(valuesFiveYearsList); var slope5Years = valuesTrendline.Slope; var intercept5Years = valuesTrendline.Intercept; var estimatedValue5Years = (DateTime.Now.Year + 1) * slope + intercept; var valuesTrendline3Years = trendline.GetTrendline(valuesThreeYearsList); var slope3Years = valuesTrendline.Slope; var intercept3Years = valuesTrendline.Intercept; var estimatedValue3Years = (DateTime.Now.Year + 1) * slope + intercept; var estimatedValues = new CompanyGrowthPrediction(); estimatedValues.CompanyId = companyId; estimatedValues.Year = DateTime.Now.Year + 1; if (other.GetMinGrowthValue(valuesList, DateTime.Now.Year + 1) < other.GetMaxGrowthValue(valuesList, DateTime.Now.Year + 1)) { estimatedValues.MinValue = other.GetMinGrowthValue(valuesList, DateTime.Now.Year + 1); estimatedValues.EspectedValue = estimatedValue; estimatedValues.MaxValue = other.GetMaxGrowthValue(valuesList, DateTime.Now.Year + 1); } else if (other.GetMinGrowthValue(valuesList, DateTime.Now.Year + 1) == other.GetMaxGrowthValue(valuesList, DateTime.Now.Year + 1)) { estimatedValues.MinValue = estimatedValue - estimatedValue * 0.1; estimatedValues.EspectedValue = estimatedValue; estimatedValues.MaxValue = estimatedValue + estimatedValue * 0.1; } else { estimatedValues.MinValue = other.GetMaxGrowthValue(valuesList, DateTime.Now.Year + 1); estimatedValues.EspectedValue = estimatedValue; estimatedValues.MaxValue = other.GetMinGrowthValue(valuesList, DateTime.Now.Year + 1); } if (other.GetMinGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1) < other.GetMaxGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1)) { estimatedValues.MinValueFiveYears = other.GetMinGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1); estimatedValues.EspectedValueFiveYears = estimatedValue5Years; estimatedValues.MaxValueFiveYears = other.GetMaxGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1); } else if (other.GetMinGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1) == other.GetMaxGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1)) { estimatedValues.MinValueFiveYears = estimatedValue - estimatedValue * 0.1; estimatedValues.EspectedValueFiveYears = estimatedValue5Years; estimatedValues.MaxValueFiveYears = estimatedValue + estimatedValue * 0.1; } else { estimatedValues.MinValueFiveYears = other.GetMaxGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1); estimatedValues.EspectedValueFiveYears = estimatedValue5Years; estimatedValues.MaxValueFiveYears = other.GetMinGrowthValue(valuesFiveYearsList, DateTime.Now.Year + 1); } if (other.GetMinGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1) < other.GetMaxGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1)) { estimatedValues.MinValueThreeYears = other.GetMinGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1); estimatedValues.EspectedValueThreeYears = estimatedValue3Years; estimatedValues.MaxValueThreeYears = other.GetMaxGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1); } else if (other.GetMinGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1) == other.GetMaxGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1)) { estimatedValues.MinValueThreeYears = estimatedValue - estimatedValue * 0.1; estimatedValues.EspectedValueThreeYears = estimatedValue3Years; estimatedValues.MaxValueThreeYears = estimatedValue + estimatedValue * 0.1; } else { estimatedValues.MinValueThreeYears = other.GetMaxGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1); estimatedValues.EspectedValueThreeYears = estimatedValue3Years; estimatedValues.MaxValueThreeYears = other.GetMinGrowthValue(valuesThreeYearsList, DateTime.Now.Year + 1); } return(estimatedValues); }
public static void AnalizeFeaturesUse(RawDataSet dataSet) { var subFeaturesUseFrequencies = FeatureMetadata.AllFeatures.SelectMany(f => f.SubFeatures.Values).ToDictionary( sf => sf, sf => new UseFrequencyInfo()); foreach (var dateGroup in dataSet .Sessions .Select(s => new { Session = s, Date = s.Started.Date }) .OrderBy(x => x.Date) .GroupBy(x => x.Date)) { var totalNrOfLogs = dateGroup.Sum(x => x.Session.TotalNrOfLogs); if (totalNrOfLogs == 0) { continue; // no logs were open this day, ignore this day } var date = dateGroup.First().Date; foreach (var featureGroup in dateGroup.SelectMany(d => d.Session.Features).GroupBy(f => f.Meta)) { var featureMeta = featureGroup.First().Meta; // Feature with meta featureMeta was used this day (date). // Let's count how often each sub-feature was used this day. var counters = featureMeta.SubFeatures.ToDictionary(sf => sf.Key, sf => 0); foreach (var sf in featureGroup.SelectMany(f => f.SubFeatures)) { counters[sf.Meta.Id] += sf.UseCount; } foreach (var sf in featureMeta.SubFeatures) { subFeaturesUseFrequencies[sf.Value].AddDataPoint(date, (double)counters[sf.Key] / (double)totalNrOfLogs); } } } var frequencesXmlDoc = new XDocument(new XElement("root")); foreach (var sf in subFeaturesUseFrequencies) { DateTime firstDate = new DateTime(); Trendline trend = null; var isDeadSubFeature = false; if (sf.Value.weeklyAverageUseFrequencies.Count == 0) { isDeadSubFeature = true; } else { firstDate = sf.Value.weeklyAverageUseFrequencies.First().date; trend = CalcTend(sf.Value.weeklyAverageUseFrequencies.Select( f => new DataPoint() { X = (f.date - firstDate).Days, Y = f.value }).ToArray()); } if (trend != null && Math.Abs(trend.slope) < 1e-6 && Math.Abs(trend.offset) < 1e-6) { isDeadSubFeature = true; } else if (trend != null && trend.slope < 0) { var predictedUnuseDate = firstDate.AddDays(-trend.offset / trend.slope); if (predictedUnuseDate < DateTime.Now) { isDeadSubFeature = true; } } if (isDeadSubFeature) { var prefix = ""; if (sf.Key.IsKnownObsoleteCodepath) { prefix += "Known "; } if (sf.Key.IsRareCodepath) { prefix += "Rare "; } if (prefix == "") { prefix = " "; } Console.Write(prefix); Console.Write("dead feature: {0} trend: ", sf.Key.Name); if (trend != null) { Console.WriteLine("{0}*x + {1}", trend.slope, trend.offset); } else { Console.WriteLine("N/A"); } } foreach (var freq in sf.Value.weeklyAverageUseFrequencies) { frequencesXmlDoc.Root.Add(new XElement( "subFeatureUseFrequency", new XElement("featureId", sf.Key.Feature.Id), new XElement("subFeatureId", sf.Key.Id), new XElement("subFeatureName", sf.Key.Name), new XElement("year", freq.date.Year), new XElement("month", freq.date.Month), new XElement("dayOfYear", freq.date.DayOfYear), new XElement("week", freq.date.DayOfYear / 7), new XElement("freq", freq.value) )); } } frequencesXmlDoc.Save(Environment.ExpandEnvironmentVariables("%USERPROFILE%\\lj.telem.sub-features.freqs.xml")); }