Exemple #1
0
        /// <summary>
        /// This function prepares then initiates the re-analysis of all articles
        /// currently stored in the database. It drops all article reviews for current
        /// user and sets all article in Database to not-analyzed.
        /// </summary>
        /// <param name="bw">BackgroundWorker to send to analyzeArticles function.</param>
        /// <returns></returns>
        public int reAnalyzeAllArticles(BackgroundWorker bw)
        {
            cDatabaseManager db = new cDatabaseManager();

            db.dropCurrentArticleReviews(cUser.UserID);
            db.setArticlesNotAnalyzed();
            return(analyzeArticles(bw));
        }
        /// <summary>
        /// This function calls the database manager class to register a new user
        /// with the credentials provided in the parameters.
        /// </summary>
        /// <param name="username">string of username for new account to be added.
        /// must be unique.</param>
        /// <param name="password">string of password encrypted using md5 hash for the
        /// account that is being created.</param>
        /// <returns>Returns true if account is successfully created.</returns>
        public bool registerUser(string username, string password)
        {
            bool             success = false;
            cDatabaseManager db      = new cDatabaseManager();

            success = db.registerUser(username, password);

            return(success);
        }
        /// <summary>
        /// This function searches for an old word in the dictionary and replaces
        /// the word with a new word, effectively modifying the word's entry.
        /// </summary>
        /// <param name="oldWord">string of the old word to search for</param>
        /// <param name="newWord">string of the new word to replace the old</param>
        /// <param name="weight">weight of the word being modified</param>
        /// <returns>True if successful</returns>
        public bool modifyWordInDictionary(string oldWord, string newWord, int weight)
        {
            bool modified = false;

            cDatabaseManager db = new cDatabaseManager();

            modified = db.modifyWordDictionary(oldWord, newWord, cUser.UserID, weight);

            return(modified);
        }
        /// <summary>
        /// This function accepts a word and communicates with the database
        /// manager to add the word to the currently logged in user's
        /// dictionary along with the weight
        /// </summary>
        /// <param name="wordToAdd">string of word to add to dictionary</param>
        /// <param name="weight">weight of word to add to dictionary</param>
        /// <returns>true if successful</returns>
        public bool addWordToDictionary(string wordToAdd, int weight)
        {
            bool added = false;

            cDatabaseManager db = new cDatabaseManager();

            added = db.addwordDictionary(wordToAdd, weight, cUser.UserID);

            return(added);
        }
        /// <summary>
        /// This function accepts a word and communicates with the database
        /// manager to remove the word from the currently logged in user's
        /// dictionary
        /// </summary>
        /// <param name="wordToDelete">string of word to remove from dictionary</param>
        /// <returns>true if successful</returns>
        public bool deleteWordFromDictionary(string wordToDelete)
        {
            bool deleted = false;

            cDatabaseManager db = new cDatabaseManager();

            deleted = db.deleteWordDictionary(wordToDelete, cUser.UserID);

            return(deleted);
        }
        /// <summary>
        /// This function calls the database manager class to validate a user's account
        /// that is attempting to log in to the program.
        /// </summary>
        /// <param name="username">username to be checked in the database for records.</param>
        /// <param name="password">encrypted password (md5 hash) associated with input
        /// username.</param>
        /// <returns>Returns true if the account is found.</returns>
        public int validateUser(string username, string password)
        {
            int success         = 0;
            cDatabaseManager db = new cDatabaseManager();

            success      = db.validateUser(username, password);
            cUser.UserID = success;

            return(success);
        }
        /// <summary>
        /// This function deletes all the user's currently saved stocks and calls the
        /// database manager to add rows in the table for each of the stocks selected to
        /// save effectively replacing old entries with new. does not add anything if the
        /// stocks list is empty, but it will still delete all currently saved stocks (if any).
        /// </summary>
        /// <param name="stocks">List of all stock ID's to add to the current User's saved
        /// stocks list. if empty, currently saved stocks are deleted and none are added.</param>
        public void saveNewStocks(List <int> stocks)
        {
            cDatabaseManager db = new cDatabaseManager();

            db.deleteStocksForUser(cUser.UserID);
            if (stocks.Count > 0)
            {
                db.saveStocksForUser(stocks, cUser.UserID);
            }
        }
        /// <summary>
        /// This function searches for a word in the current user's dictionary and
        /// changes the word's weight to the newly input weight
        /// </summary>
        /// <param name="word">Word who's weight is to be modified</param>
        /// <param name="newWeight">New weight of the word you are modifying</param>
        /// <returns>true if successful</returns>
        public bool modifyWeightInDictionary(string word, int newWeight)
        {
            bool modified = false;

            cDatabaseManager db = new cDatabaseManager();

            modified = db.modifyWeightDictionary(word, newWeight, cUser.UserID);

            return(modified);
        }
