Title: 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:
http://download.finance.yahoo.com/d/quotes.csv?s=MCI+DIS+COKE+PEP&f=sl1d1t1c1
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.
Tag | Meaning |
a | Ask |
a2 | Average Daily Volume |
a5 | Ask Size |
b | Bid |
b2 | Ask (Real-time) |
b3 | Bid (Real-time) |
b4 | Book Value |
b6 | Bid Size |
c | Change & Percent Change |
c1 | Change |
c3 | Commission |
c6 | Change (Real-time) |
c8 | After Hours Change (Real-time) |
d | Dividend/Share |
d1 | Last Trade Date |
d2 | Trade Date |
e | Earnings/Share |
e1 | Error Indication (returned for symbol changed / invalid) |
e7 | EPS Estimate Current Year |
e8 | EPS Estimate Next Year |
e9 | EPS Estimate Next Quarter |
f6 | Float Shares |
g | Day s Low |
g1 | Holdings Gain Percent |
g3 | Annualized Gain |
g4 | Holdings Gain |
g5 | Holdings Gain Percent (Real-time) |
g6 | Holdings Gain (Real-time) |
h | Day s High |
i | More Info |
i5 | Order Book (Real-time) |
j | 52-week Low |
j1 | Market Capitalization |
j3 | Market Cap (Real-time) |
j4 | EBITDA |
j5 | Change From 52-week Low |
j6 | Percent Change From 52-week Low |
k | 52-week High |
k1 | Last Trade (Real-time) With Time |
k2 | Change Percent (Real-time) |
k3 | Last Trade Size |
k4 | Change From 52-week High |
k5 | Percebt Change From 52-week High |
l | Last Trade (With Time) |
l1 | Last Trade (Price Only) |
l2 | High Limit |
l3 | Low Limit |
m | Day s Range |
m2 | Day s Range (Real-time) |
m3 | 50-day Moving Average |
m4 | 200-day Moving Average |
m5 | Change From 200-day Moving Average |
m6 | Percent Change From 200-day Moving Average |
m7 | Change From 50-day Moving Average |
m8 | Percent Change From 50-day Moving Average |
n | Name |
n4 | Notes |
o | Open |
p | Previous Close |
p1 | Price Paid |
p2 | Change in Percent |
p5 | Price/Sales |
p6 | Price/Book |
q | Ex-Dividend Date |
r | P/E Ratio |
r1 | Dividend Pay Date |
r2 | P/E Ratio (Real-time) |
r5 | PEG Ratio |
r6 | Price/EPS Estimate Current Year |
r7 | Price/EPS Estimate Next Year |
s | Symbol |
s1 | Shares Owned |
s7 | Short Ratio |
t1 | Last Trade Time |
t6 | Trade Links |
t7 | Ticker Trend |
t8 | 1 yr Target Price |
v | Volume |
v1 | Holdings Value |
v7 | Holdings Value (Real-time) |
w | 52-week Range |
w1 | Day s Value Change |
w4 | Day s Value Change (Real-time) |
x | Stock Exchange |
y | Dividend Yield |
This example uses these tags:
Tag | Meaning |
s | Symbol |
l1 | Last Trade (Price Only) |
d1 | Last Trade Date |
t1 | Last Trade Time |
c1 | Change |
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.
"MCIX",0.00,"N/A","N/A",N/A
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.
|