Get stock prices from the internet in C#

[stock prices]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in finance, internet, mathematics, web and tagged , , , , , , , , , , , , , . Bookmark the permalink.

17 Responses to Get stock prices from the internet in C#

  1. List Mail says:

    Beginner developer just looking for quality tips.

  2. Pingback: Graph stock prices downloaded from the internet in C# - C# HelperC# Helper

  3. Jason says:

    This is amazing, thank you!

  4. Pingback: Continuously graph stock prices in C# - C# HelperC# Helper

  5. Jordan says:

    Really helpful.
    Also, I was wondering if this program was adaptable to be able to pull the close price from the last day in the previous month or potentially any previous month of ones choice? Or if it would be possible to change to different financial websites for comparative perspective?

  6. Tom Christian says:

    Thanks for this useful and straightforward article.
    I took one of your online VB classes and it was equally well-done.
    All the best.

  7. Chris says:

    Thank you. This is exactly what i was looking for!
    But how do I get the data from a specific stock exchange, e.g. Xetra? Is there a way to do that?

  8. Pingback: Get stock prices from different exchanges in C# - C# HelperC# Helper

  9. Gajendran says:

    Hi,
    This code not getting quotes from India exchanges. Given symbol SBI.NS

    • RodStephens says:

      The only issue I know of is that the server returns nothing if the exchange is closed at the time. (It’s closed now so I can’t test it.)

      If that’s not the issue, then I don’t know what’s wrong.

  10. Glenn C. says:

    I am not a Web software guy so feel free to point and laugh. I basically implemented the code given above and am getting an exception thrown with the following error message: “The remote server returned an error: (403) Forbidden.” Here is the URL info being sent to Yahoo – I want to get different info but thought I would test it first with the tags you used – “http://download.finance.yahoo.com/d/quotes.csv?s=T+ED&f=sl1d1t1c1” Thanks in advance for any help.

  11. Glenn C. says:

    OK, it looks like maybe Yahoo discontinued this service on 2 Nov. Is that what you have seen?

    • RodStephens says:

      I think you’re right. This isn’t the first time I’ve seen this sort of service disappear. It’s too bad because this one was reasonably easy to use.

      They say their terms of service were being violated. It’s possible someone was spamming their web pages. All of these services limit the number of queries per hour.

  12. Glenn C. says:

    I eventually found this post on a Yahoo forum. I’m new to C#, think old dude + COBOL, Fortran, C, C++, VB6, and really like your site, thanks for doing this. https://forums.yahoo.net/t5/Known-issues-and-updates/Yahoo-Finance-API-disabled/m-p/392760#M14

Leave a Reply to Chris Cancel reply

Your email address will not be published. Required fields are marked *