Exemple #1
0
        public async Task <IActionResult> PutDailyPrice(int id, DailyPrice daily)
        {
            // PUT (i.e update) price record
            _logger.LogInformation($"START: PUT for id '{id}'.");

            if (id != daily.Id)
            {
                return(BadRequest());
            }

            _context.Entry(daily).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DailyPriceExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            _logger.LogInformation($"END: PUT for id '{id}'.");
            return(NoContent());
        }
Exemple #2
0
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            // fill out form with selected price data
            try
            {
                string msg = "";

                // check that an item has been selected
                if (this.cboPrice.SelectedIndex == -1 || this.cboPrice.SelectedIndex == 0)
                {
                    // if not return
                    // clear controls
                    ClearControls();
                    msg = "Error. Select a Daily Price from the list first";
                    SetValidationText(false, msg);
                    this.cboPrice.Focus();
                    return;
                }

                // check that item selected is a real value
                int id;
                if (!int.TryParse(this.cboPrice.SelectedValue.ToString(), out id))
                {
                    // if not return
                    // clear controls
                    ClearControls();
                    msg = "Error. Select a Daily Price from the list first";
                    SetValidationText(false, msg);
                    this.cboPrice.Focus();
                    return;
                }

                // delete the record from database via API
                DailyPrice outputPrice = await Api.DeleteDailyPrice(id);

                // show blank record on screen
                ClearControls();

                // refresh the drop list
                InitPriceListCombo(false);

                // clear the select price drop list
                this.cboPrice.ResetText();
                this.cboPrice.SelectedIndex = -1;

                this.dateTimePicker.CustomFormat = " ";

                // set the focus
                this.txtSymbol.Focus();

                // show success message
                msg = "Success. The Daily Price record has been deleted from database ";
                SetValidationText(true, msg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #3
0
        // importPrice->priceData
        private static void AddImportPrice(data.importDS.importPriceDataTable importPriceTbl,
                                           DailyPrice dailyPrice, data.baseDS.priceDataDataTable priceDataTbl)
        {
            data.baseDS.priceDataSumRow dailyPriceRow;
            data.baseDS.priceDataRow    priceDataRow;
            decimal volume = 0;

            for (int idx = 0; idx < importPriceTbl.Count; idx++)
            {
                //Invalid price, ignore
                if (importPriceTbl[idx].closePrice <= 0)
                {
                    continue;
                }

                volume = importPriceTbl[idx].volume;
                // If this is totail volume then minus the last volume to get the real volume in the period
                if (importPriceTbl[idx].isTotalVolume)
                {
                    dailyPriceRow = dailyPrice.GetData(importPriceTbl[idx]);
                    if (dailyPriceRow != null)
                    {
                        volume -= dailyPriceRow.volume;
                    }
                    if (volume <= 0)
                    {
                        continue;
                    }
                }

                priceDataRow = priceDataTbl.NewpriceDataRow();
                commonClass.AppLibs.InitData(priceDataRow);
                priceDataRow.onDate     = importPriceTbl[idx].onDate;
                priceDataRow.stockCode  = importPriceTbl[idx].stockCode;
                priceDataRow.openPrice  = importPriceTbl[idx].openPrice;
                priceDataRow.lowPrice   = importPriceTbl[idx].lowPrice;
                priceDataRow.highPrice  = importPriceTbl[idx].highPrice;
                priceDataRow.closePrice = importPriceTbl[idx].closePrice;
                priceDataRow.volume     = volume;
                //Fix other invalid price
                if (priceDataRow.highPrice <= 0)
                {
                    priceDataRow.highPrice = priceDataRow.closePrice;
                }
                if (priceDataRow.lowPrice <= 0)
                {
                    priceDataRow.highPrice = priceDataRow.lowPrice;
                }
                if (priceDataRow.openPrice <= 0)
                {
                    priceDataRow.highPrice = priceDataRow.openPrice;
                }
                priceDataTbl.AddpriceDataRow(priceDataRow);

                //Update the last row
                dailyPrice.UpdateData(importPriceTbl[idx]);
            }
        }
Exemple #4
0
        //Takes the Json file and saves it to DailyPrices Table
        public async Task UpdateDatabase(string jsonString)
        {
            JObject           jsonObject = JObject.Parse(jsonString);
            List <DailyPrice> rows       = new List <DailyPrice>();

            var jsonRows = jsonObject["Time Series (Daily)"].Children().ToList();

            foreach (var jsonRow in jsonRows)
            {
                JObject rowObject = JObject.Parse("{" + jsonRow.ToString() + "}");

                //Price Date extracted from the Key to be reused later
                var priceDate = rowObject.Properties().First().Name;

                //Get DailyPrice object to be saved to a row
                DailyPrice dailyPrice = new DailyPrice()
                {
                    Symbol           = jsonObject["Meta Data"]["2. Symbol"].ToString(),
                    PriceDate        = DateTime.Parse(priceDate),
                    LastUpdatedDate  = DateTime.Parse(jsonObject["Meta Data"]["3. Last Refreshed"].ToString()),
                    Open             = decimal.Parse(rowObject[priceDate]["1. open"].ToString()),
                    High             = decimal.Parse(rowObject[priceDate]["2. high"].ToString()),
                    Low              = decimal.Parse(rowObject[priceDate]["3. low"].ToString()),
                    Close            = decimal.Parse(rowObject[priceDate]["4. close"].ToString()),
                    AdjClose         = decimal.Parse(rowObject[priceDate]["5. adjusted close"].ToString()),
                    Volume           = int.Parse(rowObject[priceDate]["6. volume"].ToString()),
                    DividendAmount   = decimal.Parse(rowObject[priceDate]["7. dividend amount"].ToString()),
                    SplitCoefficient = decimal.Parse(rowObject[priceDate]["8. split coefficient"].ToString())
                };

                //If the row already exists, then update all data except Id
                if (_context.DailyPrices.Any(x => x.Symbol == dailyPrice.Symbol && x.PriceDate == dailyPrice.PriceDate))
                {
                    var existingRow = _context.DailyPrices.Where(x => x.Symbol == dailyPrice.Symbol && x.PriceDate == dailyPrice.PriceDate).FirstOrDefault();
                    existingRow.LastUpdatedDate  = dailyPrice.LastUpdatedDate;
                    existingRow.Open             = dailyPrice.Open;
                    existingRow.High             = dailyPrice.High;
                    existingRow.Low              = dailyPrice.Low;
                    existingRow.Close            = dailyPrice.Close;
                    existingRow.AdjClose         = dailyPrice.AdjClose;
                    existingRow.Volume           = dailyPrice.Volume;
                    existingRow.DividendAmount   = dailyPrice.DividendAmount;
                    existingRow.SplitCoefficient = dailyPrice.SplitCoefficient;
                }
                else
                {
                    rows.Add(dailyPrice);
                }
            }
            _context.DailyPrices.AddRange(rows);
            await _context.SaveChangesAsync();
        }
Exemple #5
0
        private async void btnCancel_Click(object sender, EventArgs e)
        {
            // fill out form with selected price data
            try
            {
                string msg = "";

                // check that an item has been selected
                if (this.cboPrice.SelectedIndex == -1 || this.cboPrice.SelectedIndex == 0)
                {
                    // if not return
                    // clear controls
                    ClearControls();
                    msg = "Error. Nothing to cancel";
                    SetValidationText(false, msg);
                    this.cboPrice.Focus();
                    return;
                }

                // check that an item has been selected
                int id;
                if (!int.TryParse(this.cboPrice.SelectedValue.ToString(), out id))
                {
                    // if not return
                    // clear controls
                    ClearControls();
                    msg = "Error. Nothing to cancel";
                    SetValidationText(false, msg);
                    this.cboPrice.Focus();
                    return;
                }

                // get the orignial record from database via API
                DailyPrice outputPrice = await Api.GetDailyPrice(id);

                // show record
                GoToRecord(outputPrice);

                // set the focus
                this.txtSymbol.Focus();

                // show success message
                msg = "The form has been reset to original values";
                SetValidationText(true, msg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #6
0
        public async Task <ActionResult <DailyPrice> > PostDaily(DailyPrice daily)
        {
            // POST (i.e insert) a price record
            try {
                _logger.LogInformation($"START: POST price record.");

                _context.DailyPrice.Add(daily);
                await _context.SaveChangesAsync();

                _logger.LogInformation($"END: POST price record.");
                return(CreatedAtAction("PostDaily", new { id = daily.Id }, daily));
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Exception while posting a new price record. Check the combination of 'Date','Stock Symbol' and 'Stock Exchange' are unique.");
                return(StatusCode(500, "An error occured while trying to add a new price record. Check the combination of 'Date','Stock Symbol' and 'Stock Exchange' are unique."));
            }
        }
Exemple #7
0
        private async void cboPrice_SelectedIndexChanged(object sender, EventArgs e)
        {
            // fill out form with selected price data
            try
            {
                // check that an item has been selected
                var id = 0;
                if (this.cboPrice.SelectedIndex == -1 || this.cboPrice.SelectedValue.ToString() == "-1")
                {
                    // nothing selected, return
                    ClearControls(); // clear all control values
                    return;
                }

                // check that selected value is integer
                if (!int.TryParse(this.cboPrice.SelectedValue.ToString(), out id))
                {
                    // if not return
                    // clear controls
                    ClearControls(); // clear all control values
                    return;
                }

                // get the record from database via API
                DailyPrice outputPrice = await Api.GetDailyPrice(id);

                // clear controls
                ClearControls();

                // show record
                GoToRecord(outputPrice);

                // set the focus
                this.txtSymbol.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #8
0
        public void VerifyClassAttributes()
        {
            CheckPropertyValidation cpv = new CheckPropertyValidation();

            // create the test object
            DailyPrice dailyPrice = new DailyPrice();

            dailyPrice.date                  = new DateTime(2019, 1, 1);
            dailyPrice.stock_symbol          = "TEST";
            dailyPrice.stock_price_open      = 50;
            dailyPrice.stock_price_close     = 100;
            dailyPrice.stock_price_low       = 10;
            dailyPrice.stock_price_high      = 100;
            dailyPrice.stock_price_adj_close = 100;
            dailyPrice.stock_volume          = 1000;
            dailyPrice.stock_exchange        = "NYSE";

            // test there arent any validation errors
            var errorcount = cpv.testValidation(dailyPrice).Count();

            Assert.AreEqual(0, errorcount);
        }
Exemple #9
0
        private void GoToRecord(DailyPrice price)
        {
            // set the control values for a daily price record

            try
            {
                // show record
                this.dateTimePicker.Value        = Convert.ToDateTime(price.date);
                this.dateTimePicker.CustomFormat = "dd/MM/yyyy";
                this.txtSymbol.Text   = price.stock_symbol;
                this.txtOpen.Text     = price.stock_price_open.ToString();
                this.txtClose.Text    = price.stock_price_close.ToString();
                this.txtLow.Text      = price.stock_price_low.ToString();
                this.txtHigh.Text     = price.stock_price_high.ToString();
                this.txtAdjClose.Text = price.stock_price_adj_close.ToString();
                this.txtVolume.Text   = price.stock_volume.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #10
0
        private DailyPrice PredictSingle(DailyPrice input, DateTime date, ActivationNetwork model = null)
        {
            var _model = model ?? Global.Model;

            _predictList = new List <DailyPrice>();
            var retVal = new DailyPrice();

            DataHelper.DataHelper.CloneObject(input, retVal);
            retVal.CloseDate       = date;
            retVal.PriorClosePrice = retVal.ClosePrice;
            _predictList.Add(retVal);

            double[][] _input = DataHelper.DataHelper.GetInputArray(_predictList);
            var        output = new double[1];

            output[0] = _model.Compute(_input[0]).FirstOrDefault();
            _predictList[0].Profit          = output[0];
            _predictList[0].PriorClosePrice = _predictList[0].ClosePrice;
            _predictList[0].ClosePrice      = Math.Round(_predictList[0].ClosePrice * (_predictList[0].Profit + 1));
            _predictList[0].AvrPrice        = _predictList[0].ClosePrice;

            return(_predictList[0]);
        }
Exemple #11
0
        public IReadOnlyList <Car> GetAllCars(string autoKlasse)
        {
            var cars = new List <Car>();

            _mySqlConnection.Open();
            using (var cmd = _mySqlConnection.CreateCommand())
            {
                cmd.CommandText = "SELECT * FROM(carrentdb.Cars INNER JOIN carrentdb.CarClass ON Cars.FK_CarClassId = CarClass.CarClassId)" +
                                  "INNER JOIN carrentdb.DailyPrice ON CarClass.FK_DailyPriceId = DailyPrice.DailyPriceId WHERE CarClass.CarClass=@autoKlasse";
                cmd.Parameters.AddWithValue("@autoKlasse", autoKlasse);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var dailyPrice = new DailyPrice(
                            reader.GetString("Waehrung"),
                            reader.GetDecimal("Preis")
                            );

                        var carClass = new CarClass(
                            (AutoKlasse)Enum.Parse(typeof(AutoKlasse), reader.GetString("CarClass")),
                            dailyPrice
                            );

                        cars.Add(new Car(
                                     reader.GetString("Marke"),
                                     reader.GetString("Seriennummer"),
                                     reader.GetString("Farbe"),
                                     reader.GetBoolean("Vermietet"),
                                     carClass
                                     ));
                    }
                }
                return(cars);
            }
        }
Exemple #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            //using (ApplicationDbContext db = new ApplicationDbContext())
            //{
            //    db.Database.CreateIfNotExists();
            //}
            foreach (var path in Directory.GetFiles(@"D:\Work\Stock\samples\stock", "*.txt", SearchOption.TopDirectoryOnly))
            {
                FileInfo fi    = new FileInfo(path);
                var      lines = File.ReadAllLines(path, Encoding.Default);

                using (var db = new MongoDBContext())
                {
                    List <DailyPrice> list = new List <DailyPrice>();
                    for (int i = 2; i < lines.Length - 1; i++)
                    {
                        var item = DailyPrice.NewDailyPrice(lines[i]);
                        if (item == null)
                        {
                            continue;
                        }
                        item.Id   = Guid.NewGuid().ToString("N");
                        item.Code = fi.Name.Replace(fi.Extension, "");
                        list.Add(item);
                    }
                    if (list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            db.DataSet <DailyPrice>().Insert(item);
                        }
                    }
                }
                File.Move(fi.FullName, @"D:\Work\Stock\samples\OK\" + fi.Name);
            }
        }
Exemple #13
0
        // importPrice->priceData
        private static void AddImportPrice(data.importDS.importPriceDataTable importPriceTbl,
                                           DailyPrice dailyPrice,data.baseDS.priceDataDataTable priceDataTbl)
        {
            data.baseDS.priceDataSumRow dailyPriceRow;
            data.baseDS.priceDataRow priceDataRow;
            decimal volume = 0;
            for (int idx = 0; idx < importPriceTbl.Count; idx++)
            {
                //Invalid price, ignore
                if (importPriceTbl[idx].closePrice <= 0) continue;

                volume = importPriceTbl[idx].volume;
                // If this is totail volume then minus the last volume to get the real volume in the period
                if (importPriceTbl[idx].isTotalVolume)
                {
                    dailyPriceRow = dailyPrice.GetData(importPriceTbl[idx]);
                    if (dailyPriceRow != null)
                    {
                        volume -= dailyPriceRow.volume;
                    }
                    if (volume <= 0) continue;
                }

                priceDataRow = priceDataTbl.NewpriceDataRow();
                commonClass.AppLibs.InitData(priceDataRow);
                priceDataRow.onDate = importPriceTbl[idx].onDate;
                priceDataRow.stockCode = importPriceTbl[idx].stockCode;
                priceDataRow.openPrice = importPriceTbl[idx].openPrice;
                priceDataRow.lowPrice = importPriceTbl[idx].lowPrice;
                priceDataRow.highPrice = importPriceTbl[idx].highPrice;
                priceDataRow.closePrice = importPriceTbl[idx].closePrice;
                priceDataRow.volume = volume;
                //Fix other invalid price
                if (priceDataRow.highPrice <= 0)  priceDataRow.highPrice = priceDataRow.closePrice;
                if (priceDataRow.lowPrice <= 0) priceDataRow.highPrice = priceDataRow.lowPrice;
                if (priceDataRow.openPrice <= 0) priceDataRow.highPrice = priceDataRow.openPrice;
                priceDataTbl.AddpriceDataRow(priceDataRow);

                //Update the last row
                dailyPrice.UpdateData(importPriceTbl[idx]);
            }
        }
        private async void btnSubmit_Click(object sender, EventArgs e)
        {
            // submit the record to database via API

            try
            {
                string         msg         = "";
                DateTimePicker dteDate     = this.dateTimePicker;
                ComboBox       cboExchange = this.cboExchange;
                TextBox        txtSymbol   = this.txtSymbol;
                TextBox        txtOpen     = this.txtOpen;
                TextBox        txtClose    = this.txtClose;
                TextBox        txtLow      = this.txtLow;
                TextBox        txtHigh     = this.txtHigh;
                TextBox        txtAdjClose = this.txtAdjClose;
                TextBox        txtVolume   = this.txtVolume;

                // validation
                // --------------------------------------------------------------------------------------------------------
                // validate if its been saved already
                if (recordSavedYN)
                {
                    msg = "Record has already been saved. Please click 'Add New Daily Price' to clear the form.";
                    dteDate.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate date
                if (dteDate == null || string.IsNullOrWhiteSpace(dteDate.Text))
                {
                    msg = "Validation Error. Please select the Date.";
                    dteDate.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate exchange
                if (cboExchange == null || string.IsNullOrWhiteSpace(cboExchange.Text))
                {
                    msg = "Validation Error. Please select the Exchange.";
                    cboExchange.Focus();
                    cboExchange.DroppedDown = true;
                    SetValidationText(false, msg);
                    return;
                }

                // validate stock symbol
                if (txtSymbol == null || string.IsNullOrWhiteSpace(txtSymbol.Text))
                {
                    msg = "Validation Error. Please enter a Stock Symbol.";
                    txtSymbol.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate open is not null
                if (txtOpen == null || string.IsNullOrWhiteSpace(txtOpen.Text))
                {
                    msg = "Validation Error. Please enter an Open Price.";
                    txtOpen.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // convert input to correct data type
                decimal deciOpen;
                decimal deciClose;
                decimal deciLow;
                decimal deciHigh;
                decimal deciAdjClose;
                int     intVolume;

                // validate open is numeric
                if (!decimal.TryParse(txtOpen.Text, out deciOpen))
                {
                    msg = "Validation Error. Open Price must be numeric.";
                    txtOpen.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate close is not null
                if (txtClose == null || string.IsNullOrWhiteSpace(txtClose.Text))
                {
                    msg = "Validation Error. Please enter a Close Price.";
                    txtClose.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate close is numeric
                if (!decimal.TryParse(txtClose.Text, out deciClose))
                {
                    msg = "Validation Error. Close Price must be numeric.";
                    txtClose.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate low is not null
                if (txtLow == null || string.IsNullOrWhiteSpace(txtLow.Text))
                {
                    msg = "Validation Error. Please enter a Low Price.";
                    txtLow.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate low is numeric
                if (!decimal.TryParse(txtLow.Text, out deciLow))
                {
                    msg = "Validation Error. Low Price must be numeric.";
                    txtLow.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate high is not null
                if (txtHigh == null || string.IsNullOrWhiteSpace(txtHigh.Text))
                {
                    msg = "Validation Error. Please enter a High Price.";
                    txtHigh.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate high is numeric
                if (!decimal.TryParse(txtHigh.Text, out deciHigh))
                {
                    msg = "Validation Error. High Price must be numeric.";
                    txtHigh.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate adj close is not null
                if (txtAdjClose == null || string.IsNullOrWhiteSpace(txtAdjClose.Text))
                {
                    msg = "Validation Error. Please enter an Adjusted Close Price.";
                    txtAdjClose.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate adj close is numeric
                if (!decimal.TryParse(txtAdjClose.Text, out deciAdjClose))
                {
                    msg = "Validation Error. Adjusted Close must be numeric.";
                    txtAdjClose.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate volume is not null
                if (txtVolume == null || string.IsNullOrWhiteSpace(txtVolume.Text))
                {
                    msg = "Validation Error. Please enter Volume.";
                    txtVolume.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // validate volume is numeric
                if (!int.TryParse(txtVolume.Text, out intVolume))
                {
                    msg = "Validation Error. Volume must be a whole number only.";
                    txtVolume.Focus();
                    SetValidationText(false, msg);
                    return;
                }

                // end validation
                // --------------------------------------------------------------------------------------------------------


                // no validation errors. create the object and pass object to API method to update database
                // --------------------------------------------------------------------------------------------------------
                // show wait message
                msg = "Please wait...";
                SetValidationText(true, msg);

                // create the object
                DailyPrice dailyPrice = new DailyPrice();
                dailyPrice.date                  = dteDate.Value;
                dailyPrice.stock_symbol          = txtSymbol.Text;
                dailyPrice.stock_price_open      = deciOpen;
                dailyPrice.stock_price_close     = deciClose;
                dailyPrice.stock_price_low       = deciLow;
                dailyPrice.stock_price_high      = deciHigh;
                dailyPrice.stock_price_adj_close = deciAdjClose;
                dailyPrice.stock_volume          = intVolume;
                dailyPrice.stock_exchange        = cboExchange.Text;

                // save record to the database via an API call. pass in object. bject gets converted to JSON
                DailyPrice outputPrice = await Api.PostDailyPrice(dailyPrice);

                // show success message
                msg = "Success. Daily Price record successfully added to database.";
                SetValidationText(true, msg);
            }
            catch (Exception ex)
            {
                if (ex.Message == "InternalServerError")
                {
                    string msg = "API error.";
                    SetValidationText(false, msg);
                    MessageBox.Show("An error occurred. Please make sure the combination of 'Date', 'Exchange' & 'Stock Symbol' are unique.");
                }
                else if (ex.Message == "An error occurred while sending the request.")
                {
                    string msg = "API connection error.";
                    SetValidationText(false, msg);
                    MessageBox.Show("An error occurred with the following error message: '" + ex.Message + "'" + Environment.NewLine + Environment.NewLine + "The possible cause is not being able to connect to the API service. Make sure the service is running.");
                }
                else
                {
                    string msg = "API error.";
                    SetValidationText(false, msg);
                    MessageBox.Show(ex.Message);
                }
            }
        }