Historical Volatility

The code snippet is capable of calculating historical volatility using Close Price, High Low Price and Close High Low Price methods. Simply provide symbol, start date and end date of the specific volatility method and it extracts the market data from the yahoo service and calculated the volatility.

open System
open System.IO
open System.Xml
open System.Text
open System.Net
open System.Globalization

let makeUrl symbol (dfrom:DateTime) (dto:DateTime) =
    //Uses the not-so-known chart-data:
    new Uri("http://ichart.finance.yahoo.com/table.csv?s=" + symbol +
       "&e=" + dto.Day.ToString() + "&d=" + dto.Month.ToString() + "&f=" + dto.Year.ToString() +
       "&g=d&b=" + dfrom.Day.ToString() + "&a=" + dfrom.Month.ToString() + "&c=" + dfrom.Year.ToString() +
       "&ignore=.csv")

let fetch (url : Uri) =
    let req = WebRequest.Create (url) :? > HttpWebRequest
    use stream = req.GetResponse().GetResponseStream()
    use reader = new StreamReader(stream)
    reader.ReadToEnd()

let reformat (response:string) =
    let split (mark:char) (data:string) =
        data.Split(mark) |> Array.toList
    response |> split '\n'
    |> List.filter (fun f -> f<>"")
    |> List.map (split ',') 

let getRequest uri = (fetch >> reformat) uri

type MarketData =
    {Date: DateTime;
     Open: double;
     High: double;
     Low: double;
     Close: double;
     Volume: int;
     AdjClose: double;}

let converter (data:List<List<string>>) =
    [for dataArray in data.Tail do
        yield {Date = DateTime.ParseExact(dataArray.[0],"yyyy-MM-dd",CultureInfo.InvariantCulture);
          Open = System.Convert.ToDouble(dataArray.[1]);
          High = System.Convert.ToDouble(dataArray.[2]);
          Low = System.Convert.ToDouble(dataArray.[3]);
          Close = System.Convert.ToDouble(dataArray.[4]);
          Volume = System.Convert.ToInt32(dataArray.[5]);
          AdjClose = System.Convert.ToDouble(dataArray.[6])}]

//Example: Microsoft, from 2010-03-20 to 2010-04-21
//getMarketData "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let getMarketData symbol fromDate toDate = makeUrl symbol fromDate toDate  |> getRequest |> converter

//highLowVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let highLowVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
    let data = getMarketData symbol fromDate toDate
    data
    |> List.fold (fun acc mktdata -> acc + Math.Log(mktdata.High / mktdata.Low) )  0.0
    |> (*) ( 1.0 / ( ( 2.0 * System.Convert.ToDouble(data.Length)) * System.Math.Sqrt(System.Math.Log(2.0)) ) )
    |> (*) (System.Math.Sqrt 252.0)

//closeVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let closeVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
        let data = getMarketData symbol fromDate toDate
        let rec close (dt: MarketData list)  =
            match dt with
            | x::y::[] -> System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)
            | x::y::tail -> System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)  + (close (List.append [y] tail))
            | [] -> 0.0

        let rec close1 (dt: MarketData list)  =
            match dt with
            | x::y::[] -> System.Math.Log(y.Close / x.Close)
            | x::y::tail -> System.Math.Log(y.Close / x.Close)  + (close1 (List.append [y] tail))
            | [] -> 0.0

        let firstValue = data
                            |> close
                            |> (*) (1.0 / (System.Convert.ToDouble(data.Length - 1) - 1.0))

        let secondValue = (System.Math.Pow((close1 data), 2.0)) * ( 1.0 / (System.Convert.ToDouble(data.Length - 1) *(System.Convert.ToDouble(data.Length - 1) - 1.0 )))

        System.Math.Sqrt (firstValue - secondValue) * System.Math.Sqrt(252.0)     

//highLowCloseVolatility "MSFT" (new DateTime(2010,1,1)) (new DateTime(2010,1,30));;
let highLowCloseVolatility symbol (fromDate:DateTime) (toDate:DateTime) =
        let data = getMarketData symbol fromDate toDate
        let highLow (dt: MarketData list) =
                    dt
                    |> List.fold (fun acc x -> acc + (0.5) * System.Math.Pow(System.Math.Log(x.High / x.Low),2.0))  0.0
                    |> (*) ( 1.0 / System.Convert.ToDouble(data.Length - 1))

        let rec closeCalc (dt: MarketData list)  =
                    match dt with
                    | x::y::[] -> ((2.0 * System.Math.Log(2.0)) - 1.0) * System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)
                    | x::y::tail -> ((2.0 * System.Math.Log(2.0)) - 1.0) * System.Math.Pow(System.Math.Log((y.Close / x.Close)),2.0)  + (closeCalc (List.append [y] tail))
                    | [] -> 0.0

        let close (dt: MarketData list) =
                dt
                |> closeCalc
                |> (*) ( 1.0 / System.Convert.ToDouble(data.Length - 1))

        System.Math.Sqrt(252.0) * System.Math.Sqrt((highLow data.Tail) - (close data))

 

