Advertisement
Guest User

form1.cs

a guest
Aug 23rd, 2018
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.24 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using HtmlAgilityPack;
  11.  
  12. namespace StockViewer
  13. {
  14. public partial class Form : MetroFramework.Forms.MetroForm
  15. {
  16. public static List<string> portfolio = new List<string>() { "FB", "AAPL", "NASDAQ" };
  17. public static ListView lv_portfolio;
  18. public static MetroFramework.Controls.MetroTextBox tb_portfolio;
  19.  
  20. public static List<HtmlAgilityPack.HtmlDocument> pages = new List<HtmlAgilityPack.HtmlDocument>();
  21.  
  22. System.Timers.Timer t = new System.Timers.Timer();
  23.  
  24. public static ListViewItem[] companies;
  25.  
  26. public static bool autoRefresh = true;
  27.  
  28. public Form()
  29. {
  30. //Initializing Components and Loading Portfolio
  31. InitializeComponent();
  32. lv_portfolio = listview_portfolio;
  33. tb_portfolio = textbox_portfolio;
  34.  
  35. this.BackColor = System.Drawing.Color.Black;
  36.  
  37. string[] lines = System.IO.File.ReadAllLines(@"c:\\StockViewer\\demo.txt");
  38. portfolio.Clear();
  39. for (int i = 0; i < lines.Length; i++)
  40. {
  41. portfolio.Add(lines[i]);
  42. }
  43.  
  44. companies = new ListViewItem[portfolio.Count];
  45.  
  46. //Formatting Timer
  47. t.SynchronizingObject = this;
  48. t.Start();
  49.  
  50. LoadPortfolio();
  51. }
  52.  
  53. static async void LoadPortfolio()
  54. {
  55. System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
  56. lv_portfolio.Items.Clear();
  57. pages.Clear();
  58.  
  59. HtmlWeb web = new HtmlWeb();
  60.  
  61. int counter = 0;
  62.  
  63. if (lv_portfolio.Items.Count == 0)
  64. {
  65. foreach (string ticker in portfolio)
  66. {
  67. try {
  68. //Loading the ticker through google finance
  69. var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
  70. pages.Add((HtmlAgilityPack.HtmlDocument)doc);
  71. //Selecting the necessary information on the web page
  72. var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
  73. //MessageBox.Show(ticker);
  74.  
  75. if (nodes != null)
  76. {
  77. //Converting all node InnerText to strings
  78. string[] stringNodes = new string[nodes.Count()];
  79.  
  80. for (int i = 0; i < nodes.Count(); i++)
  81. {
  82. stringNodes[i] = nodes[i].InnerText;
  83. }
  84.  
  85. //Splitting out the important numbers in the second line captured (stock price, difference, percent)
  86. string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
  87.  
  88. if (nodes[0].InnerText.Length > 2)
  89. {
  90. companies[counter] = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
  91. }
  92. else
  93. {
  94. companies[counter] = new ListViewItem(nodes[0].InnerText);
  95. }
  96.  
  97. companies[counter].SubItems.Add(portfolio[counter]);
  98.  
  99. lv_portfolio.Items.Add(companies[counter]);
  100.  
  101. for (int i = 0; i < split.Length; i++)
  102. {
  103. if (split[i] != "")
  104. {
  105. companies[counter].SubItems.Add(split[i]);
  106. }
  107.  
  108. if (split[i].Contains("-"))
  109. {
  110. companies[counter].ForeColor = Color.Red;
  111. }
  112.  
  113. if (split[i].Contains("+"))
  114. {
  115. companies[counter].ForeColor = Color.LimeGreen;
  116. }
  117. }
  118. counter++;
  119. }
  120. else
  121. {
  122. MessageBox.Show("Load Operation Failed");
  123. }
  124. System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
  125.  
  126. }
  127. catch
  128. {
  129. MessageBox.Show("Load operation failed");
  130. }
  131. }
  132. }
  133. else
  134. {
  135. try
  136. {
  137. foreach (string ticker in portfolio)
  138. {
  139. //Loading the ticker through google finance
  140. var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
  141. //Selecting the necessary information on the web page
  142. var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
  143.  
  144. if (nodes != null)
  145. {
  146. //Converting all node InnerText to strings
  147. string[] stringNodes = new string[nodes.Count()];
  148.  
  149. for (int i = 0; i < nodes.Count(); i++)
  150. {
  151. stringNodes[i] = nodes[i].InnerText;
  152. }
  153.  
  154. //Splitting out the important numbers in the second line captured (stock price, difference, percent)
  155. string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
  156.  
  157. if (nodes[0].InnerText.Length > 2)
  158. {
  159. companies[counter] = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
  160. }
  161. else
  162. {
  163. companies[counter] = new ListViewItem(nodes[0].InnerText);
  164. }
  165.  
  166. companies[counter].SubItems.Add(portfolio[counter]);
  167.  
  168. if (portfolio.Contains(companies[counter].SubItems[1].Text))
  169. {
  170.  
  171. }
  172. else
  173. {
  174. lv_portfolio.Items.Add(companies[counter]);
  175. }
  176.  
  177. for (int i = 0; i < split.Length; i++)
  178. {
  179. if (split[i] != "")
  180. {
  181. companies[counter].SubItems.Add(split[i]);
  182. }
  183.  
  184. if (split[i].Contains("-"))
  185. {
  186. companies[counter].ForeColor = Color.Red;
  187. }
  188.  
  189. if (split[i].Contains("+"))
  190. {
  191. companies[counter].ForeColor = Color.LimeGreen;
  192. }
  193. }
  194. counter++;
  195. }
  196. System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
  197. }
  198. }
  199. catch { }
  200. }
  201. }
  202.  
  203. static async void LoadTicker(string ticker)
  204. {
  205. System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
  206.  
  207. HtmlWeb web = new HtmlWeb();
  208.  
  209. ListViewItem lvi = new ListViewItem();
  210. companies[companies.Length - 1] = lvi;
  211.  
  212. var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + ticker.ToLower()));
  213. //Selecting the necessary information on the web page
  214. var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
  215.  
  216. if (nodes != null)
  217. {
  218. //Converting all node InnerText to strings
  219. string[] stringNodes = new string[nodes.Count()];
  220.  
  221. for (int i = 0; i < nodes.Count(); i++)
  222. {
  223. stringNodes[i] = nodes[i].InnerText;
  224. }
  225.  
  226. //Splitting out the important numbers in the second line captured (stock price, difference, percent)
  227. string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
  228.  
  229. if (nodes[0].InnerText.Length > 2)
  230. {
  231. lvi = new ListViewItem(nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3));
  232. }
  233. else
  234. {
  235. lvi = new ListViewItem(nodes[0].InnerText);
  236. }
  237.  
  238. lvi.SubItems.Add(ticker);
  239.  
  240. lv_portfolio.Items.Add(lvi);
  241.  
  242. for (int i = 0; i < split.Length; i++)
  243. {
  244. if (split[i] != "")
  245. {
  246. lvi.SubItems.Add(split[i]);
  247. }
  248.  
  249. if (split[i].Contains("-"))
  250. {
  251. lvi.ForeColor = Color.Red;
  252. }
  253.  
  254. if (split[i].Contains("+"))
  255. {
  256. lvi.ForeColor = Color.LimeGreen;
  257. }
  258. }
  259. }
  260.  
  261. }
  262.  
  263. static async void RefactorPortfolio()
  264. {
  265. System.IO.File.WriteAllLines(@"c:\\StockViewer\\demo.txt", portfolio);
  266.  
  267. HtmlWeb web = new HtmlWeb();
  268.  
  269. int counter = 0;
  270.  
  271. foreach (ListViewItem lvi in lv_portfolio.Items)
  272. {
  273. var doc = await Task.Factory.StartNew(() => web.Load("https://www.google.com/search?q=google+finance+" + lvi.SubItems[1].Text));
  274. //Selecting the necessary information on the web page
  275. var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//span");
  276.  
  277. if (nodes != null)
  278. {
  279. //Converting all node InnerText to strings
  280. string[] stringNodes = new string[nodes.Count()];
  281.  
  282. for (int i = 0; i < nodes.Count(); i++)
  283. {
  284. stringNodes[i] = nodes[i].InnerText;
  285. }
  286.  
  287. //Refactoring Company Name
  288. if (nodes[0].InnerText.Length > 2)
  289. {
  290. lvi.Text = nodes[0].InnerText.Substring(3, nodes[0].InnerText.Length - 3);
  291. //MessageBox.Show(lvi.Text);
  292. }
  293. else
  294. {
  295. lvi.Text = nodes[0].InnerText;
  296. }
  297.  
  298. //Splitting out the important numbers in the second line captured (stock price, difference, percent)
  299. string[] split = stringNodes[1].Split(new Char[] { ' ', '&', 'n', 'b', 's', 'p', ';' });
  300. int j = 2;
  301.  
  302. for (int i = 0; i < split.Length; i++)
  303. {
  304. if (split[i] != "")
  305. {
  306. lvi.SubItems[j].Text = split[i];
  307. j++;
  308. }
  309. }
  310.  
  311. counter++;
  312. }
  313. }
  314. }
  315.  
  316. static async void LoadFinancials(string ticker)
  317. {
  318. HtmlWeb web = new HtmlWeb();
  319.  
  320. tb_portfolio.Text = "";
  321.  
  322. try
  323. {
  324. var doc = await Task.Factory.StartNew(() => web.Load("https://www.nasdaq.com/symbol/" + ticker.ToLower() + "/financials?query=balance-sheet"));
  325. //Selecting the necessary information on the web page
  326. var nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[26]");
  327. //[@id="knowledge-finance-wholepage__entity-summary"]/div/div/g-card-section[2]/div/div/div[1]/table/tbody/tr[5]/td[2]
  328.  
  329. string[] split = nodes.InnerText.Split(' ', '\n');
  330. //Acquiring Total Liabilities
  331. split[100] = split[100].Replace("$", string.Empty);
  332. split[100] = split[100].Replace(" ", string.Empty);
  333. split[100] = split[100].Replace(",", string.Empty);
  334.  
  335. int totalLiabilities = int.Parse(split[100]);
  336.  
  337. nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[15]");
  338.  
  339. split = nodes.InnerText.Split(' ', '\n');
  340. //Acquiring Total Assets
  341. split[100] = split[100].Replace("$", string.Empty);
  342. split[100] = split[100].Replace(" ", string.Empty);
  343. split[100] = split[100].Replace(",", string.Empty);
  344.  
  345. int totalAssets = int.Parse(split[100]);
  346.  
  347. nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[21]");
  348.  
  349. split = nodes.InnerText.Split(' ', '\n');
  350.  
  351. //Acquiring Long Term Debt
  352. split[100] = split[100].Replace("$", string.Empty);
  353. split[100] = split[100].Replace(" ", string.Empty);
  354. split[100] = split[100].Replace(",", string.Empty);
  355.  
  356. int longTermDebt = int.Parse(split[100]);
  357.  
  358. int shareHolderEquity = totalAssets - totalLiabilities;
  359.  
  360. int investedCapital = shareHolderEquity + longTermDebt;
  361.  
  362. doc = await Task.Factory.StartNew(() => web.Load("https://www.nasdaq.com/symbol/" + ticker.ToLower() + "/financials?query=income-statement"));
  363. nodes = doc.DocumentNode.SelectSingleNode("//body//div[@id='financials-iframe-wrap']//div//table//tr[18]");
  364.  
  365. split = nodes.InnerText.Split(' ', '\n');
  366.  
  367. //Acquiring Net Income
  368. split[100] = split[100].Replace("$", string.Empty);
  369. split[100] = split[100].Replace(" ", string.Empty);
  370. split[100] = split[100].Replace(",", string.Empty);
  371.  
  372. int netIncome = int.Parse(split[100]);
  373.  
  374. decimal roic = (decimal) netIncome / (decimal) investedCapital;
  375.  
  376. tb_portfolio.Text = "Return On Invested Capital % (ROIC) " + (roic * 100).ToString("F2");
  377. //(roic * 100).ToString("F2")
  378.  
  379. /*
  380. float roic;
  381. float earningsYield;
  382.  
  383. ListViewItem lvi = new ListViewItem();
  384. companies[companies.Length - 1] = lvi;
  385.  
  386. for (int i = 0; i < lv_portfolio.Items.Count; i++)
  387. {
  388. if (lv_portfolio.Items[i].SubItems[1].Text == ticker)
  389. {
  390. doc = pages[i];
  391. }
  392. }
  393.  
  394. //Selecting the necessary information on the web page
  395. var nodes = doc.DocumentNode.SelectNodes("//body//div[@id='search']//div//table//tr");
  396.  
  397. List<string> financials = new List<string>();
  398. int j = 0;
  399.  
  400. foreach (HtmlNode n in nodes)
  401. {
  402. if (n.InnerText != "")
  403. {
  404. if (n.InnerText != "")
  405. {
  406. int index = n.InnerText.IndexOf("&nbsp;");
  407. if (n.InnerText.Contains("&nbsp;"))
  408. {
  409. string pulledStr = n.InnerText.Remove(index, 6);
  410. j++;
  411. if (j > 2)
  412. {
  413. financials.Add(pulledStr);
  414. }
  415. }
  416.  
  417. }
  418. }
  419. }
  420.  
  421. //Clear the textbox
  422. tb_portfolio.Text = "";
  423.  
  424. for (int i = 0; i < financials.Count; i++)
  425. {
  426. string[] split = financials[i].Split(':');
  427. split[0] += ": ";
  428. split[0] += split[1];
  429. financials[i] = split[0];
  430. tb_portfolio.Text += (financials[i] + Environment.NewLine);
  431. }
  432. */
  433. }
  434. catch {
  435. tb_portfolio.Text = "An unknown error has occurred";
  436. }
  437.  
  438. }
  439.  
  440. private void Form_Load(object sender, EventArgs e)
  441. {
  442. /*chartGraphic.ChartAreas[0].AxisY.ScaleView.Zoom(0,15);
  443. chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoom(0,15);
  444. chartGraphic.ChartAreas[0].CursorX.IsUserEnabled = true;
  445. chartGraphic.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
  446. chartGraphic.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
  447. for (int i = 0; i < 15; i++)
  448. {
  449. chartGraphic.Series[0].Points.AddXY(i, function(i));
  450. chartGraphic.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
  451. }*/
  452. }
  453.  
  454. private void textbox_tickerEntry_KeyDown(object sender, KeyEventArgs e)
  455. {
  456. if (e.KeyCode == Keys.Enter)
  457. {
  458. if (textbox_tickerEntry.Text != "")
  459. {
  460. portfolio.Add(textbox_tickerEntry.Text.ToUpper());
  461. LoadTicker(textbox_tickerEntry.Text.ToUpper());
  462. textbox_tickerEntry.Text = "";
  463. }
  464.  
  465. }
  466. }
  467.  
  468. private void listview_portfolio_MouseClick(object sender, MouseEventArgs e)
  469. {
  470. if (e.Button == MouseButtons.Right)
  471. {
  472. if (listview_portfolio.FocusedItem.Bounds.Contains(e.Location))
  473. {
  474. contextMenuStrip1.Show(Cursor.Position);
  475. }
  476. }
  477. if (e.Button == MouseButtons.Left)
  478. {
  479. LoadFinancials(listview_portfolio.FocusedItem.SubItems[1].Text.ToUpper());
  480. }
  481. }
  482.  
  483. private void removeToolStripMenuItem_Click(object sender, EventArgs e)
  484. {
  485. portfolio.Remove(listview_portfolio.FocusedItem.SubItems[1].Text);
  486. lv_portfolio.Items.Remove(listview_portfolio.FocusedItem);
  487. textbox_portfolio.Text = "";
  488. //LoadPortfolio();
  489. }
  490.  
  491. private void refreshClock_Tick(object sender, EventArgs e)
  492. {
  493. if (autoRefresh)
  494. RefactorPortfolio();
  495. }
  496.  
  497. private void button_refresh_Click_1(object sender, EventArgs e)
  498. {
  499. LoadPortfolio();
  500. }
  501.  
  502. private void button_addTicker_Click_1(object sender, EventArgs e)
  503. {
  504. portfolio.Add(textbox_tickerEntry.Text.ToUpper());
  505. LoadTicker(textbox_tickerEntry.Text.ToUpper());
  506. textbox_tickerEntry.Text = "";
  507. }
  508.  
  509. private void check_refresh_CheckedChanged_1(object sender, EventArgs e)
  510. {
  511. if (check_refresh.Checked == true)
  512. {
  513. autoRefresh = true;
  514. refreshClock.Enabled = true;
  515. }
  516. else
  517. {
  518. autoRefresh = false;
  519. refreshClock.Enabled = false;
  520. }
  521. }
  522. }
  523. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement