Graph historical stock prices in C#

[stock prices]

The key to this example is the GetStockPrices method shown in the following code.

// Get the prices for this symbol.
private List GetStockPrices(string symbol)
{
    // Compose the URL.
    string url = "http://www.google.com/finance/" +
        "historical?output=csv&q=" + symbol;

    // Get the web response.
    string result = GetWebResponse(url);

    // Get the historical prices.
    string[] lines = result.Split(
        new char[] { '\r', '\n' },
        StringSplitOptions.RemoveEmptyEntries);
    List prices = new List();
    // Process the lines, skipping the header.
    for (int i = 1; i < lines.Length; i++)
    {
        string line = lines[i];
        prices.Add(float.Parse(line.Split(',')[4]));
    }

    return prices;
}

This method composes a URL of the form http://www.google.com/finance/historical?output=csv&q=DIS where DIS is a stock ticker symbol. The Google website returns historical stock data for that symbol in the form of a CSV (comma-separated value) file. The program breaks the file into lines and saves the prices in a List of float that it returns to the calling code.

For additional information about how the program works, including how it draws the graph and how the GetWebResponse method works, download the example and look at the code.


Download Example   Follow me on Twitter   RSS feed   Donate




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

Leave a Reply

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