imageIn this article I’ll take you, step by step, through everything you need to do to build, run, and test a real-world Windows Phone 8 app that’s useful while also being fun and interesting. You’ll build an app that downloads data about the trading prices for a stock ticker that your user enters, performs an analysis on the current price of the stock relative to its historic price using a ‘trading bands’ technique, makes a judgment on the purchase opportunity of the stock at the moment, and renders this as a color.

Before you get started, you’ll need a Windows 8 development environment set up and ready to go. This article ‘Getting Started with Windows Phone 8 Development’ is a good place to start. It guides you through getting the tools and installing and making sure that they work.

Step 1.  Create the UI

For the tutorial, I’m keeping the UI of the app as simple as possible. It’s up to you to replace this with something a bit more polished! The UI will simply be a TextBox where the user can type the ticker for their desired stock, a button that they will press to begin the action of downloading and analyzing the price history for the stock, and a rectangle where the color for the analysis will be returned.

Note: Generally stock applications have a primitive color visualization of red or green, where red means the stock price has gone down in the last trade, and green means it has gone up. This is not a good indicator of whether it’s a good opportunity at this moment to purchase the stock. The app you’ll build in this article is much more sophisticated – analysing historic trends, and making a judgement as to whether the current price is a good opportunity to buy (green, with higher intensity indicating better opportunity) or a good opportunity to avoid buying (or sell if you have it), in red, with a higher intensity meaning that it’s time to avoid, or sell.

Create a new Windows Phone 8 app in Visual Studio, and edit the ContentPanel grid in MainPage.xaml to have this code:

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button Content="Analyze" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click_1" Margin="13,83,0,0"/>
            <Rectangle x:Name="heatView" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="306" Margin="25,150,0,0" Stroke="Black" VerticalAlignment="Top" Width="406"/>
            <TextBox x:Name="txtTicker" HorizontalAlignment="Left" Height="72" Margin="13,11,0,0" TextWrapping="Wrap" Text="MSFT" VerticalAlignment="Top" Width="402"/>

        </Grid>

You’ll see that Button has a click event called ‘Button_Click_1’, so we’ll see how to implement the code behind that in the next step.

Step 2. Download the Price History Data

When the user presses the button, the App will download Price History data for the stock indicated by the ticker that they entered in the TextBox. The Windows Phone 8 SDK provides a ‘WebClient’ class for this functionality. It’s in the System.Net namespace.

WebClient gives you an asynchronous download mechanism whereby you tell it to download data, and it calls you back once the data is done.

The data itself will come from Yahoo in CSV (Comma Separated Value) format. To get the data for any stock, you simply call the following URL (for example for Microsoft MSFT):

http://ichart.finance.yahoo.com/table.csv?s=MSFT

So, upon the button press, you’d have the following code:

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            WebClient wc = new WebClient();
            string strTicker = txtTicker.Text;
            wc.OpenReadCompleted += wc_OpenReadCompleted;
            wc.OpenReadAsync(new Uri("http://ichart.finance.yahoo.com/table.csv?s=" + strTicker));
           
        }

Now, upon pressing the button, your phone will go out and download the CSV data for the stock, and call back to wc_OpenReadCompleted when it’s done. You’ll see how to parse the data from that in the next step.

Step 3. Parse the Price History Data

The data you get back from the Yahoo Price History service is Comma Separated Values which look like this:

Date,Open,High,Low,Close,Volume,Adj Close
2013-01-31,27.79,27.97,27.40,27.45,50530000,27.45
2013-01-30,28.01,28.19,27.76,27.85,43580

The first line in the file is the columns, where each value is divided by a comma. Each line then has the corresponding data for that column. So, in this case there are 7 columns (Date, Open, High, Low, Close, Volume, Adjusted Close), and each line of data has 7 values, one for each of the columns.

This makes parsing the data quite easy. So, for example if you want the Adjusted close price for the stock, you simply read each line as a string, split it based on the ‘,’ character, and take the 7th item. It’ll be a string, so convert it to a number.

One way to do this is as follows:

Create a List<double> to hold the closing prices:

List<Double> ClosingPrices = new List<double>();

I put this as a module level variable so it can be shared among functions.

Then, populate this with the closing values upon wc_OpenReadCompleted firing:

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  // Clear the List<> of closing prices
  ClosingPrices.Clear();
  // We're going to keep a total of all stock closing prices to be used later in the analytics
  nTotal = 0;
  // WebClient returns a Stream, so load this into a Stream variable
  System.IO.Stream yData = e.Result;
  // Read the stream with a stream reader
  System.IO.StreamReader sRead = new System.IO.StreamReader(yData);
  // The first line is the headers. Read it and throw it away 
  string strHeaders = sRead.ReadLine();
  // Read the first line of data
  string strValues = sRead.ReadLine();
  int rowsCounted = 0;
  // Read 120 lines of data (4 months) unless there are less than 4 months worth
  while ( (strValues != null) && (rowsCounted < 120) )
  {
    // Split the line of data based on the comma character
    string[] Columns = strValues.Split(',');
    // We count from zero, so even though the character is in the 7th column, it's element 6 in the array
    Double closing = Convert.ToDouble(Columns[6]);
    // Add it to Closing Prices
    ClosingPrices.Add(closing);
    // Update the total with today's closing price
    nTotal += closing;
    // Read the next line
    strValues = sRead.ReadLine();
    // Update the rows we've counted
    rowsCounted++; 
  }

I’ve commented each line to make it clear what it does, but it’s pretty simple – it simply reads through the first 120 lines of the data, pulls the 7th column out, converts it to a double and puts it in the List<double> you created earlier. You could, of course, do more than 120 lines (approximately 4 months worth of data), to get a better historic picture, it’s up to you.

Once you have the data, it’s time to analyze it. You’ll see that in the next step.

Step 4. Calculate the trading bands.

One method of stock price analysis that is surprisingly reliable for judging performance is to take a look at a stock’s trading bands over time. These bands are drawn up based on its lows and highs, and will typically give you a good idea for how the stock will perform in the future. Like with everything else, they’re just an indicator, so please don’t consider this to be investment advice!

A picture’s worth a thousand words, so here’s an example of trading bands calculated using the ‘bollinger band’ technique:

image

The concept is simple – if the current price is at the bottom of the band, it’s generally a good time to buy. If it is near the top, it’s generally a good time to sell. So, for example, this stock was at around 700 in mid September, which would have been a really good time to sell according to this analytic. And it works out right, because within 2 months it had fallen about 20%. Likewise in mid November it was at about 520, and near the bottom, and within a couple of weeks it was close to 580, and near the top, which is a nice profit one could make in 2 weeks!

These bands are surprisingly easy to calculate – the upper band is 2 standard deviations above the moving average and the lower band is 2 standard deviations below it.

This app isn’t going to calculate the full trading band over time, but just what the values would be today, so it takes the average stock price over the last 120 days (or however many days it read), and figures out what the high and low band for them would be.

Here’s the code:

// We kept a total, so the average is the total divided by the amount
Double nAverage = nTotal / ClosingPrices.Count();

// Calculate the standard deviation
Double sum = 0.0;
for (int i = 0; i < ClosingPrices.Count; i++)
{
  sum += Math.Pow(ClosingPrices[i] - nAverage, 2);
}
Double nDeviation = Math.Sqrt(sum / (ClosingPrices.Count - 1));

// Top bollinger is Average + 2xSTD
Double bollingerTop = nAverage + (2 * nDeviation);
// Bottom bollinger is Average - 2xSTD
Double bollingerBottom = nAverage - (2 * nDeviation);

 

Now that we have the trading envelope for today, and we know today’s closing price, let’s figure out where we are relative to the bottom band. Let’s normalize this so that it’s a value between 0 and 1, where 0 means we’re right at the bottom of the band, and 1 means we’re right at the top.

// Top bollinger is Average + 2xSTD
Double bollingerTop = nAverage + (2 * nDeviation);

// Bottom bollinger is Average - 2xSTD
Double bollingerBottom = nAverage - (2 * nDeviation);

// Today's price is the first one we read
Double bCloseToday = ClosingPrices[0];

// Range is the width of the envelope
Double range = bollingerTop - bollingerBottom;

// Value is how high we are above the bottom
Double value = bCloseToday - bollingerBottom;

// If we device the value by the range, we have a normalized indicator of where we are in the envelope
Double score = (value / range);

So now that we have the score, we can turn that into a color, you’ll see that in the next step.

Step 5. Visualizing the Score with Color

We want to use Green to show that today’s price is good for buying, and Red is bad for buying (or conversely good for selling).

Colors are represented using RGB values, with R=Red level, G=Green level and B=Blue level. Each level has 256 values in 24-bit color, so the ‘brightest’ red will be 0xFF0000, and the ‘brightest’ green will be 0x00FF00.

So, if our score for today’s stock price relative to the trading envelope is 0, we are at the bottom of the band, so we should paint the rectangle 0x00FF00, and if it is 1, we are at the top of the band, and we paint the rectangle with 0xFF0000.

Of course we are likely in between the two, so we want to map our current value to something between 0xFF0000 and 0x00FF00 to give an ‘intensity level’.

Here’s the code to do this:

// This is the bottom value (Green)
Double heatVal = 0x00FF00; // (0x00FF00)

// This is the heat range, i.e. the difference between red and green
long heatRange = 0xFF0000 - 0x00FF00; // Red is 0xFF0000, Green is 0x00FF00. Subtract one from the other to get the range.
            
// Our value is then the bottom value plus the amount of the range we should move 'up' by
// So, for example if our score was 0, we'd stay at green. If our score is at .5 we'd move up to the half way point
// between Red and Green, which would be Green + half the range between red+green etc.
heatVal += heatRange * score;

// Now that we have our color, how do we turn it into a brush?
long heatValBits = (long)heatVal;

// Here's the red value -- shift the bits 0x10 to the right and AND them with FF
byte redByte = (byte) ((heatValBits >> 0x10) & 0xFFL);

// here's the green value -- shift the bits 0x08 to the right and AND them with FF
byte greenByte = (byte) ((heatValBits >> 8) & 0xFFL);

// Now we know what the Red and Green attributes for our desired color are, we can use a Color object to create them
Color heatColor = Color.FromArgb(255, redByte, greenByte, 0);
// And then turn that into a brush
Brush heatBrush = new SolidColorBrush(heatColor);
// And then fill the rectangle with this brush
heatView.Fill = heatBrush;

 

And that’s everything you need to build this app. Below are a couple of screen shots of it in action today (February 11, 2013). Let’s see if it’s advice turns out to be correct! :)

image image image

MSFT = Bright Green = Strong Buy

IBM = Brightish Red = Avoid/Sell

Goog= Dark Green = Buy, but not strong buy.

This is for educational use only. Do not buy or sell stock based on this app.

You can download the source code here.