Advertisement
Guest User

cheese

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