Exemple #9
0
 public cArticleScanner()
 {
     baseUrl            = new Uri("http://www.investopedia.com/markets/stock-analysis/");
     _db                = new cDatabaseManager();
     _lastArticleUpdate = _db.getLastArticleUpdateTime();
     if (_lastArticleUpdate.Year == 1997)
     {
         _articlesStored = false;
     }
 }
        /// <summary>
        /// Handler for generate graph button. Creates new form to display
        /// graph for the User based on parameters made on this form.
        /// </summary>
        /// <param name="sender">Default parameter</param>
        /// <param name="e">Default parameter</param>
        private void btn_CreateGraph_Click(object sender, EventArgs e)
        {
            //ensure atleast one stock is enabled & one graph mode is selected
            if ((stock_one_enabled || stock_two_enabled || stock_three_enabled) &&
                (cbValueOverTime.Checked || cbScoreOverTime.Checked))
            {
                fGraph graph = new fGraph();

                cDatabaseManager db = new cDatabaseManager();

                if (cbValueOverTime.Checked)                    //add selected curves to graph(s)
                {
                    if (stock_one_enabled)
                    {
                        var list = db.getStockPrices(stock_one);
                        graph.addCurve(list, stock_one_str, true, Color.Red);
                    }
                    if (stock_two_enabled)
                    {
                        var list = db.getStockPrices(stock_two);
                        graph.addCurve(list, stock_two_str, true, Color.Blue);
                    }
                    if (stock_three_enabled)
                    {
                        var list = db.getStockPrices(stock_three);
                        graph.addCurve(list, stock_three_str, true, Color.Green);
                    }
                }

                if (cbScoreOverTime.Checked)
                {
                    if (stock_one_enabled)
                    {
                        var list = db.getStockRatings(cUser.UserID, stock_one);
                        graph.addCurve(list, stock_one_str, false, Color.Red);
                    }
                    if (stock_two_enabled)
                    {
                        var list = db.getStockRatings(cUser.UserID, stock_two);
                        graph.addCurve(list, stock_two_str, false, Color.Blue);
                    }
                    if (stock_three_enabled)
                    {
                        var list = db.getStockRatings(cUser.UserID, stock_three);
                        graph.addCurve(list, stock_three_str, false, Color.Green);
                    }
                }
                graph.ShowDialog();                 //show the graph itself
            }
            else
            {
                MessageBox.Show("Must select at least one stock to graph and at least one mode to graph it", "Error");
            }
        }
Exemple #11
0
        /// <summary>
        /// This is called when the Graph button is pressed on the main screen. It opens
        /// the graph configuration screen so the user can generate a graph to view.
        /// </summary>
        /// <param name="sender">Default parameter.</param>
        /// <param name="e">Default parameter.</param>
        private void btnGraph_Click(object sender, EventArgs e)
        {
            cDatabaseManager dbm = new cDatabaseManager();

            if (dbm.getNumStockEntries() > 3)
            {
                fGraphConfig config = new fGraphConfig();
                config.ShowDialog();
            }
            else
            {
                DialogResult dialogResult = MessageBox.Show("There are no stocks found to graph! Please run stock price update first!",
                                                            "Warning!",
                                                            MessageBoxButtons.OK);
            }
        }
        /// <summary>
        /// Called when the add stock button is pressed. If the user has
        /// less than 20 stocks already saved, the add stock window appears
        /// and the user can select a new stock to add to their favorites list.
        /// </summary>
        /// <param name="sender">Default param.</param>
        /// <param name="e">Default param.</param>
        private void btn_AddStock_Click(object sender, EventArgs e)
        {
            if (gridView_SavedStocks.Rows.Count < 20)                   //if user has less than 20 stocks saved
            {
                fAddStock add = new fAddStock();

                if (add.ShowDialog() == DialogResult.OK)                 //open new stock window, check for close OK (no cancel)
                {
                    cDatabaseManager db = new cDatabaseManager();

                    List <int> save_stocks = new List <int>();
                    save_stocks.Add(add.sID);                        //get selected stock id from add stock window
                    db.saveStocksForUser(save_stocks, cUser.UserID); //save it to db
                    updateSavedStocksGrid();                         // update stock grid to reflect changes
                }
            }
            else
            {
                //more than 20 stocks saved
                MessageBox.Show("Cannot save more than 20 stocks", "Stop");
            }
        }
