Getting Stock Prices with F# (1)

So how we get the stock prices for our F# program?

Well Yahoo of course.

Luca Bolognese's WebLog has a great writeup of how to download stock prices from Yahoo's finance site.  I have borrowed liberally from his work and made some tweaks of my own.

The first part of my F# code is:

#light
open System
open System.Collections.Generic
open System.IO
open System.Data.SqlClient
open System.Text.RegularExpressions
open System.Net

[<Measure>] type dollars
[<Measure>] type volume

We immediately run into two statements for setting up units of measure.  The statement [<Measure>] type dollars identifies a unit of measure named dollars in our program.

Now what are units of measure?

In F#, you can set up floating point numbers as certain unit of measure types.  The F# compiler will ensure that certain mathematical operations are only performed on variables with the same measure type.  For example, if I try to add apples and oranges:

let a = 10.0<dollars>
let b = 20.0<volume>
let c = a + b

I get a compiler error: "The unit of measure 'volume' does not match the unit of measure 'dollars'"

Now this is legal:

let a = 100.0<dollars>
let b = 20.0<volume>
let c = a / b

and the result c would be 5.0 of type <dollars> per <volume>.

Also, the F# compiler is smart enough to allow:

let d = 500.0<volume> * c

and it knows that if I multiply a <volume> times a number expressed as  <dollars> per <volume> that the result must be of type <dollars>.

Also, according to our friends at Microsoft:

"Units of measure are used for compile-time unit checking but are not persisted in the run-time environment. Therefore, they do not affect performance."

Now a piece of trivia: Do you remember NASA's Mars Climate Orbiter? It was lost in September 1999 because some engineer messed up the converting metric to English units of measurement.  With the introduction of units of measure in F# we can prevent operations that use inconsistent units of measure.  This is very cool.

The one gotcha I ran into was with the printfn function:

printfn "d = %8.2f" d

This expression throws a type mismatch because d is not a float, but of type <dollars>

What I finally ended up doing was writing a function toFloat:

let toFloat (someBucks : float<dollars>) =
     someBucks / 1.0<dollars>
    
printfn "d = %8.2f" (toFloat d)

and then this works.  In the toFloat function I just divide an input of type <dollars> by 1.0<dollar> which F# then know is just a floating point number.  I couldn't find another way around this problem.  Anyone know a better answer?

The next part of my code creates several useful types.

type Span = { Start: DateTime; End: DateTime }

type Price = { Open: float<dollars>; High: float<dollars>; Low:float<dollars>;   Close:float<dollars>; Volume: float<volume>}

type Event =
    | StkPrice of Price
    | Split of float
    | Dividend of float<dollars>

type Observation = { Date: DateTime; Event: Event}

The 'Span' type is basically used to create a date range variable type.

The 'Price' type defines a daily stock price: the opening price, the high for the day, the low for the day, the closing price, and the volume.

The 'Event' type needs a little explaining.  It is not a Record type, but It is what is called a "Discriminated Union."  What the heck is that?