Open new window with its own UI thread.

The code below speaks for itself on how to open multiple windows which have there own dispatcher.
private void CreateNewWindow()
  {
   Thread thread = new Thread(() =>
    {
     Window1 w = new Window1();
     w.Show();

     w.Closed += (sender2, e2) =>
      w.Dispatcher.InvokeShutdown();

     System.Windows.Threading.Dispatcher.Run();
    });

   thread.SetApartmentState(ApartmentState.STA);
   thread.Start();
  }

Powershell – Copyright header generator script

Recently i have been doing pair programming with my colleague Andre and thanks to him, i learned powershell programming. Most of the code files in the project need some kind of copyright information at the top. One way to add these headers is by using code formatting tools like stylecop or resharper. But with my newly acquired skills i believe its better to write a small script to append the header on all code files using powershell.

Problem: (Add copyright information to all the files with a given extension found in the target and its subdirectories.)

  • Read all the files from target directory and its subdirectories with given extension.
  • Append header text at the beginning of the file with copyright information.

Solution:

param($target = "c:\\tmp", $companyname = "Lab49")
$header = "//-----------------------------------------------------------------------
// <copyright file=""{0}"" company=""{1}"">
//     Copyright (c) {1}. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------`r`n"
function Write-Header ($file) {
$content = Get-Content $file
$filename = Split-Path -Leaf $file
$fileheader = $header -f $filename,$companyname
Set-Content $file $fileheader
Add-Content $file $content
}
Get-ChildItem $target -Recurse | ? { $_.Extension -like ".txt" } | % {
Write-Header $_.PSPath.Split(":",3)[2]
}

WPF Dynamic Data Display.

Found this amazing library for dynamic data display developed by Computational Science Laboratory in Microsoft Research. It features efficient binding mechanisms and real-time interactivity capable of charting millions of data points. WPF developers in finance should have a look at this.

http://www.codeplex.com/dynamicdatadisplay

CSLA.Net framework for developing business objects.

I have been fan of CSLA.Net(component-based, scalable, logical architecture) framework since early days of my career had ported it from VB.Net to C# then. This framework comes handy for development of N-Tier architecture. Following are the feature highlights.
  1. Tracking Broken Business Rules
  2. Tracking Whether the Object Has Changed
  3. Strongly Typed Collections of Child Objects
  4. Simple and Abstract Model for the UI Developer
  5. Supporting Data Binding
  6. Object Persistence and Object-Relational Mapping .
  7. Business Object Creation
  8. N-Level Undo Functionality
  9. Data Binding Support
  10. Validation Rules
  11. Data Portal
  12. Custom Authentication
  13. Integrated Authorization

