[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Get stock prices from the internet in C#

[Get stock prices from the internet in C#]

There are many web sites that can return stock prices to a program. This program uses download.finance.yahoo.com. It builds a URL of the following form to get prices for MCI, DIS, COKE, and PEP:


The end of the URL, which in this example is &f=sl1d1t1c1, tells the Yahoo server what data you want to download. The following table shows the tags you can include.

a2Average Daily Volume
a5Ask Size
b2Ask (Real-time)
b3Bid (Real-time)
b4Book Value
b6Bid Size
cChange & Percent Change
c6Change (Real-time)
c8After Hours Change (Real-time)
d1Last Trade Date
d2Trade Date
e1Error Indication (returned for symbol changed / invalid)
e7EPS Estimate Current Year
e8EPS Estimate Next Year
e9EPS Estimate Next Quarter
f6Float Shares
gDay s Low
g1Holdings Gain Percent
g3Annualized Gain
g4Holdings Gain
g5Holdings Gain Percent (Real-time)
g6Holdings Gain (Real-time)
hDay s High
iMore Info
i5Order Book (Real-time)
j52-week Low
j1Market Capitalization
j3Market Cap (Real-time)
j5Change From 52-week Low
j6Percent Change From 52-week Low
k52-week High
k1Last Trade (Real-time) With Time
k2Change Percent (Real-time)
k3Last Trade Size
k4Change From 52-week High
k5Percebt Change From 52-week High
lLast Trade (With Time)
l1Last Trade (Price Only)
l2High Limit
l3Low Limit
mDay s Range
m2Day s Range (Real-time)
m350-day Moving Average
m4200-day Moving Average
m5Change From 200-day Moving Average
m6Percent Change From 200-day Moving Average
m7Change From 50-day Moving Average
m8Percent Change From 50-day Moving Average
pPrevious Close
p1Price Paid
p2Change in Percent
qEx-Dividend Date
rP/E Ratio
r1Dividend Pay Date
r2P/E Ratio (Real-time)
r5PEG Ratio
r6Price/EPS Estimate Current Year
r7Price/EPS Estimate Next Year
s1Shares Owned
s7Short Ratio
t1Last Trade Time
t6Trade Links
t7Ticker Trend
t81 yr Target Price
v1Holdings Value
v7Holdings Value (Real-time)
w52-week Range
w1Day s Value Change
w4Day s Value Change (Real-time)
xStock Exchange
yDividend Yield

This example uses these tags:

l1Last Trade (Price Only)
d1Last Trade Date
t1Last Trade Time

The web site returns a single string containing the results. The stocks' entries are separated by \r\n pairs. The values for each stock are separated by commas. The following text shows a sample.

"MCI",16.146,"1/16/2015","3:48pm",+0.096 "DIS",95.18,"1/16/2015","4:00pm",+0.83 "COKE",95.99,"1/16/2015","4:00pm",+2.13 "PEP",97.29,"1/16/2015","4:00pm",+0.62

The GetWebResponse method shown in the following code gets a web response and returns it in a string.

// Get a web response. private string GetWebResponse(string url) { // Make a WebClient. WebClient web_client = new WebClient(); // Get the indicated URL. Stream response = web_client.OpenRead(url); // Read the result. using (StreamReader stream_reader = new StreamReader(response)) { // Get the results. string result = stream_reader.ReadToEnd(); // Close the stream reader and its underlying stream. stream_reader.Close(); // Return the result. return result; } }

This code creates a WebClient and uses its OpenRead method to get a StreamReader that can read the result of the URL request. The code reads the stream to its end and returns the resulting string.

The following code shows how the program uses the GetWebResponse method.

// Get the stock prices. private void btnGetPrices_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; Application.DoEvents(); // Build the URL. string url = ""; if (txtSymbol1.Text != "") url += txtSymbol1.Text + "+"; if (txtSymbol2.Text != "") url += txtSymbol2.Text + "+"; if (txtSymbol3.Text != "") url += txtSymbol3.Text + "+"; if (txtSymbol4.Text != "") url += txtSymbol4.Text + "+"; if (url != "") { // Remove the trailing plus sign. url = url.Substring(0, url.Length - 1); // Prepend the base URL. const string base_url = "http://download.finance.yahoo.com/d/quotes.csv?s=@&f=sl1d1t1c1"; url = base_url.Replace("@", url); // Get the response. try { // Get the web response. string result = GetWebResponse(url); Console.WriteLine(result.Replace("\\r\\n", "\r\n")); // Pull out the current prices. string[] lines = result.Split( new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); txtPrice1.Text = decimal.Parse(lines[0].Split(',')[1]).ToString("C3"); txtPrice2.Text = decimal.Parse(lines[1].Split(',')[1]).ToString("C3"); txtPrice3.Text = decimal.Parse(lines[2].Split(',')[1]).ToString("C3"); txtPrice4.Text = decimal.Parse(lines[3].Split(',')[1]).ToString("C3"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Read Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } this.Cursor = Cursors.Default; }

The code builds the URL from the symbols in the program's text boxes. It calls the GetWebResponse and parses the result to find the stock prices. After it finds each price, it converts it into a decimal value and displays it as currency with 3 digits after the decimal point.

This example only uses the first value, the stock price, so you really don't need the other tags in the URL. I've put them in here just to show how you can add more tags.

Note that this web site returns a string with the following format if you try to look up a stock symbol that doesn't exist.


In that case, the program displays 0.00 for the price (which is better than crashing).

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.