Exemple #13
0
        /// <summary>
        /// This function gets current prices for all stock symbols on the nasdaq exchange. It then stores
        /// all symbols and their prices in the database along with the current date.
        /// </summary>
        /// <param name="bw">BackgroundWorker to report progress to main thread</param>
        /// <returns>Returns true if stocks succcessfully are queried and new entries are created in the
        /// database.</returns>
        public int getCurrentQuotes(BackgroundWorker bw)
        {
            int success = -1;   //-1 = function failed

            //pull all nasdaq stocks for price record in database
            HttpWebRequest csv_req = (HttpWebRequest)WebRequest.Create("http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download");

            csv_req.KeepAlive       = false;
            csv_req.ProtocolVersion = HttpVersion.Version10;

            bw.ReportProgress(1);
            try
            {
                HttpWebResponse csv_resp = (HttpWebResponse)csv_req.GetResponse();
                bw.ReportProgress(2);

                //build response into reader then into string for filehelper to open
                StreamReader response_reader = new StreamReader(csv_resp.GetResponseStream());
                string       stock_csv       = response_reader.ReadToEnd();
                response_reader.Close();
                bw.ReportProgress(3);

                FileHelperEngine engine = new FileHelperEngine(typeof(cStock));
                cStock[]         res    = (cStock[])engine.ReadString(stock_csv); //build results into array for easy access
                bw.ReportProgress(4);

                //more stuffs just to ensure its working. must refactor this asap.
                cDatabaseManager db = new cDatabaseManager();

                bool update_prices = false;
                //ensure prices aren't updated too frequently
                if ((DateTime.Now - db.getLastStockUpdateTime()).TotalHours >= MIN_HOURS_BETWEEN_UPDATE)
                {
                    update_prices = true;
                }
                else
                {
                    success = -2;   //-2 = stocks already updated with past 12 hours
                    for (int i = 5; i < 100; ++i)
                    {
                        bw.ReportProgress(i);
                    }
                }

                if (update_prices == true)
                {
                    float percent = 0.0f;
                    int   count   = 0;
                    success = 1;    //1 = update success
                    foreach (cStock stock in res)
                    {
                        int stock_id = db.addStockSymbol(stock._symbol);          //add symbol

                        Decimal lastSale;                                         //used to convert string of most recent sale
                        if (Decimal.TryParse(stock._lastSalePrice, out lastSale)) //removes "n/a" entries
                        {
                            if (!db.addStockQuote(stock_id, lastSale))
                            {
                                success = -3; //-3 one or more stocks failed to insert price to db
                            }
                        }
                        percent = ((float)count / (float)res.Length) * 100f; //percent complete
                        if (percent < 5)                                     //acount for the 5 percent before loop begins
                        {
                            percent += 5 - percent;
                        }
                        bw.ReportProgress((int)percent);
                        ++count;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception caught stock quote retrieval & storage (probably can't access network):\n");
                Console.WriteLine(e.Message);
                success = -1;    //should change success to integer to determine which message box to pop (no internet, stream cannot be read etc.)
                bw.ReportProgress(100);
            }

            return(success);
        }
Exemple #14
0
        /// <summary>
        /// This function analyzes all articles stored in the database that
        /// are marked as unreviewed. The algorithm is performed and all stocks
        /// associated with the article reviewed are saved with the score from
        /// that specifc article.
        /// </summary>
        /// <param name="bw">BackgroundWorker to report progress of function
        /// to main thread in case of slow review;</param>
        /// <returns></returns>
        public int analyzeArticles(BackgroundWorker bw)
        {
            int success         = 1;            //1 for successful analysis
            cDatabaseManager db = new cDatabaseManager();

            Dictionary <int, string> articles = db.getUnreviewedArticles();
            Dictionary <int, string> stocks   = db.getStockSymbols();
            Dictionary <string, int> dict     = db.getUserDictionary(cUser.UserID);

            float percent = 0.0f;
            int   count   = 0;

            if (articles.Count == 0)             //no unreviewed articles
            {
                success = 0;                     //0 for all articles already scanned
            }
            foreach (var a in articles)
            {
                List <KeyValuePair <int, string> > listed_stocks = new List <KeyValuePair <int, string> >();
                int article_score = 0;

                //find all stocks mentioned in the article
                foreach (var s in stocks)
                {
                    string expr = "\\W" + s.Value + "\\W";

                    Regex r = new Regex(expr);                          //use regex on stock symbol to only find symbols with non-characters near it
                    Match m = r.Match(a.Value);

                    if (m.Success)
                    {
                        listed_stocks.Add(s);
                    }
                }

                //find occurences of words contained in the dictionary
                foreach (var e in dict)
                {
                    int currentIndex = 0;
                    while ((currentIndex = a.Value.IndexOf(e.Key, currentIndex, StringComparison.OrdinalIgnoreCase)) != -1)
                    {
                        currentIndex++;

                        //add word score to article total score
                        if (e.Value > 0)
                        {
                            ++article_score;
                        }
                        else
                        {
                            --article_score;
                        }

                        //article_score += e.Value;
                    }
                }

                //save article score for each entry
                foreach (var entry in listed_stocks)
                {
                    if (!db.addAnalysis(cUser.UserID, entry.Key, a.Key, article_score))
                    {
                        success = -1;                           //failure during database insert
                    }
                }

                db.setArticlesAnalyzed(a.Key);                 //set article as analyzed
                percent = ((float)count / (float)articles.Count) * 100f;
                bw.ReportProgress((int)percent);
                ++count;
            }

            return(success);
        }