Thursday, June 26, 2014

F# example: Getting live stock ticks through Google Finance API

NOTE: This article demonstrates how F# in conjunction with Reactive Extensions can be used to connect to live data streaming. The full project with example client can be found at This Github link.

Disclaimer

I do not  take any responsibility of the code and any damages caused by it. Code which is provided AS IS is only for demonstration purposes and in no way encourages anyone to use Google Finance API for business. 

Introduction

It has been a week learning F# and I have finally converted my C# code that uses Google Finance API to F#

Here is what my code does. In simple words, it gives you back the IObservable<Tick> for one security (or symbol)

Here is the screenshot of how it looks like


Here is how you use it as a library in C#
 DataMachine machine = new DataMachine();  
 IObservable<Tick> appleTicker = machine.GetStockQuote("AAPL"); // Get Apple's stock prices  
 appleTicker.Subscribe(tick => {  
        // Everytime price changes, this piece of code will be called and an   
       // An object of Tick will be supplied as tick  
       // You can either add them to your Graph series to plot live chart  
       // Or save them to CSV  
       });  

Google Finance API

The simple finance API by Google is just a URL that takes symbol in 'q' GET parameter (or query string parameter). The following will give you the current price data for Yahoo in Json format.


How it works ?

It creates a thread using TaskFactory which queries Google Finance every 1 second, fetches the price and if there is a change in price produces the output into the Observable. Google Finance API gives back Json object. I am using Json.Net library by James-Newton King to parse that.

Here is the type definition of Tick
 type Tick() =   
     [<JsonProperty(PropertyName = "t")>]   
     member val Symbol = Unchecked.defaultof<string> with get, set  
     [<JsonProperty(PropertyName = "l")>]  
     member val Price = Unchecked.defaultof<float> with get, set  
     [<JsonProperty(PropertyName = "lt_dts")>]  
     member val LastUpdated = Unchecked.defaultof<DateTime> with 

Here is the code for DataMachine type
 type DataMachine() =   
   member this.GetLiveGoogleApiTicks(symbol : string) =  
     //google_api queries Google APi every second and produces the string output  
     let google_api (symbol : string) =  
       // When operation is cancelled by the caller, this variable will be modified  
       let cancelled = ref false  
       let operation(o : IObserver<string>) =  
         //Time to wait before fetching again through the API  
         let timeToSleep = TimeSpan.FromSeconds(1.0)  
         //Google Finance API , notice q is the query string parameter for symbol  
         let urlBuilder = new StringBuilder("""http://www.google.com/finance/info?q=""")  
         urlBuilder.Append symbol  
         let url = urlBuilder.ToString()  
         let client = new WebClient()  
         let cancelToken = Task.Factory.CancellationToken  
         client.BaseAddress = url  
         let task() =  
               try  
                 while not cancelToken.IsCancellationRequested && not !cancelled do  
                   let data = client.DownloadString url  
                   //Produce the item in observable  
                   o.OnNext data  
                   Thread.Sleep timeToSleep  
                   while client.IsBusy do  
                     Thread.Sleep 100  
               finally  
                   ignore  
         Task.Factory.StartNew task       
         let a = new Action(fun () -> (cancelled := true))  
         a |> Disposable.Create  
       Observable.Create(operation)  
     let strings = (google_api symbol)  
     // Eliminate unparseable characters for Json.Net library  
     let trimmed = strings.Select (fun (l:string) -> l.Substring(l.IndexOf("[") + 1, l.LastIndexOf("]") - 2 - l.IndexOf("[") + 1))  
     //Parse into object and return the IObservable<Tick>  
     trimmed.Select(fun (l:string) -> JsonConvert.DeserializeObject(l)).DistinctUntilChanged(fun (a:Tick) -> a.Price)
     

Remember to add Rx-Main and Json.Net from Nuget in your project and add appropriate 'open' declarations for namespaces.


Download the code


The fully functional project with sample client for this project can be found at This Github link.

Let me know your comments in the section below. If there is anything that I should have done differently, I would love to hear about that.

Happy coding!

24 comments:

  1. It feels awe-inspiring to read such informative and distinctive articles on your websites.
    North Creek Financial

    ReplyDelete
  2. I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed... national savings

    ReplyDelete
  3. Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job! cheaploansdirectory.com

    ReplyDelete

  4. Remember that paying little heed to how much pay you gain, the way to keeping up money related steadiness is through shrewd obligation the board and personal finance planning.Michael

    ReplyDelete
  5. Despite the fact that an ever increasing number of business sectors are getting to be soaked, you can even now exploit them because of the steady increment of the Internet advertise. make money online

    ReplyDelete
  6. This article is an appealing wealth of useful informative that is interesting and well-written. I commend your hard work on this and thank you for this information. I know it very well that if anyone visits your blog, then he/she will surely revisit it again. Instant payday loans

    ReplyDelete
  7. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us. كول كورة

    ReplyDelete
  8. It was wondering if I could use this write-up on my other website, I will link it back to your website though.Great Thanks. Arizona emergency cash

    ReplyDelete
  9. A delightful reading for anyone who loves reading blogs.
    mortgagecalculator.website

    ReplyDelete
  10. I am genuinely thankful to the holder of this web page who has shared this wonderful paragraph at at this place State of Origin 2020live streaming

    ReplyDelete
  11. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. slick cash loan

    ReplyDelete
  12. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. slick cash loan

    ReplyDelete
  13. Hi to everybody, here everyone is sharing such knowledge, so it’s fastidious to see this site, and I used to visit this blog daily imarketslive sign up

    ReplyDelete
  14. I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed... XDCE

    ReplyDelete
  15. Awesome and interesting article. Great things you've always shared with us. Thanks. Just continue composing this kind of post. slickcashloan.com

    ReplyDelete
  16. It would appear to be outlandish for a bank not to give a credit, to a solid private venture. Most brokers feel that there are less organizations to loan to, however are anxious to begin loaning to trustworthy up-and-comers. wells fargo check routing number

    ReplyDelete
  17. When you use a genuine service, you will be able to provide instructions, share materials and choose the formatting style. Azizi Jawad

    ReplyDelete
  18. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information. internal audit management software

    ReplyDelete
  19. The other, more various gathering demonstrates, that an efficient class of credit exists corresponding to the practical classification of finances, by which it underlines difficulty of the credit's presence in the consistence of finances.FinanceSuggest

    ReplyDelete
  20. Illustrious Bank turned down the offer and utilized stores to take care of the cash. Anyway the loan costs didn't descend.FinanceWorldNow

    ReplyDelete
  21. I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks! https://mapsjar.com/

    ReplyDelete
  22. Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. small business marketing firms

    ReplyDelete
  23. Good thing there are alternative service providers who are dedicated in addressing their customers' needs. Here is a list of merchant account providers who cater people with bad credit history namely: North American Bancard Sales Partner

    ReplyDelete
  24. You made some pretty good points. Thanks for posting this!

    Best Education App Ideas is the most important thing for everyone because Education helps in self-development. The App Ideas is leading web and Mobile App development. We provide the best IT Services at best rates. Contact us now!

    ReplyDelete