Random Walks For Windows Phone 7

WinP7MiniTutorialLogoFramed_thumb

It makes me a little crazy that every time the markets go up or down the newspapers cannot resist attributing a reason (though they’re not so good at predicting!).  Today’s NY TimMarket Predictores: “Markets down 2% on concerns about slowing economy.”  Oh Yeah? How do they know that’s the reason?  Maybe it is the cost of oil, the situation in the middle east, unemployment, gamma waves…   So I decided to try an experiment: let’s predict up or down randomly, and give reasons, and we’ll see how well we do.

Now, I believe in modeling that ADHD and other such things are nothing to be ashamed of. Simple brain chemistry; doesn’t make you a bad person.  But what many folks don’t realize is that ADHD involves hyper-focus as much as inattention, and so setting off to build a simple random number generator… well the truth is I already have one. But what a great opportunity to build a Win Phone Application. So, I got this working in 20 minutes. And then tinkered for a few hours.

[Click on image to see full size]

The application itself is pretty simple, just a single page that displays a scrollable  list of 30 days worth of randomly generated predictions.

Let’s take a quick look at the code.

Here’s the markup for the Content Grid in MainPage,

<StackPanel x:Name="TitlePanel"
            Grid.Row="0"
            Margin="24,24,0,12">

   <TextBlock x:Name="ApplicationTitle"
              Text="Market Predictor"
              Style="{StaticResource PhoneTextNormalStyle}" />
   <TextBlock x:Name="PageTitle"
              Text="Next 30 Days"
              Margin="-3,-8,0,0"
              Style="{StaticResource PhoneTextTitle1Style}" />

</StackPanel>

<Grid x:Name="ContentGrid"
      Grid.Row="1">

   <ListBox x:Name="MainListBox"
            ItemsSource="{Binding}">
      <ListBox.ItemTemplate>
         <DataTemplate>

            <TextBlock x:Name="ItemText"
                       Text="{Binding DateAndPrediction}"
                       Style="{StaticResource PhoneTextNormalStyle}"
                       FontSize="18"/>

         </DataTemplate>
      </ListBox.ItemTemplate>
   </ListBox>

</Grid>

Note that the ListBox’s ItemsSource is set to Binding with no binding path. This causes it to bind to the page, and we’ll set the data context dynamically. Also note that I wanted finer control over the font size, and so modified the standard style with a fontsize attribute in the DataTemplate

For this quick and dirty application I did not use MVVM (sometimes you just don’t!), and all the code is in MainPage.xaml.cs.

Predictions

The list box will be populated with predictions, and so I’ve created a small class to manage that information.  Each instance has three properties:

  1. The date for the prediction
  2. Whether the market will be up or down
  3. One of half a dozen standard “reasons.”
public class Prediction
{
    private Dictionary<int, String> Reasons =
            new Dictionary<int, string>();

    public Prediction ()
    {
        Reasons.Add( 0, "Jobs predictions" );
        Reasons.Add( 1, "Economic forecasts" );
        Reasons.Add( 2, "the Cost of Oil" );
        Reasons.Add( 3, "Congressional action" );
        Reasons.Add( 4, "President Obama's statement" );
        Reasons.Add( 5, "the OMB");
        Reasons.Add( 6, "economic trends");
    }

    public string PredictionDate { private get; set; }
    public bool PredictionBool { private get; set; }
    public int PredictionReason { private get; set; }

    public string DateAndPrediction
    {
        get
        {
            string reason = PredictionReason > 0 &&
                            PredictionReason < Reasons.Count
                                ? Reasons[ PredictionReason ]
                                : Reasons[4];
            return PredictionDate + ": " +
                   (PredictionBool
                        ? "Up"
                        : "Down") + " on news of " + reason;
        }
    }
}

The public property DateAndPrediction returns a string that will be displayed in the list box, and it is to this property that the TextBlock in the DataTemplate binds.

OnNavigatedTo

When the page is navigated to the OnNavigatedTo event handler is called. In this method we do three things:

  1. Call the base class
  2. Call a private helper method SetData() to set up the predictions
  3. Set the data context to the collection of predictions defined as a member variable of the class.
protected override void OnNavigatedTo( NavigationEventArgs e )
{
    base.OnNavigatedTo( e );

    SetData();
    if ( DataContext == null )
        DataContext = Predictions;
}

SetData

All the fun happens in SetData.  We’ll create an array to compute the number of days in each month and a Dictionary for the month names.  With those ready, we can compute the current date and then create predictions for the next ten days.

private void SetData()
{

    int month = DateTime.Now.Month;
    int date = DateTime.Now.Day + 6;
    int[] daysInMonth = {
                          31, 28, 31, 30, 31, 30, 31,
                          31, 30, 31, 31, 31
                      };
    var monthNames = new Dictionary<int, string>
                         {
                             {1, "Jan"},
                             {2, "Feb"},
                             {3, "Mar"},
                             {4, "Apr"},
                             {5, "May"},
                             {6, "June"},
                             {7, "Jul"},
                             {8, "Aug"},
                             {9, "Sept"},
                             {10, "Oct"},
                             {11, "Nov"},
                             {12, "Dec"}

                         };

    var r = new Random();

    for ( int i = 0; i < 30; i++ )
    {
        var prediction = new Prediction();
        if ( ++date > daysInMonth[ month - 1 ] )
        {
            ++month;
            if ( month > 12 )
            {
                month = 1;
            }
            date = 1;
        }
        string newDate = monthNames[ month ] + " " +
                         date;
        prediction.PredictionDate = newDate;
        int randomNumber = r.Next( 0, 100 );
        prediction.PredictionBool = randomNumber %2 == 0;
        prediction.PredictionReason = r.Next(0, 6);
        Predictions.Add( prediction );
    }
}

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Mini-Tutorial, News, WindowsPhone and tagged , . Bookmark the permalink.

2 Responses to Random Walks For Windows Phone 7

Comments are closed.