Showing posts with label Yahoo Finance. Show all posts
Showing posts with label Yahoo Finance. Show all posts

Friday, February 11, 2011

Stock Market Ticker For Website - Getting Historical Data

To get Historical Data from Yahoo Finance, we can use certain parameters in Query String. Check out following query string for NASDAQ (i.e. Symbol "^IXIC");
http://ichart.finance.yahoo.com/table.csv?s=^IXIC&a=01&b=5&c=1971&d=01&e=8&f=2011&g=m&ignore=.csv
 If we analyze above link we can see some parameters varying from a to g. We can use these parameters to filter HISTORICAL data as per our requirement. Each of above parameter (i.e. from a to g) indicates following things
  • s - Ticker symbol.(This parameter is not optional; other parameters are optional)
  • a - Month number, starting with 0 for January.
  • b - Day number, eg, 1 for the first of the month.
  • c - Year.

    End date for historical prices (default is the most current available closing price):
  • d - Month number, starting with 0 for January.
  • e - Day number, eg, 1 for the first of the month.
  • f - Year.
  • g - Possible values are 'd' for daily (the default), 'w' for weekly, and 'm' for monthly.

We can download csv file and modify its URL run time as per our requirements.
Submit this story to DotNetKicks

Read more...

Tuesday, February 1, 2011

Stock Market Ticker For Website - Yahoo Finance API

In My Previous article Stock Market Ticker For Website; we have seen how to USE YAHOO FINANCE URL, i.e. remote CSV file available for Download to use in Stock Market Ticker.

Suppose we want to download and CSV file with Market Indices
But to display various details related to stock market YAHOO Finance has allowed us to take advantage of live data. Do check out my article about Stock Market Ticker For Website

In previous article we use following link to get market data
http://download.finance.yahoo.com/d/quotes.csv?s=^DJI,^IXIC,^GSPC,^FTSE,^GDAXI,^FCHI,^N225,^HSI,^STI,^BSESN,^NSEI&f=sl1c1&e=.csv
Check out "f=sl1c1" this is where we need to apply following code for getting desired details. e.g. if we want to get "day-low,day-high, 52-week low & 52-week high" along with symbol(s), last trade(price)(l1) and change(c1) from YAHOO FINANCE, our "f=sl1c1" will change to "f=sl1c1ghjk". This is very simple, use following table for getting desired data about Stock exchanges or for equities. Yes we can also get Cross Currency rates from YAHOO FINANCE (e.g. Symbol "USDINR=X,USDEUR=X")

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 h Day’s High
j 52-week Low k 52-week High g1 Holdings Gain Percent
g3 Annualized Gain g4 Holdings Gain g5 Holdings Gain Percent (Real-time)
g6 Holdings Gain (Real-time) i More Info i5 Order Book (Real-time)
j1 Market Capitalization j3 Market Cap (Real-time) j4 EBITDA
j5 Change From 52-week Low j6 Percent Change From 52-week Low 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

Download Demo code here --> Stock Market Ticker for Websites(MarketWatch.zip)
Above  demo code is associated with my previous article.


Submit this story to DotNetKicks

Read more...

Wednesday, January 19, 2011

Stock Market Ticker For Website

In this article we shall work out on Live stock market ticker for website. To develop live stock market ticker for website the basic requirement is to have live data. Free live data is available at some cost, but to display tickers on website we can always go for two to three minutes delayed data, which we can download from Yahoo Finance. Yahoo Finance is giving enable use to download CSV file in the manner we want. Once we get the CSV file logic which remains is to display data and Polling of data at certain interval

Check out folder structure of our Demo Code

(Note: Demo contains Cross Currency Data as well; which will be same as Stock market data.)

In this article we shall be considering major stock exchanges, and in demo code we shall see updates related to stock exchanges.
  • DOW (Symbol: ^DJI)
  • Nasdaq (Symbol: ^IXIC)
  • S&P 500 (Symbol: ^GSPC)
  • FTSE 100 (Symbol: ^FTSE)
  • DAX (Symbol: ^GDAXI)
  • CAC 40 (Symbol: ^FCHI)
  • Hang Seng (Symbol: ^HSI)
  • NIKKEI 225 (Symbol: ^N225)
  • Straits Times (Symbol: ^STI)
  • BSE India (Symbol: ^BSESN)
  • NSE India (Symbol: ^NSEI)

