Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { NewsService } from './../../../services/news.service';
  2. import { Router } from '@angular/router';
  3. import { Stock } from './../../../classes/stock';
  4. import { SharedMemoryService } from './../../../services/sharedMemory.service';
  5. import { Component, SimpleChanges, OnChanges, Input, HostListener, AfterViewInit, Renderer2, ViewChild, OnInit } from '@angular/core';
  6. import { clone, reverse, chunk, max, sortBy } from 'lodash';
  7. import { StockAnalysisService } from './stock-analysis.service';
  8. import { AppStorageService } from '../../../services/appStorage.service';
  9. import { StockService } from '../stock.service';
  10.  
  11. declare const google: any;
  12.  
  13. @Component({
  14.   selector: 'app-stock-analysis',
  15.   templateUrl: './stock-analysis.component.html',
  16.   styleUrls: ['./stock-analysis.component.css'],
  17.   providers: []
  18. })
  19.  
  20. export class StockAnalysisComponent implements OnChanges, AfterViewInit, OnInit {
  21.   @Input() chartData: any;
  22.   @Input() canDraw: boolean;
  23.   @Input() stock: Stock;
  24.   dataTable: any[];
  25.   timeFrame: any[];
  26.   @ViewChild('periodSort') periodSort: Element;
  27.   period = 'Y';
  28.   days = 1000;
  29.   factor: number;
  30.   dataTableLength = 0;
  31.   timeFrameLength: number;
  32.   preStockData = []; // holds all of the detailed data of the graph. each click on grph point will have its details.
  33.   chosenGraphPoint;
  34.   top4Indexes = [];
  35.   tfCopy;
  36.   firstTimerCounter = 0;
  37.  
  38.   constructor(
  39.     private sharedMemoryService: SharedMemoryService,
  40.     private renderer: Renderer2,
  41.     private router: Router,
  42.     private newsService: NewsService,
  43.     private stockAnalysisService: StockAnalysisService,
  44.     private appStorageService: AppStorageService,
  45.     private stockService: StockService
  46.   ) {
  47.     google.charts.load('current', { packages: ['line', 'bar'] });
  48.     google.charts.setOnLoadCallback(this.drawBasic.bind(this));
  49.  
  50.   }
  51.  
  52.   // this.stockAnalysisService.getOptionsY(); has the same hAxis as the rest of the getOptions (W\M)
  53.   @HostListener('window:resize', ['$event']) onResize(event) {
  54.     if (event.target['innerWidth'] < 420) {
  55.       this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM';
  56.     } else if (event.target['innerWidth'] < 760) {
  57.       this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MM. yy\'';
  58.     } else { this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM d, yyyy'; }
  59.     this.drawBasic();
  60.   }
  61.  
  62.   ngOnInit() {
  63.     this.stockAnalysisService.changeViewListener()
  64.       .subscribe(({ period: period, length: section }) => {
  65.         this.changeView(period, section);
  66.       });
  67.   }
  68.  
  69.   ngOnChanges(simpleChanges: SimpleChanges) {
  70.     // first initial draw (only to present graph first with no data):
  71.  
  72.     // data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
  73.  
  74.  
  75.     if (this.canDraw) {
  76.       this.chartData = reverse(this.chartData); // to present on axis line the last week \ month
  77.       const data = new google.visualization.DataTable();
  78.       data.addColumn('date', 'Date');
  79.       data.addColumn('number', 'Stock');
  80.       const chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  81.       chart.draw(data, this.stockAnalysisService.getOptionsY());
  82.  
  83.       this.dataTable = this.sharedMemoryService.getToolTipData();
  84.       this.fetchStockDaily(); // fetch and manipulate needed data for stock daily per point on graph.
  85.       this.appStorageService.saveStockHistory(this.dataTable);
  86.       this.changeView('M', -1);
  87.     }
  88.   }
  89.  
  90.   ngAfterViewInit() {
  91.     // document.getElementById('line_chart').style.opacity = '1';
  92.     const periodChildren = this.periodSort['nativeElement'].children;
  93.     this.renderer.addClass(periodChildren[1], 'active');
  94.     // this.onResize({ target: { innerWidth: window.innerWidth } });
  95.     // this.changeToMonth();
  96.  
  97.   }
  98.  
  99.   changeToMonth() {
  100.     setTimeout(() => {
  101.       if (this.canDraw) {
  102.         this.changeView('M', -1);
  103.       } else { this.changeToMonth(); }
  104.     }, 100);
  105.   }
  106.  
  107.   resetAnnotations() { // used to clean all annotations from changeView to changeView ('M' to 'Y' for example)
  108.     // const length = this.factor + this.dataTable['length'];
  109.     const length = this.chartData['length'];
  110.     for (let i = 0; i < length; i++) {
  111.       this.chartData[i][2] = null;
  112.     }
  113.     // for (let i = 0; i < length; i++) {
  114.     //   if (this.chartData[i]['length'] === 3) {
  115.     //     this.chartData[i][2] = null;
  116.     //   } else {
  117.     //     this.chartData[i].push(null);
  118.     //   }
  119.     // }
  120.   }
  121.  
  122.   drawBasic() {
  123.  
  124.     // score - opponent - outcome
  125.     if (this.canDraw) {
  126.       const data = new google.visualization.DataTable();
  127.       data.addColumn('date', 'Date');
  128.       data.addColumn('number', 'Stock');
  129.       data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
  130.  
  131.       const chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  132.       // getting all 'x' highest Abs stock values (* I cannot sort since there are alot of same EXACT values, index is best solution.)
  133.       this.resetAnnotations(); // so data from 'M' wont affect 'Y' because it still remains after changeView.
  134.  
  135.       // #### START OF TOP 4 ALGORITHM
  136.       let indexCounter = 0;
  137.       let stockValuesIndex = [];
  138.       const tempStockValues = [];
  139.       const tempStockValuesIndexes = [];
  140.       for (let i = 1; i < this.dataTable['length']; i++) {
  141.         const currentIndexValue = this.dataTable[i][1];
  142.         const beforeIndexValue = this.dataTable[i - 1][1];
  143.         const totalDifference = currentIndexValue - beforeIndexValue;
  144.         if (currentIndexValue - beforeIndexValue > 0) {
  145.           // tempStockValues.push(this.dataTable[i][1]);
  146.           tempStockValues.push(totalDifference);
  147.           tempStockValuesIndexes.push(this.factor + i);
  148.         } else if (currentIndexValue - beforeIndexValue < 0) {
  149.           tempStockValues.push(Math.abs(totalDifference));
  150.           tempStockValuesIndexes.push(this.factor + i);
  151.         }
  152.       }
  153.       let top4 = [];
  154.       if (tempStockValues.length > 4) {
  155.         for (let i = 0; i < 4; i++) {
  156.           const currentMaxValue = max(tempStockValues); // find max value
  157.           // delete current max value so we wont find duplicate max values:
  158.           const currentMaxValueIndex = tempStockValues.indexOf(currentMaxValue);
  159.           top4.push(tempStockValuesIndexes[currentMaxValueIndex]); // add max value
  160.           tempStockValues.splice(currentMaxValueIndex, 1);
  161.           tempStockValuesIndexes.splice(currentMaxValueIndex, 1);
  162.         }
  163.       } else {
  164.         top4 = tempStockValuesIndexes;
  165.       }
  166.       stockValuesIndex = sortBy(top4);
  167.       this.top4Indexes = stockValuesIndex;
  168.       // #### END OF TOP 4 ALGORITHM
  169.  
  170.  
  171.  
  172.  
  173.       let phrase = ''; // this will contain for each annotation its concatonated text for switch case statement.
  174.       // const dtLength = this.dataTable['length'] - 1;
  175.       for (let i = 0; i < this.dataTableLength; i++) {
  176.         // const dTable = this.dataTable[i];
  177.         // const outrights =  this.dataTable[i][2]['outrights'];
  178.         if (i === this.dataTableLength - 1) { // to handle last point
  179.           //
  180.         } else {
  181.           if (this.dataTable[i][2]['games']) { // if there was a game on that date
  182.             const game = this.dataTable[i][2]['games'][0];
  183.  
  184.             // for Factor 1 and for later use.
  185.             const score = game['score'];
  186.             const opponent = game['opponent'];
  187.             const outcome = game['outcome'];
  188.             // if league (in our case only EPL)
  189.             if (game['competition'] === 'EPL') {
  190.               // phrase = outcome + ' ' + game['competition'] + ' game';
  191.               phrase = 'E';
  192.             } else { // FA, EFL, CL and EL
  193.               for (let t = 0; t < this.dataTable[i][2]['outrights']['length'] - 1; t++) {
  194.                 if (this.dataTable[i][2]['outrights'][t]['competition'] === 'premier-league') { // this means cell '0' is also premiere league
  195.                   if (this.dataTable[i + 1][2]['outrights'][t]['fulfilled'] === 1 &&
  196.                     typeof (this.dataTable[i][2]['outrights'][t]['fulfilled'] === 'undefined')) { // if league outrights was achieved
  197.                     // TODO: if there are more then 1 achievement, we should decide top achievement
  198.                     // phrase = `Secured ${this.dataTable[i][2]['outrights'][i]['competition']} ${this.dataTable[i][2]['outrights'][i]['outright']}`;
  199.                     phrase = 'E';
  200.                     break;
  201.                   } else if (this.dataTable[i + 1][2]['outrights'][t]['fulfilled'] === 0 &&
  202.                     typeof (this.dataTable[i][2]['outrights'][t]['fulfilled'] === 'undefined')) { // if league outrights was lost
  203.                     // phrase = `Lost ${this.dataTable[i][2]['outrights'][i]['competition']} ${this.dataTable[i][2]['outrights'][i]['outright']}`;
  204.                     phrase = 'E';
  205.                     break;
  206.                   } else {
  207.                     if (i === this.dataTable[i][2]['outrights']['length'] - 1) { // we want it only once. ???
  208.                       // phrase = outcome + ' ' + game['competition'] + ' game';
  209.                       phrase = 'E';
  210.                       break;
  211.                     }
  212.                   }
  213.                 }
  214.               }
  215.             }
  216.           } else { // if there was no game
  217.             for (let j = 0; j < this.dataTable[i][2]['outrights']['length']; j++) {
  218.               if (this.dataTable[i + 1][2]['outrights'][j]['fulfilled'] === 1 &&
  219.                 typeof (this.dataTable[i][2]['outrights'][j]['fulfilled'] === 'undefined')) { // if league outrights was achieved
  220.                 // TODO: if there are more then 1 achievement, we should decide top achievement
  221.                 // phrase = `Qualified for ${this.dataTable[i][2]['outrights'][i]['competition']} NA`;
  222.                 phrase = 'E';
  223.                 break;
  224.               } else if (this.dataTable[i + 1][2]['outrights'][j]['fulfilled'] === 0 &&
  225.                 typeof (this.dataTable[i][2]['outrights'][j]['fulfilled'] === 'undefined')) { // if league outrights was lost
  226.                 // phrase = `Relegation from ${this.dataTable[i][2]['outrights'][i]['competition']} NA`;
  227.                 phrase = 'E';
  228.                 break;
  229.               } else { // for now we do not implement 'league outright was changed'
  230.                 let totalOutrightsSum = 0;
  231.                 for (let k = 0; k < this.dataTable[i][2]['outrights']['length'] - 1; k++) {
  232.                   totalOutrightsSum += parseFloat(this.dataTable[i][2]['outrights'][k]['impact']);
  233.                 }
  234.  
  235.                 let direction = '';
  236.                 if (totalOutrightsSum > 0) {
  237.                   direction = 'Improved';
  238.                 } else if (totalOutrightsSum < 0) {
  239.                   direction = 'Worsened';
  240.                 }
  241.                 // phrase = `Expectations ${direction}`;
  242.                 phrase = 'E';
  243.                 break;
  244.               }
  245.             }
  246.           }
  247.         }
  248.  
  249.  
  250.         switch (this.period) {
  251.           case 'W': {
  252.             if (this.factor + i === stockValuesIndex[indexCounter]) {
  253.               this.chartData[this.factor + i][2] = phrase;
  254.               indexCounter++;
  255.             }
  256.             break;
  257.           }
  258.           case 'M': {
  259.             if (this.factor + i === stockValuesIndex[indexCounter]) {
  260.               // this.chartData[this.factor + i][1] = tempStockValues[stockValuesIndex[indexCounter]];
  261.               this.chartData[this.factor + i][2] = phrase;
  262.               indexCounter++;
  263.             }
  264.             break;
  265.           }
  266.           case 'Y': {
  267.             if (this.factor + i === stockValuesIndex[indexCounter]) {
  268.               this.chartData[this.factor + i][2] = phrase;
  269.               indexCounter++;
  270.             }
  271.             break;
  272.           }
  273.         }
  274.       }
  275.  
  276.       const timeFrame = chunk(this.chartData, this.days);
  277.       const length = this.timeFrameLength;
  278.       data.addRows((timeFrame[length]));
  279.  
  280.  
  281.       // set listener
  282.       this.selectListener(chart, data);
  283.       // this.readyListener(chart, data);
  284.  
  285.       chart.draw(data, this.stockAnalysisService.getOptionsW());
  286.       // this.chosenGraphPoint = this.preStockData[this.factor + this.dataTable['length'] - 1];
  287.       // console.log(chart.getSelection())
  288.  
  289.       // responsible to auto select a default graph point per each period. (last event)
  290.       let topIndex: number;
  291.       if (typeof (this.top4Indexes[3]) !== 'undefined') {
  292.         topIndex = this.top4Indexes[3];
  293.       } else if (typeof (this.top4Indexes[2]) !== 'undefined') {
  294.         topIndex = this.top4Indexes[2];
  295.       } else if (typeof (this.top4Indexes[1]) !== 'undefined') {
  296.         topIndex = this.top4Indexes[1];
  297.       } else if (typeof (this.top4Indexes[0]) !== 'undefined') {
  298.         topIndex = this.top4Indexes[0];
  299.       }
  300.  
  301.       chart.setSelection([{ row: topIndex - this.factor }]);
  302.       this.chosenGraphPoint = this.preStockData[this.factor + chart.getSelection()[0]['row']];
  303.     }
  304.  
  305.   }
  306.  
  307.  
  308.   changeView(_period, section: number): void {
  309.     if (this.canDraw) {
  310.       // emit yield change:
  311.       if (_period === 'Y') { // TODO: make 'Y' as an 'S' in the app?
  312.         this.stockService.yieldNotifyer().next('S');
  313.       } else {
  314.         this.stockService.yieldNotifyer().next(_period);
  315.       }
  316.  
  317.       // if (_period === 'W' && this.timeFrame[0] === 30) { // chosen 'W' after 'M' was selected.
  318.       //   const timeFrameCopy = this.timeFrame;
  319.       //   const dataTableLengthCopy = this.dataTableLength;
  320.       // }
  321.  
  322.       let arr = clone(this.dataTable);
  323.       arr = (arr);
  324.       let days = 0;
  325.       let index = 0;
  326.       switch (_period) {
  327.         case 'W': {
  328.           days = 7;
  329.           index = 0;
  330.           this.period = 'W';
  331.           break;
  332.         }
  333.         case 'M': { days = 30; index = 1; this.period = 'M'; break; }
  334.         case 'Y': { days = this.dataTable['length']; index = 2; this.period = 'Y'; break; }
  335.       }
  336.       this.days = days;
  337.       // responsible for 'W' 'M' 'Y' selection
  338.       const periodChildren = this.periodSort['nativeElement'].children;
  339.       for (let i = 0; i < periodChildren['length']; i++) {
  340.         this.renderer.removeClass(periodChildren[i], 'active');
  341.       }
  342.       this.renderer.addClass(periodChildren[index], 'active');
  343.  
  344.       this.timeFrame = chunk(arr, days); // chunks of days according to period
  345.       if (_period === 'M') {
  346.         this.tfCopy = this.timeFrame['length'];
  347.       } else if (_period === 'W' && this.firstTimerCounter > 0) {
  348.         this.tfCopy = this.timeFrame['length'];
  349.       }
  350.       const dataCopy = clone(this.dataTable);
  351.  
  352.  
  353.       // case for aggregation of week with month
  354.       let monthDifference;
  355.       let weeksInTotal;
  356.       if (_period === 'W' && this.firstTimerCounter === 0) { // chosen 'W' after 'M' was selected.
  357.         monthDifference = (this.tfCopy - this.timeFrameLength) - 1; // converting months to weeks difference.
  358.         weeksInTotal = monthDifference * 4;
  359.         this.firstTimerCounter++;
  360.       } else if (_period === 'W' && this.firstTimerCounter > 0) {
  361.         weeksInTotal = 0;
  362.       }
  363.  
  364.       if (section === -1) {
  365.         this.timeFrameLength = this.timeFrame['length'] - 1;
  366.       } else {
  367.         this.timeFrameLength = section;
  368.       }
  369.       this.stockAnalysisService.setTimeFrameLength(this.timeFrameLength);
  370.  
  371.       if (_period === 'W') {
  372.         this.timeFrameLength -= weeksInTotal;
  373.       }
  374.  
  375.       this.dataTable = (this.timeFrame[this.timeFrameLength]);
  376.       this.factor = this.timeFrameLength * days; // not for use yet.
  377.       this.dataTableLength = this.timeFrame[this.timeFrameLength]['length']; // used to track previous length of dataTable for onResize()
  378.       this.showProperAxis();
  379.       this.drawBasic();
  380.       this.dataTable = dataCopy; // return to original full array ('Y' aka season)
  381.  
  382.     }
  383.   }
  384.  
  385.  
  386.   showProperAxis() {
  387.     if (window.innerWidth < 420) {
  388.       this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM';
  389.     } else if (window.innerWidth < 760) {
  390.       this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MM. yy\'';
  391.     } else { this.stockAnalysisService.getOptionsY()['hAxis']['format'] = 'MMM d, yyyy'; }
  392.   }
  393.  
  394.   selectListener(chart, data) {
  395.     google.visualization.events.addListener(chart, 'select', (e) => {
  396.       try {
  397.         const stringDateArray1 = new Date(data.getValue(chart.getSelection()[0]['row'], 0)).toLocaleString().split(',')[0].split('/');
  398.         const stringDateArray2 = new Date(data.getValue(chart.getSelection()[0]['row'], 0)).toLocaleString().split(',')[0].split('.');
  399.         let stringDateArray: any;
  400.         if (stringDateArray1.length > 1) {
  401.           stringDateArray = stringDateArray1;
  402.         } else { stringDateArray = stringDateArray2; }
  403.  
  404.         if (stringDateArray[0].length === 1) {
  405.           stringDateArray[0] = '0' + stringDateArray[0];
  406.         }
  407.         if (stringDateArray[1]['length'] === 1) {
  408.           stringDateArray[1] = '0' + stringDateArray[1];
  409.         }
  410.         const stringDate = stringDateArray[2] + '-' + stringDateArray[0] + '-' + stringDateArray[1];
  411.         console.log(data.getValue(chart.getSelection()[0]['row'], 2));
  412.         this.newsService.getNewsForTeamByDate(this.stock['id'].toString(), stringDate)
  413.           .then(res => console.log(res));
  414.  
  415.         console.log(chart.getSelection()[0]['row']);
  416.         this.chosenGraphPoint = this.preStockData[this.factor + chart.getSelection()[0]['row']];
  417.         console.log(this.chosenGraphPoint);
  418.         console.log(this.factor + chart.getSelection()[0]['row']);
  419.  
  420.       } catch (e) { }
  421.  
  422.  
  423.     });
  424.   }
  425.  
  426.   readyListener(chart, data) {
  427.     // TODO: only in case of 'Y' condition later? or case 'letter' is enough...
  428.  
  429.     // if (this.period === 'Y') {
  430.     //   Array.prototype.forEach.call(document.getElementById('line_chart').getElementsByTagName('text'), (text, index) => {
  431.     //     for (let i = 0; i < data.getNumberOfRows(); i++) {
  432.     //       if ((text.getAttribute('text-anchor') === 'middle')) {
  433.     //         switch (text.innerHTML) {
  434.     //           case 'W':
  435.     //             text.parentNode.firstElementChild.attributes[8].value = '#7CFC00';
  436.     //             break;
  437.     //           case 'L':
  438.     //             text.parentNode.firstElementChild.attributes[8].value = '#FF0000';
  439.     //             break;
  440.  
  441.     //           case 'D':
  442.     //             text.parentNode.firstElementChild.attributes[8].value = '#D3D3D3';
  443.     //             break;
  444.     //         }
  445.     //       }
  446.     //     }
  447.     //   });
  448.     // } else if (this.period === 'W') {
  449.     //   Array.prototype.forEach.call(document.getElementById('line_chart').getElementsByTagName('text'), (text, index) => {
  450.     //     for (let i = 0; i < data.getNumberOfRows(); i++) {
  451.     //       if ((text.getAttribute('text-anchor') === 'middle')) {
  452.     //         // const score = text.innerHTML.split(' ');
  453.     //         // const newScore = score[0].substring(1, score[0].length - 2);
  454.     //         // const isolatedScore = newScore.split(':');
  455.  
  456.     //         switch (text.innerHTML.split(' ')[2]) {
  457.     //           case 'W':
  458.     //             text.parentNode.firstElementChild.attributes[8].value = '#7CFC00';
  459.     //             break;
  460.     //           case 'L':
  461.     //             text.parentNode.firstElementChild.attributes[8].value = '#FF0000';
  462.     //             break;
  463.  
  464.     //           case 'D':
  465.     //             text.parentNode.firstElementChild.attributes[8].value = '#D3D3D3';
  466.     //             break;
  467.     //         }
  468.     //       }
  469.     //     }
  470.     //   });
  471.     // } else if (this.period === 'M') {
  472.     //   Array.prototype.forEach.call(document.getElementById('line_chart').getElementsByTagName('text'), (text, index) => {
  473.     //     for (let i = 0; i < data.getNumberOfRows(); i++) {
  474.     //       if ((text.getAttribute('text-anchor') === 'middle')) {
  475.  
  476.     //         switch (text.innerHTML.split(' ')[2]) {
  477.     //           case 'W':
  478.     //             text.parentNode.firstElementChild.attributes[8].value = '#7CFC00';
  479.     //             text.innerHTML = text.innerHTML.substring(0, text.innerHTML.length - 2);
  480.     //             break;
  481.     //           case 'L':
  482.     //             text.parentNode.firstElementChild.attributes[8].value = '#FF0000';
  483.     //             text.innerHTML = text.innerHTML.substring(0, text.innerHTML.length - 2);
  484.     //             break;
  485.  
  486.     //           case 'D':
  487.     //             text.parentNode.firstElementChild.attributes[8].value = '#D3D3D3';
  488.     //             text.innerHTML = text.innerHTML.substring(0, text.innerHTML.length - 2);
  489.     //             break;
  490.     //         }
  491.     //       }
  492.     //     }
  493.     //   });
  494.     // }
  495.  
  496.     // });
  497.   }
  498.  
  499.   fetchStockDaily() {
  500.     const dt = reverse(this.dataTable);
  501.     const dtArr = []; // will contain per each day its full data. array of stockItem
  502.     const dtLength = dt['length'];
  503.     for (let i = 0; i < dtLength; i++) { // TODO: solve 1 last missing index
  504.       const stockItem = {};
  505.  
  506.       if (i === 0) {
  507.         stockItem['date'] = dt[i][0];
  508.         stockItem['stockValue'] = (dt[i][1]).toFixed(2);
  509.         stockItem['dailyYield'] = '0.00%';
  510.         stockItem['changeReason'] = [{ phrase: '', impact: 0.00 }];
  511.         dtArr.push(stockItem);
  512.       } else if (i === dt['length'] - 1) {
  513.         stockItem['date'] = dt[i][0];
  514.         stockItem['stockValue'] = (dt[i][1]).toFixed(2);
  515.         let dailyYield;
  516.         let yieldSign = '';
  517.         if (dt[i][1] - dt[i - 1][1] > 0) {
  518.           yieldSign = '+';
  519.         }
  520.         const fixedYield = (dt[i][1] - dt[i - 1][1]).toFixed(2);
  521.         dailyYield = yieldSign + (fixedYield) + '%';
  522.         stockItem['dailyYield'] = dailyYield;
  523.  
  524.         // change reason:
  525.         const changeReason = [];
  526.         const game = dt[i][2]['games'];
  527.         if (game) {
  528.           let outcome = game[0]['outcome'];
  529.           if (outcome === 'W') {
  530.             outcome = 'WON';
  531.           } else if (outcome === 'L') {
  532.             outcome = 'LOST';
  533.           } else if (outcome === 'D') { outcome = 'DRAW'; }
  534.           const competition = game[0]['competition'];
  535.           const score = game[0]['score'];
  536.           const opponent = game[0]['opponent'];
  537.           const phrase = outcome + ' ' + competition + ' game by ' + score + ' against ' + opponent;
  538.           const impact = game[0]['impact'];
  539.           changeReason.push({ phrase: phrase, impact: impact });
  540.         }
  541.         stockItem['changeReason'] = changeReason;
  542.         dtArr.push(stockItem);
  543.       } else {
  544.         // ###HEADER###
  545.         stockItem['date'] = dt[i][0];
  546.         stockItem['stockValue'] = (dt[i][1]).toFixed(2);
  547.         let dailyYield;
  548.         let yieldSign = '';
  549.         if (dt[i][1] - dt[i - 1][1] > 0) {
  550.           yieldSign = '+';
  551.         }
  552.         const fixedYield = (dt[i][1] - dt[i - 1][1]).toFixed(2);
  553.         dailyYield = yieldSign + (fixedYield) + '%';
  554.         stockItem['dailyYield'] = dailyYield;
  555.  
  556.         // ###CHANGE REASON###
  557.         const changeReason = [];
  558.  
  559.         // Event outcome:
  560.         const game = dt[i][2]['games'];
  561.  
  562.         if (game) {
  563.           let outcome = game[0]['outcome'];
  564.           if (outcome === 'W') {
  565.             outcome = 'WON';
  566.           } else if (outcome === 'L') {
  567.             outcome = 'LOST';
  568.           } else if (outcome === 'D') { outcome = 'DRAW'; }
  569.           const competition = game[0]['competition'];
  570.           const score = game[0]['score'];
  571.           const opponent = game[0]['opponent'];
  572.           const phrase = outcome + ' ' + competition + ' game by ' + score + ' against ' + opponent;
  573.           const impact = parseFloat(game[0]['impact']);
  574.           let color: string;
  575.           if (impact > 0) {
  576.             color = 'green';
  577.           } else if (impact < 0) {
  578.             color = 'red';
  579.           }
  580.           changeReason.push({ phrase: phrase, impact: impact, color: color });
  581.         }
  582.  
  583.         const outrights = dt[i][2]['outrights'];
  584.  
  585.         // Outright changed:
  586.         for (let j = 0; j < outrights['length']; j++) {
  587.           if (parseFloat(outrights[j]['impact']) !== 0 && (typeof (outrights[j]['fulfilled']) === 'undefined')) {
  588.             const competition = outrights[j]['competition'];
  589.             const outright = outrights[j]['outright'];
  590.             let direction;
  591.             let phrase = '';
  592.             if (parseFloat(outrights[j]['impact']) > 0) {
  593.               direction = 'better';
  594.               phrase = 'Expectations for the ' + competition + ' ' + outright + ' got ' + direction;
  595.             } else if (parseFloat(outrights[j]['impact']) < 0) {
  596.               direction = 'worse';
  597.               phrase = 'Expectations for the ' + competition + ' ' + outright + ' got ' + direction;
  598.             }
  599.             const impact = parseFloat(outrights[j]['impact']);
  600.             let color: string;
  601.             if (impact > 0) {
  602.               color = 'green';
  603.             } else if (impact < 0) {
  604.               color = 'red';
  605.             }
  606.             changeReason.push({ phrase: phrase, impact: impact, color: color });
  607.           }
  608.         }
  609.         // Outright achieved: League + Outright obsolete: League + Outright obsolete: League relegated
  610.         for (let j = 0; j < outrights['length']; j++) {
  611.           if (i > 0) {
  612.             if (outrights[j]['competition'] === 'premier-league' &&
  613.               (parseFloat(dt[i][2]['outrights'][j]['fulfilled']) === 1 &&
  614.                 (typeof (dt[i - 1][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // achieved
  615.               if (outrights[j]['outright'] === 'to-stay-up') {
  616.                 const competition = outrights[j]['competition'];
  617.                 const phrase = 'Relegated from the  ' + competition;
  618.                 const impact = parseFloat(outrights[j]['impact']);
  619.                 let color: string;
  620.                 if (impact > 0) {
  621.                   color = 'green';
  622.                 } else if (impact < 0) {
  623.                   color = 'red';
  624.                 }
  625.                 changeReason.push({ phrase: phrase, impact: impact, color: color });
  626.               } else {
  627.                 const competition = outrights[j]['competition'];
  628.                 const outright = outrights[j]['outright'];
  629.                 const phrase = 'Secured ' + competition + ' ' + outright + ' ranking';
  630.                 const impact = parseFloat(outrights[j]['impact']);
  631.                 let color: string;
  632.                 if (impact > 0) {
  633.                   color = 'green';
  634.                 } else if (impact < 0) {
  635.                   color = 'red';
  636.                 }
  637.                 changeReason.push({ phrase: phrase, impact: impact, color: color });
  638.               }
  639.             } else if (outrights[j]['competition'] === 'premier-league' &&
  640.               (parseFloat(dt[i][2]['outrights'][j]['fulfilled']) === 0 &&
  641.                 (typeof (dt[i - 1][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // obsolete
  642.               const competition = dt[i][2]['outrights'][j]['competition'];
  643.               const outright = dt[i][2]['outrights'][j]['outright'];
  644.               const phrase = competition + ' ' + outright + ' ranking was not secured';
  645.               const impact = parseFloat(outrights[j]['impact']);
  646.               let color: string;
  647.               if (impact > 0) {
  648.                 color = 'green';
  649.               } else if (impact < 0) {
  650.                 color = 'red';
  651.               }
  652.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  653.             }
  654.           } else {
  655.             if (outrights[j]['competition'] === 'premier-league' &&
  656.               (parseFloat(dt[i + 1][2]['outrights'][j]['fulfilled']) === 1 &&
  657.                 (typeof (dt[i][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // achieved
  658.               if (outrights[j]['outright'] === 'to-stay-up') {
  659.                 const competition = outrights[j]['competition'];
  660.                 const phrase = 'Relegated from the  ' + competition;
  661.                 const impact = parseFloat(outrights[j]['impact']);
  662.                 let color: string;
  663.                 if (impact > 0) {
  664.                   color = 'green';
  665.                 } else if (impact < 0) {
  666.                   color = 'red';
  667.                 }
  668.                 changeReason.push({ phrase: phrase, impact: impact, color: color });
  669.               } else {
  670.                 const competition = outrights[j]['competition'];
  671.                 const outright = outrights[j]['outright'];
  672.                 const phrase = 'Secured ' + competition + ' ' + outright + ' ranking';
  673.                 const impact = parseFloat(outrights[j]['impact']);
  674.                 let color: string;
  675.                 if (impact > 0) {
  676.                   color = 'green';
  677.                 } else if (impact < 0) {
  678.                   color = 'red';
  679.                 }
  680.                 changeReason.push({ phrase: phrase, impact: impact, color: color });
  681.               }
  682.             } else if (outrights[j]['competition'] === 'premier-league' &&
  683.               (parseFloat(dt[i + 1][2]['outrights'][j]['fulfilled']) === 0 &&
  684.                 (typeof (dt[i][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // obsolete
  685.               const competition = dt[i][2]['outrights'][j]['competition'];
  686.               const outright = dt[i][2]['outrights'][j]['outright'];
  687.               const phrase = competition + ' ' + outright + ' ranking was not secured';
  688.               const impact = parseFloat(outrights[j]['impact']);
  689.               let color: string;
  690.               if (impact > 0) {
  691.                 color = 'green';
  692.               } else if (impact < 0) {
  693.                 color = 'red';
  694.               }
  695.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  696.             }
  697.           }
  698.         }
  699.  
  700.         // Outright achieved: Knockout stage + Outright obsolete: Cup (group or knockout)
  701.         for (let j = 0; j < outrights['length']; j++) {
  702.           if (i > 0) {
  703.             if (outrights[j]['competition'] !== 'premier-league' &&
  704.               (parseFloat(dt[i][2]['outrights'][j]['fulfilled']) === 1 &&
  705.                 (typeof (dt[i - 1][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // achieved
  706.               const competition = outrights[j]['competition'];
  707.               const phrase = 'Qualified for the ' + competition + ' knockout phase';
  708.               const impact = parseFloat(outrights[j]['impact']);
  709.               let color: string;
  710.               if (impact > 0) {
  711.                 color = 'green';
  712.               } else if (impact < 0) {
  713.                 color = 'red';
  714.               }
  715.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  716.             } else if (outrights[j]['competition'] !== 'premier-league' &&
  717.               (parseFloat(dt[i][2]['outrights'][j]['fulfilled']) === 0 &&
  718.                 (typeof (dt[i - 1][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // obsolete
  719.               const competition = outrights[j]['competition'];
  720.               const phrase = 'Knocked-out of the ' + competition;
  721.               const impact = parseFloat(outrights[j]['impact']);
  722.               let color: string;
  723.               if (impact > 0) {
  724.                 color = 'green';
  725.               } else if (impact < 0) {
  726.                 color = 'red';
  727.               }
  728.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  729.             }
  730.           } else {
  731.             if (outrights[j]['competition'] !== 'premier-league' &&
  732.               (parseFloat(dt[i + 1][2]['outrights'][j]['fulfilled']) === 1 &&
  733.                 (typeof (dt[i][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // achieved
  734.               const competition = outrights[j]['competition'];
  735.               const phrase = 'Qualified for the ' + competition + ' knockout phase';
  736.               const impact = parseFloat(outrights[j]['impact']);
  737.               let color: string;
  738.               if (impact > 0) {
  739.                 color = 'green';
  740.               } else if (impact < 0) {
  741.                 color = 'red';
  742.               }
  743.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  744.             } else if (outrights[j]['competition'] !== 'premier-league' &&
  745.               (parseFloat(dt[i + 1][2]['outrights'][j]['fulfilled']) === 0 &&
  746.                 (typeof (dt[i][2]['outrights'][j]['fulfilled']) === 'undefined'))) { // obsolete
  747.               const competition = outrights[j]['competition'];
  748.               const phrase = 'Knocked-out of the ' + competition;
  749.               const impact = parseFloat(outrights[j]['impact']);
  750.               let color: string;
  751.               if (impact > 0) {
  752.                 color = 'green';
  753.               } else if (impact < 0) {
  754.                 color = 'red';
  755.               }
  756.               changeReason.push({ phrase: phrase, impact: impact, color: color });
  757.             }
  758.           }
  759.  
  760.         }
  761.  
  762.         // adding all of the data of changeReason for specific item:
  763.         stockItem['changeReason'] = changeReason;
  764.         dtArr.push(stockItem);
  765.       }
  766.       // adding all data of the iterate as a stockItem:
  767.     }
  768.     this.preStockData = (dtArr);
  769.   }
  770.  
  771. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement