Title: Graph historical stock prices in C#
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.
Note that the format of the returned string has changed so this example no longer works. You will have to modify it to work with the new format. (I'm not going to do that because then I'll need to update it every time the returned data changes.)
|
Download the example to experiment with it and to see additional details.
|