If you go to Yahoo Finance and put any of the Symbol you can check all related data. Also that data is allowed to download, we are going to use this downloaded data to display live (little delayed) data to develop Stock Market Ticker for Website. (Note: If you are not aware about ICALLBack Event handler, please refer this article ---> ICallback Event Handler Article
We are going to get data from Yahoo Finance in CSV format. So we shall write logic accordingly. Following is the function to convert CSV in to Data Table.

public static DataTable csvToDataTable(string strData, bool isRowOneHeader)
    {
        DataTable csvDataTable = new DataTable();
        //no try/catch - add these in yourselfs or let exception happen
        String[] csvData = strData.Replace("\r", "").Replace("=X", "").Split('\n');
        //if no data in file ‘manually’ throw an exception
        if (csvData.Length == 0)
        {
            throw new Exception("CSV File Appears to be Empty");
        }

        String[] headings = csvData[0].Split(',');
        int index = 0; //will be zero or one depending on isRowOneHeader
        if (isRowOneHeader) //if first record lists headers
        {
            index = 1; //so we won’t take headings as data
            //for each heading
            for (int i = 0; i < headings.Length; i++)
            {
                //replace spaces with underscores for column names
                headings[i] = headings[i].Replace("", "_");
                //add a column for each heading
                csvDataTable.Columns.Add(headings[i], typeof(string));
            }
        }
        else //if no headers just go for col1, col2 etc.
        {
            for (int i = 0; i < headings.Length; i++)
            {
                //create arbitary column names
                csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
            }
        }
        //populate the DataTable
        for (int i = index; i < csvData.Length - 1; i++)
        {
            //create new rows
            DataRow row = csvDataTable.NewRow();
            for (int j = 0; j < headings.Length; j++)
            {
                //fill them
                row[j] = csvData[i].Split(',')[j];
            }
            //add rows to over DataTable
            csvDataTable.Rows.Add(row);
        }

        //return the CSV DataTable
        return csvDataTable;
    }

Another Important Function for our development of Stock Market Ticker for website is, the function which will call Yahoo Finance to fetch desired data.

We shall user WebRequest Class to call remove CSV file i.e. Read a downloadable CSV file from remote server. Check out following function.

 public DataTable CallYahooFinance()
    {
        WebRequest req = WebRequest.Create(StaticVariables.Markets);
        WebResponse result = req.GetResponse();
        Stream ReceiveStream = result.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader sr = new StreamReader(ReceiveStream, encode);
        string output = string.Empty;
        Char[] read = new Char[256];
        int count = sr.Read(read, 0, read.Length);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            output += str;
            count = sr.Read(read, 0, read.Length);
        }
        output = output.Replace("^DJI", "DOW").Replace("^IXIC", "NASDAQ").Replace("^GSPC", "S&P500");
        output = output.Replace("^FTSE", "FTSE 100").Replace("^GDAXI", "DAX").Replace("^FCHI", "CAC 40");
        output = output.Replace("^HSI", "HANG SENG").Replace("^N225", "NIKKEI 225").Replace("^STI", "STRAITS TIMES");
        output = output.Replace("^BSESN", "SENSEX").Replace("^NSEI", "NIFTY");
        DataTable DT = csvToDataTable(output, false);
        DT.Columns[0].ColumnName = "Market";
        DT.Columns[1].ColumnName = "Last Trade";
        DT.Columns[2].ColumnName = "Change (in %)";
        return DT;
    } 

In above code "output" is the string i.e. CSV string and we have replaced Yahoo Finance Symbols with the Name of the Stock Index.

If you check above function Webrequest.Create Method contains URL. To get CSV File we are using following URL, if you simple copy paste the URL you can download CSV file. URL for Stock Market Ticker is set into Static variable.

public static class StaticVariables
{
public static string Markets = "http://download.finance.yahoo.com/d/quotes.csv?s=%5EDJI,%5EIXIC,%5EGSPC,%5EFTSE,%5EGDAXI,%5EFCHI,%5EN225,%5EHSI,%5ESTI,%5EBSESN,%5ENSEI&f=sl1c1&e=.csv";
}

Thats it now we got the relevant data from yahoo finance which we can display the way we want. We are using ICallback Event handler to poll data from Yahoo Server. Now if you are aware about ICallback Simply check out following functions. Where we are not doing anything special.


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String cbReference =
                Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
            String callbackScript;
            callbackScript = "function CallServer(arg, context)" +
                "{ " + cbReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
        }
    }

Also check Region for ICallback Implementation
public void RaiseCallbackEvent(String eventArgument)
    {
    
    }
    public String GetCallbackResult()
    {
        GridView GridView1 = new GridView();
        GridView1.DataSource = CallYahooFinance();
        GridView1.DataBind();

        return getHTML(GridView1);
    }


public string getHTML(GridView _grid)
    {
        string result = string.Empty;
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            _grid.RenderControl(htw);
            htw.Flush();
             result = sw.ToString();
        }
        return result;
    }
//getHTML returns HTMLString for GRIDView

Now in the HTML of our page we have only following tags.

We use following JavaScript to Fetch live data from server side at the interval of 1000mili second.

function call()
    {
    window.document.getElementById('_polling').style.display="";
    CallServer("", "");
    }
    
     function ReceiveServerData(retValue)
    {   
        document.getElementById("result").innerHTML = retValue;
        window.document.getElementById('_polling').style.display="none";
        setTimeout("call()",1000); //Set polling to 1000mili second
    }

Implementation of above code is very simple check out Demo code for the same.
Download Demo Code here --> Stock Market Ticker For Website.zip Submit this story to DotNetKicks

Read more...