Showing posts with label Candlestick. Show all posts
Showing posts with label Candlestick. Show all posts

Tuesday, 31 December 2013

11 RIL stock data from Quandl - Filtered on a range of dates

This is an improvement on the chart shown in the previous post where NSE data was picked up in CSV format from Quandl - an excellent source of global timeseries data -- and shown in a candlestick format. Since the data that we are plotting this time, Reliance share prices, goes back a long time. We will be using a RangeFilter to choose the start and end dates of our plot. The big challenge in this case was to convert the date data obtained from Quandl which was in STRING format into the DATE format that is required by the  RangeFilter. This was done by using the code very kindly provide by ASGALLANT.The final chart is seen on this html page and also in this blog page.

Vizualyse PK



<head>
   <title>Vizualyse PK</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> 
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> -->
   <script type='text/javascript'>
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart","controls"]});
   google.setOnLoadCallback(drawCandlefromQuandlPK);
//-------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------
   function drawCandlefromQuandlPK(){
   
   var dashboardPK = new google.visualization.Dashboard(
       document.getElementById('div_dashboardPK'));
//----------------------------------------------------------------------------------------------------------------------------------------       
   var controlPK = new google.visualization.ControlWrapper({
     'controlType': 'ChartRangeFilter',
     'containerId': 'div_controlPK',
     'options': {
       // Filter by the date axis.
       'filterColumnIndex': 0,
       'ui': {
         'chartType': 'LineChart',
         'chartOptions': {
  //         'chartArea': {'width': '90%'},
           'hAxis': {'baselineColor': 'none'}
         },
         // Display a single series that shows the closing value of the stock.
         // Thus, this view has two columns: the date (axis) and the stock value (line series).
         'chartView': {
           'columns': [0, 4]
         },
         // 1 day in milliseconds = 24 * 60 * 60 * 1000 = 86,400,000
         'minRangeSize': 86400000
       }
     },
     // Initial range: 2007-11-31 to 2008-09-31.
     'state': {'range': {'start': new Date(2007, 10, 31), 'end': new Date(2008, 8, 31)}}
   });
 //--------------------------------------------------------------------------------------------------------------------------------------------
   var chartPK = new google.visualization.ChartWrapper({
     'chartType': 'CandlestickChart',
     'containerId': 'div_chartPK',
     'options': {
       title: "Reliance Stock Prices at NSE from Quandl",
       // Use the same chart area width as the control for axis alignment.
//       'chartArea': {'height': '80%', 'width': '90%'},
//       'hAxis': {'slantedText': false},
          'vAxis': {'viewWindow': {'min': 0, 'max': 3500}},
       'legend': {'position': 'none'}
     },
   });
//--------------------------------------------------------------------------------------------------------------------------------------------
     // grab the CSV
         //  $.get("https://www.quandl.com/api/v1/datasets/NSE/RELIANCE.csv?&trim_start=1998-03-20&trim_end=2013-12-27&collapse=weekly&
         $.get("https://www.quandl.com/api/v3/datasets/NSE/RELIANCE.csv??&auth_token=xxxxxxxxxxxxxxxxxxxxx&trim_start=1998-03-20&trim_end=2013-12-27&collapse=weekly&sort_order=desc", function(csvStringPK) {
         // transform the CSV string into a 2-dimensional array
            var arrayDataPK = $.csv.toArrays(csvStringPK, {onParseValue: $.csv.hooks.castToScalar});
         // this new DataTable object holds all the data
            var dataPK = new google.visualization.arrayToDataTable(arrayDataPK);
            
         // this view selects only a subset of the data, that is columns 0,3,1,5,2 that is appropriate for the candlestick chart
         // more importantly it converts the 0th column from string to date using the example given in http://jsfiddle.net/asgallant/8RFsB/1/
         // the string to date conversion is very important as otherwise the ControlWrapper will not work
            
            var viewPK = new google.visualization.DataView(dataPK);
            viewPK.setColumns([{
                type: 'date',
                label: dataPK.getColumnLabel(0),
                calc: function (dt, row) {
                    // split the string into date and time
                    var valArr = dt.getValue(row, 0).split(' ');
                    // split the date into year, month, day
                    var dateArr = valArr[0].split('-');
                   // create a new Date object from the data
                   // note that we subtract 1 from the month to convert to javascripts 0-index
                   var date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2]);
                  // return the date and the formatted value as set in the original DataTable
                  return {
                      v: date,
                      f: dt.getFormattedValue(row, 0)
                  };
               }
          }, 3, 1,5,2]);
            
  //-----------------------------------------------------------------------------------------------------------------------------------------------          
    
        dashboardPK.bind(controlPK, chartPK);
        dashboardPK.draw(viewPK);
         });
   }
   </script>
</head>
<body>
<div id="div_dashboardPK">
<div id="div_chartPK" style="height: 600px; width: 900px;">
</div>
<div id="div_controlPK" style="height: 50px; width: 900px;">
</div>
</div>
</body>


an earlier post on dashboards also talks about filters in some detail. however the code is possibly cleaner here.

Sunday, 29 December 2013

10 Plotting NSE stock price data from Quandl

Quandl is a really fantastic source for all kinds of really useful financial data. For example you can see historical data on Tata Steel stock prices here. We will use this data to plot a Google Candlestick chart that shows open, close, high, low data for the Tata Steel stock both in a regular HTML page and in the blog below.

Google Chart Example


There are couple of interesting things in the following code that are interesting to know about.

  • While pulling the CSV data from Quandl, you can specify the start/end dates and the level of aggregation, that is daily, weekly, monthly
  • Google Candlestick charts expect the data to be in a certain order. Quandl provides the data in a different order and the columns needs to be rearranged. Hence the data table called "data" is converted into a view called "view" where we select columns 0,1,2,3,5 and reorder them into 0,3,1,5,2
  • This view and not the data is used to draw the chart



<head>
   <title>Google Chart Example</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> -->
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> -->
   <script type='text/javascript'>
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart"]});
   google.setOnLoadCallback(drawCandlefromQuandl);
  
   function drawCandlefromQuandl(){
     // grab the CSV
         $.get("https://www.quandl.com/api/v3/datasets/NSE/TATASTEEL.csv?api_key=xxxxxx.xxxxx&collapse=weekly&start_date=2012-12-31&end_date=2014-12-31", function(csvString) {
         // transform the CSV string into a 2-dimensional array
            var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
         // this new DataTable object holds all the data
            var data = new google.visualization.arrayToDataTable(arrayData);
         // this view can select a subset of the data at a time
            var view = new google.visualization.DataView(data);
            view.setColumns([0,3,1,5,2]);
         var options = {
         title: "Tata Steel NSE Stock Prices from Quandl",
          hAxis: {title: view.getColumnLabel(0), minValue: view.getColumnRange(0).min, maxValue: view.getColumnRange(0).max},
          vAxis: {title: "Price in INR"},
          legend: 'none'
          };
          var chart = new google.visualization.CandlestickChart(document.getElementById('QuandlCandle'));
          chart.draw(view, options);
         });
   }
   </script>
</head>
<body>
   <div id="QuandlCandle" style="width: 900px; height: 500px;"> </div>   
</body>



Quandl provides a huge amount of data and this makes the chart rather clumsy. Our next step would be to see how to provide a control so that you can specify the dates of your data rather than hardcoding the same into the java script.