From what I can figure, it is a variable that can morph itself into any of the listed options.  Thus, the type Event can be a StkPrice (which is of type Price), or a Split (which is of type float),  or a Dividend (which is of type <dollars>

If you look at the next line:

type Observation = { Date: DateTime; Event: Event}

We have a type called observation which consists of a date and an event.  But, an event can have one of three types: a stock price, a dividend, or a split.  Thus, we could have a list of Observations (that are by definition of the same type, but they can each represent one of three events.  Or, we could have a function that takes an Event type as an argument that would allow a stock price, a dividend, or a split to be passed in.  I will explain more of this latter when we actually use the Event type.

Now let's look at some code.  The following three statements have the identical meaning:

let aSplit0 : Event = Event. Split(2.0)
let aSplit1 = Event.Split(2.0)
let aSplit2 = Split(2.0)

They all say assign the value of 2.0 to a variable of type Event that masks a float named Split.  Note that in the first two examples, I use the dot (.) notation, which in the .Net editor uses Intellisense.  The third example is too terse for my liking, buy you can see that the F# compiler can look through the Event type and resolve it's type to the float named Split.

Here are two examples how how to instantiate Event values:

let aPrice : Event = Event.StkPrice{Open = 48.25<dollars>; High = 50.50<dollars>; Low = 47.25<dollars>; Close = 50.0<dollars>; Volume =21221.0<volume>}

let aDiv = Event.Dividend(2.50<dollars>)

I suppose a Discriminated Union is like a Variant (in VB6) or an Object in .Net whose underlying type is limited to those that you specify, instead of anything.  I presume this allows the compiler to early bind instead of late bind the variables.

 

Print | posted @ Thursday, June 25, 2009 11:20 AM

Comments on this entry:

Gravatar # re: Getting Stock Prices: F# & NHibernate (2)
by Microsoft Office 2007 at 7/15/2010 11:53 PM

Office home and student 2007
Office 2007 home and student
  
Gravatar # re: Getting Stock Prices with F# (1)
by deexu at 7/16/2010 1:33 AM

great range of Ed Hardy products. Ed Hardy Women's Ellerise Lowrise Sneaker · Ed Hardy Women's
ed hardy jeans, ed hardy hoody, ed hardy shirt, ed hardy clothing, ed hardy cap, ed glasses, ed belts,
women fashion shoes, men's clothes. helping .perhaps you will like
Ed Hardy
Ed Hardy shoes
Ed Hardy shirts
Ed Hardy clothes
Ed Hardy clothing
Ed Hardy shoes
Don Ed Hardy is an American tattoo collector raised in Southern California
Ed Hardy Clothing,Christian Audigier,Ed Hardy Shoes,Ed Hardy Swimwear,Ed Hardy Hat,
ED Hardy Caps
Ed Hardy Sunglasses
Ed Hardy Wallets
EdHardy
Gucci outlet store online, numerous cheap Gucci bags, handbags, wallets, purses, totes, shoes on sale,
cheap prices and authentic qualities
gucci handbags
gucci jewelryRTBFB NLK
  
Gravatar # nike air max 2010
by nike air max 2010 at 7/23/2010 7:34 AM

In recent years, with the introduction of air max ltd, air max nike ace of running shoes in this family have given up years are

named. But this change has not been authorized shoe fans, nike air max ltd generations of the market performance can only be said to be unsatisfactory. Nike finally entered in

2009 decided to resume the traditional name, launched a revival of hope carrying air max 2009 and air max

2010
, not only followed the 360 air-cushion, but the introduction of the most popular of flywire technology and nike air max, as long the air max running

shoes
quiet family brings a gratifying new look
In 2009, NIKE developed the nike air max 2009 and womens air max 2009 shoes,and in

2010,continued to design new air max as nike air max 2009 iv shoes and nike air max 2009 leather SI shoes,in 2010 developed new nike air max

tailwind
called nike air max 2010, air max shoes technology to achieve the ultimate,now,not only have many air max classic shoes as nike air max classic bw,nike air max

95
,nike air max 90 and nike air max tn,but also have many new hot sale style,nike air max 2009 mesh shoes and nike air max

2010 mesh shoes

womens air max 2010 or womens air max other style running shoes, emphasis was put runners were wearing more

comfortable feeling and better athletic performance. In the free end of the bubble structure of the whole air-cushion technology to give you a whole new feeling to walk --- even more flexible more stable and more comfortable. revolutionary air cushion

system into the air max 2009 nike running shoes Full length cushion technology. In order to provide a total feel most comfortable wearing, a pair of sports shoes in the use of so

many air-cushion technology.
  
Gravatar # re: Getting Stock Prices with F# (1)
by lv handbags at 7/24/2010 7:44 AM

balenciaga Handbags are one of the most common bags for women. They come in a variety of silhouettes and sizes. Surely in the domain of classiness,balenciaga handbags get the maximum grade. What are the latest trends adopted by balenciaga Wallets? Frenzy among the fashionable women has been triggered by the Balenciaga Handbags, still new on the market and very likely available wholesale in a few months. Your friends will wonder how you could afford all of those high quality hand bags and be jealous of your fashionable purses. since you are going to have the latest high priced fashion on your arms,everyone will wonder what your secret is.
  
Gravatar # re: Getting Stock Prices with F# (1)
by ckangel3 at 7/31/2010 12:26 AM

Tiffany jewelry
mous Tiffany Jewelry Shop which sell directly Tiffany Rings, Earrings, Necklaces, Pendants, Bracelets,
Bangles, Accessories.
Tiffany co jewelry
Tiffany
Tiffany Bracelets
affordable tiffany jewelry, beautiful discount tiffany rings, tiffany necklaces,tiffany Pendants,
tiffany earrings and tiffany Bracelets.
Tiffany Charms
Tiffany Earrings
Tiffany Necklaces
Tiffany Rings
Tiffany Jewelry Online,Discount Tiffany & Co Jewelry On Sale,you can buy cheap Tiffany silver.
All jewelry come with Tiffany package
links of london
Tiffany co jewelry
links london
links of london jewellery

  
Gravatar # re: Getting Stock Prices with F# (1)
by lv handbags at 8/2/2010 3:50 AM

Welcome to www.weblvonline.com. We are continually updating and adding more and more products from famous brand such as: Louis Vuitton,Gucci,Chanel,Balenciaga and more! Such as,all luxury handbag of the materials are exactly the same as the genuine and all the products are produced with elaborate technique. . . All Handbags Accessories also come with a dust cover, certificate of replica louis vuitton handbags authenticity card and care booklet. All customers will receive free shipping on all orders! We will send you the goods in 24 hour and then the tracking number.


Quality which are almost as excellent as originals. Our site has a variety of collections of discount louis vuitton handbags replicas so you may always find a luxury one that can catches your eyes, yet remain the fact that the price is rather competitive comparing with an original one. www.weblvonline.com is experienced in dealing in fake Designer cheap louis vuitton handbags. Our manufactures have paid close attention to the production and make sure they are up to standard to meet our Our site's clients demanding requirements. As our handbags fit your budget as well as your taste, so why hesitate?


www.weblvonline.com is an online store to collect and supply the most great collection and information of louis vuitton handbags,louis vuitton bags,louis vuitton replica,louis vuitton handbags on sale,discount louis vuitton handbags,replica louis vuitton handbags,cheap louis vuitton handbags ,from men's to women's, also we can help you to find and compare which best fits you. At weblvonline.com you can buy up to 80% OFF on sale, Big Discount and very Cheap Price!

When you are walking on the road and take a Louis Vuitton Handbag, you would be instantly noticed, and admired by women and men beside you. A LV handbag, not only reflect your high sense of fashion, but also represents your status, confidence and prestige. For many people who has a budget, however, a Louis Vuitton bag could be a cost-prohibitive order.Weblvonline.com will meet your all demands and suffice satisfaction, here have most great collection of all designer handbags and wallets, all and high quality knock off designer bag, same as real and authentic handbags, but cheap price.

Authentic quality louis vuitton handbags, we have louis vuitton bags from SURYA, Mahina, CRUISE 2009, Suhali leather, Damier Canvas, Collection Beach, Nomade Leather, Monogram Vernis, Monogram Denim, Monogram MiniLin, Monogram canvas, Monogram Motard, Monogram Limelight etc. We will meet all your designer handbag demands.
  
Gravatar # re: Getting Stock Prices with F# (1)
by nannan at 9/3/2010 12:34 AM

NVRH FRY GTYT Tiffany jewellery
Tiffany
Tiffany & Co
Tiffany Co Bracelets
I came across a story in the WSJ last week (WSJ August 13th) in which some major food companies were warning of a sugar shortage in the US. Excuse me. A sugar shortage? I'm not making this up. Here's the text of the letter
Tiffany Co Charms
Tiffany Co Earrings
Tiffany sale
Tiffany Co Necklaces
Tiffany uk
Tiffany Co Rings
tiffany jewelry
tiffany co
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 8 and type the answer here: