Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using HtmlAgilityPack;
- namespace StockViewer
- {
- public partial class Form : MetroFramework.Forms.MetroForm
- {
- public static List<string> portfolio = new List<string>() { "FB", "AAPL", "NASDAQ" };
- public static ListView lv_portfolio;
- public static MetroFramework.Controls.MetroTextBox tb_portfolio;
- public static List<HtmlAgilityPack.HtmlDocument> pages = new List<HtmlAgilityPack.HtmlDocument>();
- System.Timers.Timer t = new System.Timers.Timer();
- public static ListViewItem[] companies;
- public static bool autoRefresh = true;
- public Form()
- {
- //Initializing Components and Loading Portfolio
- InitializeComponent();
- lv_portfolio = listview_portfolio;
- tb_portfolio = textbox_portfolio;
- this.BackColor = System.Drawing.Color.Black;
- string[] lines = System.IO.File.ReadAllLines(@"c:\\StockViewer\\demo.txt");
- portfolio.Clear();
- for (int i = 0; i < lines.Length; i++)
- {
- portfolio.Add(lines[i]);
- }
- companies = new ListViewItem[portfolio.Count];
- //Formatting Timer
- t.SynchronizingObject = this;
- t.Start();
- LoadPortfolio();
- }
- static async void LoadPortfolio()
- {
- System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
- lv_portfolio.Items.Clear();
- pages.Clear();
- HtmlWeb web = new HtmlWeb();
- int counter = 0;
- if (lv_portfolio.Items.Count == 0)
- {
- foreach (string ticker in portfolio)
- {
- try {
- //Loading the ticker through google finance
- var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
- pages.Add((HtmlAgilityPack.HtmlDocument)doc);
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
- //MessageBox.Show(ticker);
- if (nodes != null)
- {
- //Converting all node InnerText to strings
- string[] stringNodes = new string[nodes.Count()];
- for (int i = 0; i < nodes.Count(); i++)
- {
- stringNodes[i] = nodes[i].InnerText;
- }
- //Splitting out the important numbers in the second line captured (stock price, difference, percent)
- string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
- if (nodes[0].InnerText.Length > 2)
- {
- companies[counter] = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
- }
- else
- {
- companies[counter] = new ListViewItem(nodes[0].InnerText);
- }
- companies[counter].SubItems.Add(portfolio[counter]);
- lv_portfolio.Items.Add(companies[counter]);
- for (int i = 0; i < split.Length; i++)
- {
- if (split[i] != "")
- {
- companies[counter].SubItems.Add(split[i]);
- }
- if (split[i].Contains("-"))
- {
- companies[counter].ForeColor = Color.Red;
- }
- if (split[i].Contains("+"))
- {
- companies[counter].ForeColor = Color.LimeGreen;
- }
- }
- counter++;
- }
- else
- {
- MessageBox.Show("Load Operation Failed");
- }
- System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
- }
- catch
- {
- MessageBox.Show("Load operation failed");
- }
- }
- }
- else
- {
- try
- {
- foreach (string ticker in portfolio)
- {
- //Loading the ticker through google finance
- var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
- if (nodes != null)
- {
- //Converting all node InnerText to strings
- string[] stringNodes = new string[nodes.Count()];
- for (int i = 0; i < nodes.Count(); i++)
- {
- stringNodes[i] = nodes[i].InnerText;
- }
- //Splitting out the important numbers in the second line captured (stock price, difference, percent)
- string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
- if (nodes[0].InnerText.Length > 2)
- {
- companies[counter] = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
- }
- else
- {
- companies[counter] = new ListViewItem(nodes[0].InnerText);
- }
- companies[counter].SubItems.Add(portfolio[counter]);
- if (portfolio.Contains(companies[counter].SubItems[1].Text))
- {
- }
- else
- {
- lv_portfolio.Items.Add(companies[counter]);
- }
- for (int i = 0; i < split.Length; i++)
- {
- if (split[i] != "")
- {
- companies[counter].SubItems.Add(split[i]);
- }
- if (split[i].Contains("-"))
- {
- companies[counter].ForeColor = Color.Red;
- }
- if (split[i].Contains("+"))
- {
- companies[counter].ForeColor = Color.LimeGreen;
- }
- }
- counter++;
- }
- System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
- }
- }
- catch { }
- }
- }
- static async void LoadTicker(string ticker)
- {
- System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
- HtmlWeb web = new HtmlWeb();
- ListViewItem lvi = new ListViewItem();
- companies[companies.Length - 1] = lvi;
- var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
- if (nodes != null)
- {
- //Converting all node InnerText to strings
- string[] stringNodes = new string[nodes.Count()];
- for (int i = 0; i < nodes.Count(); i++)
- {
- stringNodes[i] = nodes[i].InnerText;
- }
- //Splitting out the important numbers in the second line captured (stock price, difference, percent)
- string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
- if (nodes[0].InnerText.Length > 2)
- {
- lvi = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
- }
- else
- {
- lvi = new ListViewItem(nodes[0].InnerText);
- }
- lvi.SubItems.Add(ticker);
- lv_portfolio.Items.Add(lvi);
- for (int i = 0; i < split.Length; i++)
- {
- if (split[i] != "")
- {
- lvi.SubItems.Add(split[i]);
- }
- if (split[i].Contains("-"))
- {
- lvi.ForeColor = Color.Red;
- }
- if (split[i].Contains("+"))
- {
- lvi.ForeColor = Color.LimeGreen;
- }
- }
- }
- }
- static async void RefactorPortfolio()
- {
- System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
- HtmlWeb web = new HtmlWeb();
- int counter = 0;
- foreach (ListViewItem lvi in lv_portfolio.Items)
- {
- var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + lvi.SubItems[1].Text));
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
- if (nodes != null)
- {
- //Converting all node InnerText to strings
- string[] stringNodes = new string[nodes.Count()];
- for (int i = 0; i < nodes.Count(); i++)
- {
- stringNodes[i] = nodes[i].InnerText;
- }
- //Refactoring Company Name
- if (nodes[0].InnerText.Length > 2)
- {
- lvi.Text = nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3);
- //MessageBox.Show(lvi.Text);
- }
- else
- {
- lvi.Text = nodes[0].InnerText;
- }
- //Splitting out the important numbers in the second line captured (stock price, difference, percent)
- string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
- int j = 2;
- for (int i = 0; i < split.Length; i++)
- {
- if (split[i] != "")
- {
- lvi.SubItems[j].Text = split[i];
- j++;
- }
- }
- counter++;
- }
- }
- }
- static async void LoadFinancials(string ticker)
- {
- HtmlWeb web = new HtmlWeb();
- tb_portfolio.Text = "";
- try
- {
- var doc = await Task.Factory.StartNew(() => web.Load("https://www.nasdaq.com/symbol/" + ticker.ToLower() + "/financials?query=balance-sheet"));
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[26]");
- //[@id="knowledge-finance-wholepage__entity-summary"]/div/div/g-card-section[2]/div/div/div[1]/table/tbody/tr[5]/td[2]
- string[] split = nodes.InnerText.Split(' ', '\n');
- //Acquiring Total Liabilities
- split[100] = split[100].Replace("$", string.Empty);
- split[100] = split[100].Replace(" ", string.Empty);
- split[100] = split[100].Replace(",", string.Empty);
- int totalLiabilities = int.Parse(split[100]);
- nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[15]");
- split = nodes.InnerText.Split(' ', '\n');
- //Acquiring Total Assets
- split[100] = split[100].Replace("$", string.Empty);
- split[100] = split[100].Replace(" ", string.Empty);
- split[100] = split[100].Replace(",", string.Empty);
- int totalAssets = int.Parse(split[100]);
- nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[21]");
- split = nodes.InnerText.Split(' ', '\n');
- //Acquiring Long Term Debt
- split[100] = split[100].Replace("$", string.Empty);
- split[100] = split[100].Replace(" ", string.Empty);
- split[100] = split[100].Replace(",", string.Empty);
- int longTermDebt = int.Parse(split[100]);
- int shareHolderEquity = totalAssets - totalLiabilities;
- int investedCapital = shareHolderEquity + longTermDebt;
- doc = await Task.Factory.StartNew(() => web.Load("https://www.nasdaq.com/symbol/" + ticker.ToLower() + "/financials?query=income-statement"));
- nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[18]");
- split = nodes.InnerText.Split(' ', '\n');
- //Acquiring Net Income
- split[100] = split[100].Replace("$", string.Empty);
- split[100] = split[100].Replace(" ", string.Empty);
- split[100] = split[100].Replace(",", string.Empty);
- int netIncome = int.Parse(split[100]);
- decimal roic = (decimal) netIncome / (decimal) investedCapital;
- tb_portfolio.Text = "Return On Invested Capital % (ROIC) " + (roic * 100).ToString("F2");
- //(roic * 100).ToString("F2")
- /*
- float roic;
- float earningsYield;
- ListViewItem lvi = new ListViewItem();
- companies[companies.Length - 1] = lvi;
- for (int i = 0; i < lv_portfolio.Items.Count; i++)
- {
- if (lv_portfolio.Items[i].SubItems[1].Text == ticker)
- {
- doc = pages[i];
- }
- }
- //Selecting the necessary information on the web page
- var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//table//tr");
- List<string> financials = new List<string>();
- int j = 0;
- foreach (HtmlNode n in nodes)
- {
- if (n.InnerText != "")
- {
- if (n.InnerText != "")
- {
- int index = n.InnerText.IndexOf(" ");
- if (n.InnerText.Contains(" "))
- {
- string pulledStr = n.InnerText.Remove(index, 6);
- j++;
- if (j > 2)
- {
- financials.Add(pulledStr);
- }
- }
- }
- }
- }
- //Clear the textbox
- tb_portfolio.Text = "";
- for (int i = 0; i < financials.Count; i++)
- {
- string[] split = financials[i].Split(':');
- split[0] += ": ";
- split[0] += split[1];
- financials[i] = split[0];
- tb_portfolio.Text += (financials[i] + Environment.NewLine);
- }
- */
- }
- catch {
- tb_portfolio.Text = "An unknown error has occurred";
- }
- }
- private void Form_Load(object sender, EventArgs e)
- {
- /*chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoom(0,15);
- chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoom(0,15);
- chartGraphic.ChartAreas[0].CursorX.IsUserEnabled = true;
- chartGraphic.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
- chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
- for (int i = 0; i < 15; i++)
- {
- chartGraphic.Series[0].Points.AddXY(i, function(i));
- chartGraphic.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
- }*/
- }
- private void textbox_tickerEntry_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Enter)
- {
- if (textbox_tickerEntry.Text != "")
- {
- portfolio.Add(textbox_tickerEntry.Text.ToUpper());
- LoadTicker(textbox_tickerEntry.Text.ToUpper());
- textbox_tickerEntry.Text = "";
- }
- }
- }
- private void listview_portfolio_MouseClick(object sender, MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Right)
- {
- if (listview_portfolio.FocusedItem.Bounds.Contains(e.Location))
- {
- contextMenuStrip1.Show(Cursor.Position);
- }
- }
- if (e.Button == MouseButtons.Left)
- {
- LoadFinancials(listview_portfolio.FocusedItem.SubItems[1].Text.ToUpper());
- }
- }
- private void removeToolStripMenuItem_Click(object sender, EventArgs e)
- {
- portfolio.Remove(listview_portfolio.FocusedItem.SubItems[1].Text);
- lv_portfolio.Items.Remove(listview_portfolio.FocusedItem);
- textbox_portfolio.Text = "";
- //LoadPortfolio();
- }
- private void refreshClock_Tick(object sender, EventArgs e)
- {
- if (autoRefresh)
- RefactorPortfolio();
- }
- private void button_refresh_Click_1(object sender, EventArgs e)
- {
- LoadPortfolio();
- }
- private void button_addTicker_Click_1(object sender, EventArgs e)
- {
- portfolio.Add(textbox_tickerEntry.Text.ToUpper());
- LoadTicker(textbox_tickerEntry.Text.ToUpper());
- textbox_tickerEntry.Text = "";
- }
- private void check_refresh_CheckedChanged_1(object sender, EventArgs e)
- {
- if (check_refresh.Checked == true)
- {
- autoRefresh = true;
- refreshClock.Enabled = true;
- }
- else
- {
- autoRefresh = false;
- refreshClock.Enabled = false;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement