Blogs

Bryan Wood - DevExpress Charts Blog

information and training regarding all things DevExpress Charting.

Financial Charts Part 1–Getting Data and Drawing a Financial Chart

     

In the past we haven’t spent much time covering Financial Charting it’s a not very publicized feature in the XtraCharts platform. In this first post in the series we are going to cover how to draw a financial chart, using data acquired from Yahoo Finance.

Get Data

There are a lot of places you can go to get data. I've chosen Yahoo Finance because it is free, easy to use, and easy to consume.

Here are the steps to get some historical data.

1. Go to http://finance.yahoo.com

2. Enter a ticker and hit Get Quotes

 

Yahoo-Finance---Quote

3. Click Historical Prices (on the left column)

 

Yahoo-Finance-Historical-Quotes

4. scroll to the bottom and click Download to Spreadsheet

Yahoo-Finance-Historical-Spreadsheet

Import the Data

I created a simple csv parser for this demo so that I can share the file along with the source code for this example. but you could do this any number of ways (sql, access, use a csv parser, etc). One of the reasons I did this is that some time in the future I may want to pull the data on demand from the yahoo site so that I can display various charts on demand.

Bar.cs (defines 1 bar worth of stock data):

 

public class Bar
{
    public DateTime Date { get; set; }
    public double Open { get; set; }
    public double High { get; set; }
    public double Low { get; set; }
    public double Close { get; set; }
    public double AdjClose { get; set; }
    public long Volume { get; set; }

    /// <summary>
    /// Initializes a new instance of the Bar class.
    /// </summary>
    public Bar(DateTime date, double open, double high, double low, double close, double adjClose, long volume)
    {
        Date = date;
        Open = open;
        High = high;
        Low = low;
        Close = close;
        AdjClose = adjClose;
        Volume = volume;
    }
}

Stock.cs (contains the parser and collection of bars of data):

 

public class Stock
{
    public List<WebApplication1.Bar> Bars
    {
        get
        {
            return _Bars;
        }
    } private List<WebApplication1.Bar> _Bars = new List<WebApplication1.Bar>();

    /// <summary>
    /// Initializes a new instance of the Stock class.
    /// </summary>
    public Stock(string fileName)
    {
        string[] stockDays;

        if (File.Exists(fileName))
        {
            stockDays = File.ReadAllLines(fileName);

            for (int i = 1; i < stockDays.Length; i++)
            {
                string[] dayValues = stockDays[i].Split(',');

                DateTime date = DateTime.ParseExact(dayValues[0], "yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);
                double open = Convert.ToDouble(dayValues[1]);
                double high = Convert.ToDouble(dayValues[2]);
                double low = Convert.ToDouble(dayValues[3]);
                double close = Convert.ToDouble(dayValues[4]);
                long volume = Convert.ToInt64(dayValues[5]);
                double adjClose = Convert.ToDouble(dayValues[6 ]);

                Bars.Add(new Bar(date, open, high, low, close, adjClose, volume));
            }
        }
        else
        {
            throw new FileNotFoundException();
        }

    }
}

Draw the Chart

The first thing we need to do is to set up the chart (Default.aspx):

 

<dxchartsui:WebChartControl ID="stockChart" runat="server" 
    ClientIDMode="AutoID" Height="400px" 
    IndicatorsPaletteName="Default" Width="800px">
</dxchartsui:WebChartControl>

Standard definition there. we are going to be doing the bulk of the work in the code behind.

Now that we have created the chart we have a few things that need to happen to display the chart.

  1. get the data
  2. define the data series
  3. setup the series
  4. populate the series
  5. attach the series to the chart.

 

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Stock fordHistorical = new Stock(Server.MapPath("table.csv"));
                
        DevExpress.XtraCharts.Series series = new DevExpress.XtraCharts.Series("Ford", DevExpress.XtraCharts.ViewType.Stock);
        stockChart.Series.Add(series);

        SetupSeriesOptions(series);
        PopulateSeries(fordHistorical, series);
    }
}

The SetupSeriesOptions method is where we setup and format the chart to show our stock data in a relevant and useful way.

 

private void SetupSeriesOptions(DevExpress.XtraCharts.Series series)
{
    series.ArgumentScaleType = DevExpress.XtraCharts.ScaleType.DateTime;
    series.Label.Visible = false;

    StockSeriesView myView = (StockSeriesView)series.View;

    myView.LineThickness = 2;
    myView.LevelLineLength = 0.25;

    // Specify the series reduction options.
    myView.ReductionOptions.Level = StockLevel.Close;
    myView.ReductionOptions.Color = Color.Blue;
    myView.ReductionOptions.Visible = true;

    XYDiagram diagram = (XYDiagram)stockChart.Diagram;
    diagram.AxisY.Range.AlwaysShowZeroLevel = false;
    diagram.AxisX.Label.Staggered = true;
}

The ScaleType.DateTime which is how we inform the chart that our x-axis will a Date vs. some other type.

the remainder of the settings are for adjusting various visual settings, if you’d like to discuss some of these further let me know in the comments.

PopulateSeries is where we take the data from the Stock class and populate or above-defined data series. For the time being I’m doing this via a for loop. I plan to refactor this to a straight DataBind in the future.

 

private static void PopulateSeries(Stock fordHistorical, DevExpress.XtraCharts.Series series)
{
    int maxDaysToShow = 20;
    for (int i = 0; i <= maxDaysToShow; i++)
    {
        Bar currentBar = fordHistorical.Bars[i];
                
        series.Points.Add(new SeriesPoint(currentBar.Date, new object[] { currentBar.Low, currentBar.High, currentBar.Open, currentBar.Close }));
    }
}

Results

All done, here is resulting chart

 

Final-Site-Completed-With-Financial-Chart

 

 

In the next part I’ll show how to accommodate the data for Weekends and Holidays and we’ll get into drawing the our new indicators on the chart.

Source Code (xtraFinancialCharts.zip)

Published Nov 03 2010, 12:29 PM by Bryan Wood (DevExpress)
Bookmark and Share

Comments

 

Bryan Wood - DevExpress Charts Blog said:

This is part 2 of a Multi-Part Series you can view Part 1 here: community.devexpress.com/blogs

November 17, 2010 1:56 AM
 

Bryan Wood - DevExpress Charts Blog said:

This is part 2 of a Multi-Part Series you can view Part 1 here: community.devexpress.com/blogs

November 17, 2010 12:17 PM
More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.