http://www.lhotka.net/

    Posted in .Net, C#. Tags: . 1 Comment »

    Finally WPF/Sliverlight style generator.

    I started this project last week and so far i was able to get Monochromatic, complimentary, Triad , Tetrads and analogous colors. The final goal of this project are as follows.

    1. User should be able to view dark and light style with chosen color on predefined template.
    2. User should be able to generate ResourceDictionary for Silverlight/WPF out of the chosen color. (This would relieve every developer from pain of styling the application :) trust me i know it)

    image

    Coming soon on codeplex…….  Download code.

    Note: Please contribute to the project for the wellbeing of all the developers :)

    Microsoft Security Essentials

    Microsoft Security Essentials provides real-time protection for your home PC that guards against viruses, spyware, and other malicious software. It is available for free, for Windows XP 32-bit, Windows Vista/7 32-bit, and Windows Vista/7 64-bit.

    http://www.microsoft.com/security_essentials/

    Project Tuva from microsoft research.

    http://research.microsoft.com/apps/tools/tuva/index.html

    Microsoft research project tuva home page explains it like this:

    “Project Tuva explores core scientific concepts and theories through presenting timeless videos with its new enchanced Video Player featuring searchable video, linked transcripts, notes, and interactive extras”

    It was amazing to see and hear Dr. Richard Feynman’s lecture on “Law of Gravitation” at Cornell University in 1964.

    Why functional programming?

    Functional programming is not a silver bullet, but learning it will indeed add to the knowledge of every software engineer about solving problem in different a way. One can always implement functional style of programming in any imperative language they use.

    Advantages:

    1. For analysis of mathematical problem that requires human analysts, it is possible to represent the problem in a concise mathematical form that analysts can understand.
    2. A declarative language simplifies the creation and multiple interpretations and static analysis.
    3. Compositional construction allows natural mapping of the problem domain and encourages code reuse.
    4. Functional programming language like haskell makes maintenance easy due to its high level of abstraction which also makes addition of new features a lot simpler then it would be in any imperative language.
    5. As most of the data types in functional languages are immutable concurrency and parallelism is integral art of the language. Most modern functional languages like Haskell and Erlang support multi-core without any extra libraries.
    6. Its easy to implement domain-specific language.

    Disadvantages:

    1. Its difficult to get developers on functional languages and thus it adds to project risk.
    2. UI development is not a proven ground in functional world.
    3. Performance is real unknown for most functional languages as its not widely accepted in developing of large real time systems. Haskell performance. (i personally believe that with multi-core systems any problem needs to be parallelized and immutability is the only answer to that type problems. So even imperative languages have to make data structures immutable to solve the problem on multi-core.)

    Here is the implementation of Black Scholes model for European options in Haskell and C#. I wrote this example to show the difference between functional and imperative language, see it your self.

    1. type Put = String
    2. type Call = String
    3. data Option = Call | Put
    4. deriving (Eq, Show)
    5. blackscholes :: Option -> Double -> Double -> Double -> Double -> Double -> Double
    6. blackscholes  option s x t r v
    7. | option == Call = s * normcdf d1 – x*exp (-r*t) * normcdf d2
    8. | option == Put = x * exp (-r*t) * normcdf (-d2) – s * normcdf (-d1)
    9. where
    10. d1 = ( log(s/x) + (r+v*v/2)*t )/(v*sqrt t)
    11. d2 = d1 – v*sqrt t
    12. normcdf x
    13. | x < 0 = 1 – w
    14. | otherwise = w
    15. where
    16. w = 1.0 – 1.0 / sqrt (2.0 * pi) * exp(-l*l / 2.0) * poly k
    17. k = 1.0 / (1.0 + 0.2316419 * l)
    18. l = abs x
    19. poly = horner coeff
    20. coeff = [0.0,0.31938153,-0.356563782,1.781477937,-1.821255978,1.330274429]
    21. horner coeff base = foldr1 multAdd  coeff
    22. where
    23. multAdd x y = y*base + x
    1. namespace BackScholes
    2. {
    3. class Program
    4. {
    5. static void Main(string[] args)
    6. {
    7. }
    8. }
    9. enum Option
    10. {
    11. Call,
    12. Put
    13. }
    14. /// <summary>
    15. /// Summary description for BlackSholes.
    16. /// </summary>
    17. public class BlackSholes
    18. {
    19. public double BlackScholes(Option option, double S, double X,
    20. double T, double r, double v)
    21. {
    22. double d1 = 0.0;
    23. double d2 = 0.0;
    24. double dBlackScholes = 0.0;
    25. d1 = (Math.Log(S / X) + (r + v * v / 2.0) * T) / (v * Math.Sqrt(T));
    26. d2 = d1 – v * Math.Sqrt(T);
    27. if (option == Option.Call)
    28. {
    29. dBlackScholes = S * CND(d1) – X * Math.Exp(-r * T) * CND(d2);
    30. }
    31. else if (option == Option.Put)
    32. {
    33. dBlackScholes = X * Math.Exp(-r * T) * CND(-d2) – S * CND(-d1);
    34. }
    35. return dBlackScholes;
    36. }
    37. public double CND(double X)
    38. {
    39. double L = 0.0;
    40. double K = 0.0;
    41. double dCND = 0.0;
    42. const double a1 = 0.31938153;
    43. const double a2 = -0.356563782;
    44. const double a3 = 1.781477937;
    45. const double a4 = -1.821255978;
    46. const double a5 = 1.330274429;
    47. L = Math.Abs(X);
    48. K = 1.0 / (1.0 + 0.2316419 * L);
    49. dCND = 1.0 – 1.0 / Math.Sqrt(2 * Convert.ToDouble(Math.PI.ToString())) *
    50. Math.Exp(-L * L / 2.0) * (a1 * K + a2 * K * K + a3 * Math.Pow(K, 3.0) +
    51. a4 * Math.Pow(K, 4.0) + a5 * Math.Pow(K, 5.0));
    52. if (X < 0)
    53. {
    54. return 1.0 – dCND;
    55. }
    56. else
    57. {
    58. return dCND;
    59. }
    60. }
    61. }
    62. }

    Dryad and DryadLinq release for academic community.

    Microsoft’s answer to google map reduce and hadoop for distributed computing is Dryad.

    http://research.microsoft.com/en-us/collaboration/tools/dryad.aspx

    Follow

    Get every new post delivered to your Inbox.