Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

F# for Quantitative Finance
F# for Quantitative Finance
F# for Quantitative Finance
Ebook582 pages3 hours

F# for Quantitative Finance

Rating: 0 out of 5 stars

()

Read preview

About this ebook

To develop your confidence in F#, this tutorial will first introduce you to simpler tasks such as curve fitting. You will then advance to more complex tasks such as implementing algorithms for trading semi-automation in a practical scenario-based format.If you are a data analyst or a practitioner in quantitative finance, economics, or mathematics and wish to learn how to use F# as a functional programming language, this book is for you. You should have a basic conceptual understanding of financial concepts and models. Elementary knowledge of the .NET framework would also be helpful.
LanguageEnglish
Release dateDec 26, 2013
ISBN9781782164630
F# for Quantitative Finance

Related to F# for Quantitative Finance

Related ebooks

Programming For You

View More

Related articles

Reviews for F# for Quantitative Finance

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    F# for Quantitative Finance - Johan Astborg

    Table of Contents

    F# for Quantitative Finance

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why Subscribe?

    Free Access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Introducing F# Using Visual Studio

    Introduction

    Getting started with Visual Studio

    Creating a new F# project

    Creating a new project in Visual Studio

    Understanding the program template

    Adding an F# script file

    Understanding F# Interactive

    Language overview

    Explaining mutability and immutability

    Primitive types

    Explaining type inference

    Explaining functions

    Learning about anonymous functions

    Explaining higher-order functions

    Currying

    Investigating lists

    Concatenating lists

    Tuples

    The pipe operator

    Documenting your code

    Your first application

    The whole program

    Understanding the program

    Extending the example program

    The entire program

    The power of prototyping

    Functional languages in quantitative finance

    Understanding the imperative code and interoperability

    Summary

    2. Learning More About F#

    Structuring your F# program

    Looking into modules

    Using functions and values in modules

    Namespaces

    Looking deeper inside data structures

    Record types

    Discriminated unions

    Enumerations

    Arrays

    Interesting functions in an array module

    Lists

    Pattern matching and lists

    Interesting functions in a list module

    Sequences

    Interesting functions in the sequence module

    Sets

    Maps

    Interesting functions in the map module

    Options

    Strings

    Interesting functions in the string module

    Choosing data structures

    Arrays

    Lists

    Sets

    Maps

    More on functional programming

    Recursive functions

    Tail recursion

    Pattern matching

    Incomplete pattern matching

    Using guards

    Pattern matching in assignment and input parameters

    Active patterns

    Introducing generics

    Lazy evaluation

    Units of measure

    Asynchronous and parallel programming

    Events

    Background workers

    Threads

    Thread pools

    Asynchronous programming

    The F# asynchronous workflows

    Asynchronous binding

    Examples of using an async workflow

    Parallel programming using TPL

    MailboxProcessor

    A brief look at imperative programming

    Object-oriented programming

    Classes

    Objects and members

    Methods and properties

    Overloaded operators

    Using XML documentation

    Useful XML tags

    Typical XML documentation

    Summary

    3. Financial Mathematics and Numerical Analysis

    Understanding the number representation

    Integers

    Two's complement

    Floating-point numbers

    The IEEE 754 floating-point standard

    Learning about numerical types in F#

    Arithmetic operators

    Learning about arithmetic comparisons

    Math operators

    Conversion functions

    Introducing statistics

    Aggregate statistics

    Calculating the sum of a sequence

    Calculating the average of a sequence

    Calculating the minimum of a sequence

    Calculating the maximum of a sequence

    Calculating the variance and standard deviation of a sequence

    Calculating variance

    Calculating standard deviation

    Looking at an example application

    Using the Math.NET library

    Installing the Math.NET library

    Introduction to random number generation

    Pseudo-random numbers

    Mersenne Twister

    Probability distributions

    Normal distribution

    Statistics

    Linear regression

    Using the least squares method

    Using polynomial regression

    Learning about root-finding algorithms

    The bisection method

    Looking at an example

    Finding roots using the Newton–Raphson method

    Looking at an example

    Finding roots using the secant method

    Looking at an example

    Summary

    4. Getting Started with Data Visualization

    Making your first GUI in F#

    Composing interfaces

    More about agents

    The user interface

    The main application

    Learning about event handling

    Displaying data

    Extending the form to use a table

    Displaying financial data from Yahoo! Finance

    Understanding the application code

    Extending the application to use Bollinger bands

    Using FSharp.Charting

    Creating a candlestick chart from stock prices

    Creating a bar chart

    Summary

    5. Learning Option Pricing

    Introduction to options

    Looking into contract specifications

    European options

    American options

    Exotic options

    Learning about Wiener processes

    Learning the Black-Scholes formula

    Implementing Black-Scholes in F#

    Using Black-Scholes together with charts

    Introducing the greeks

    First-order greeks

    Second-order greeks

    Implementing the greeks in F#

    Delta

    Gamma

    Vega

    Theta

    Rho

    Investigating the sensitivity of the greeks

    Code listing for visualizing the four greeks

    The Monte Carlo method

    Summary

    6. Exploring Volatility

    Introduction to volatility

    Actual volatility

    Implied volatility

    Exploring volatility in F#

    The complete application

    Learning about implied volatility

    Solving for implied volatility

    Delta hedging using Black-Scholes

    Exploring the volatility smile

    Summary

    7. Getting Started with Order Types and Market Data

    Introducing orders

    Order types

    Market orders

    Limit orders

    Conditional and stop-orders

    Order properties

    Understanding order execution

    Introducing market data

    Implementing simple pretrade risk analysis

    Validating orders

    Introducing FIX and QuickFIX/N

    Using FIX 4.2

    Configuring QuickFIX to use the simulator

    Summary

    8. Setting Up the Trading System Project

    Explaining automated trading

    Understanding software testing and test-driven development

    Understanding NUnit and FsUnit

    Requirements for the system

    Setting up the project

    Installing the NUnit and FsUnit frameworks

    Connecting to Microsoft SQL Server

    Introducing type providers

    Using LINQ and F#

    Explaining sample code using type providers and LINQ

    Creating the remaining table for our project

    Writing test cases

    Details about the setup

    Summary

    9. Trading Volatility for Profit

    Trading the volatility

    Plotting payoff diagrams with FSharpCharts

    Learning directional trading strategies

    Trading volatility using options

    Trading the straddle

    Long straddle

    Short straddle

    Trading the butterfly spread

    The long butterfly spread

    The short butterfly spread

    Trading the VIX

    Trading the delta neutral portfolio

    Deriving the mathematics

    Hedging with implied volatility

    Implementing the mathematics

    Learning relative value trading strategies

    Trading the slope of the smile

    Defining the trading strategy

    Case 1 – increasing the slope

    Case 2 – decreasing the slope

    Defining the entry rules

    Defining the exit rules

    Summary

    10. Putting the Pieces Together

    Understanding the requirements

    Revisiting the structure of the system

    Understanding the Model-View-Controller pattern

    The model

    The view

    The controller

    Executing the trading strategy using a framework

    Building the GUI

    Presenting information in the GUI

    Adding support for downloading the data

    Looking at possible additions to the system

    Improving the data feed

    Support for backtesting

    Extending the GUI

    Converting to the client-server architecture

    Summary

    Index

    F# for Quantitative Finance


    F# for Quantitative Finance

    Copyright © 2013 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: December 2013

    Production Reference: 1191213

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78216-462-3

    www.packtpub.com

    Cover Image by Aniket Sawant ( <[email protected]>)

    Credits

    Author

    Johan Astborg

    Reviewers

    Yan Cui

    Arthur Pham

    Isaac Abraham

    Acquisition Editors

    Sam Birch

    Aarthi Kumaraswamy

    Kunal Parikh

    Lead Technical Editor

    Athira Laji

    Copy Editors

    Roshni Banerjee

    Janbal Dharmaraj

    Mradula Hegde

    Gladson Monteiro

    Deepa Nambiar

    Karuna Narayanan

    Shambhavi Pai

    Alfida Paiva

    Adithi Shetty

    Shambhavi Pai

    Technical Editors

    Gauri Dasgupta

    Shiny Poojary

    Siddhi Rane

    Sonali S. Vernekar

    Project Coordinator

    Mary Alex

    Proofreader

    Paul Hindle

    Indexers

    Hemangini Bari

    Mariammal Chettiyar

    Tejal Soni

    Graphics

    Ronak Dhruv

    Production Coordinator

    Melwyn D'sa

    Cover Work

    Melwyn D'sa

    About the Author

    Johan Astborg is the developer and architect of various kinds of software systems and applications, financial software systems, trading systems, as well as mobile and web applications. He is interested in computer science, mathematics, and quantitative finance, with a special focus on functional programming. Johan is passionate about languages such as F#, Clojure, and Haskell, and operating systems such as Linux, Mac OS X, and Windows for his work. Most of Johan's quantitative background comes from Lund University, where he studied courses in computer science, mathematics, and physics. Currently Johan is studying pure mathematics at Lund University, Sweden, and is aiming for a PhD in the future, combining mathematics and functional programming. Professionally, Johan has worked as a part-time developer for Sony Ericsson and various smaller firms in Sweden. He also works as a part-time consultant focusing on web technologies and cloud solutions. You can easily contact him by sending an e-mail to <[email protected]> or visit his GitHub page at https://github.com/joastbg.

    About the Reviewers

    Yan Cui (@theburningmonk) is a lead server-side developer at the London-based, award winning gaming company GameSys. He focuses on building highly distributed and scalable server-side solutions for GameSys's social and mobile games. Yan is a regular speaker on topics such as F#, AOP, and NoSQL at local user groups and conferences in the UK and keeps an active blog at http://theburningmonk.com. He is also a co-author of the upcoming book, F# Deep Dives, Manning Publications.

    Arthur Pham is working for for Thomson Reuters as a Lead Quantitative Engineer since 2006. He has spent many years designing and implementing derivatives pricing models and still loves learning new programming languages like F#, C++, Python, Flex/Actionscript, C#, Ruby, and JavaScript.

    He currently lives in New York, USA, and can be contacted on Twitter @arthurpham.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.

    Why Subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via web browser

    Free Access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    F# is a functional programming language that allows you to write simple code for complex problems. Currently, it is most commonly used in the financial sector. Quantitative finance makes heavy use of mathematics to model the real world. If you are interested in using F# for your day-to-day work or research in quantitative finance, this book is for you.

    This book covers everything you need to know about using functional programming for quantitative finance. Using a functional programming language for quantitative finance will enable you to concentrate more on the model itself rather than the implementation details. Tutorials and snippets are summarized into a trading system throughout this book.

    F#, together with .NET, provides a wide range of tools needed to produce high quality and efficient code, from prototyping to production. The example code snippets in this book can be extended into larger blocks of code, and reused and tested easily in a functional language. F# is considered one of the default functional languages of choice for financial and trading-related applications.

    What this book covers

    Chapter 1, Introducing F# Using Visual Studio, introduces you to F# and its roots in functional languages. You will learn how to use F# in Visual Studio and write your first application.

    Chapter 2, Learning More About F#, teaches you more about F# as a language and illustrates the many sides of this paradigm language.

    Chapter 3, Financial Mathematics and Numerical Analysis, introduces the toolset we'll need throughout the book to implement financial models and algorithms.

    Chapter 4, Getting Started with Data Visualization, introduces some of the most common ways to use F# to visualize data and display information in a GUI.

    Chapter 5, Learning Option Pricing, teaches you about options, the Black-Scholes formula and ways of exploring options using the tools at hand.

    Chapter 6, Exploring Volatility, digs deeper into the world of Black-Scholes and teaches you about implied volatility.

    Chapter 7, Getting Started with Order Types and Market Data, takes a rather pragmatic approach towards finance and implements a basic order management system.

    Chapter 8, Setting Up the Trading System Project, builds the foundation for the project and shows how to connect to SQL Server and use LINQ for queries.

    Chapter 9, Trading Volatility for Profit, studies various ways of monetizing through movements in volatility and the arbitrage opportunity defining the trading strategy for the project.

    Chapter 10, Putting the Pieces Together, shows the final steps towards the complete trading system using a volatility arbitrage strategy and FIX 4.2.

    What you need for this book

    Apart from an interest in F# and finance, you need a computer with Visual Studio 2012 installed. Visual Studio 2012 is the recommended IDE, supporting F# 3.0.

    Who this book is for

    This book is for anyone interested in writing F# code in the financial domain, with a quantitative approach. The book is mainly intended to be a source of inspiration and uses a lot of working code examples to illustrate both the concepts of finance and F# as a functional language.

    At the end of the book we develop a simple trading system for volatility arbitrage. Details about orders and the FIX protocol are explained, as well as the theory behind the strategy itself. This may work as a foundation for anyone interested in developing their own trading system based on options and volatility.

    Conventions

    In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input are shown as follows: First we set a flag in the constructor, WorkerSupportsCancellation = true, then we check a flag every time we iterate the calculation.

    A block of code is set as follows:

    let rec getSecondLastElement = function

            | head :: tail :: [] -> head

            | head :: tail -> getSecondLastElement tail

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    SocketConnectPort=9878 SocketConnectHost=192.168.0.25

     

    FileStorePath=temp

    New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: If you run this code, you will see a form with the title Displaying data in F#, like the one in the following screenshot.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

    To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

    Piracy

    Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <[email protected]> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors, and our ability to bring you valuable content.

    Questions

    You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

    Chapter 1. Introducing F# Using Visual Studio

    In this chapter, you will learn about the history of F# and its roots in other programming languages. We will also be introducing Visual Studio and the fundamental language constructs of F#. You will be comfortable using the interactive mode for prototyping the code step-by-step. You will get a better understanding of how to build programs in F# by putting pieces together. Also, the basics of the language are covered by using and evaluating the code in the Read Eval Print Loop (REPL).

    In this chapter you will learn:

    How to use F# with Visual Studio 2012

    How to use F# Interactive to write the code in a new exploratory way

    The basics of F# and how to write your first non-toy application

    How functional programming will make you more productive

    Introduction

    Before we dive in to the language itself, we should discuss why we need it in the first place. F# is a powerful language, which may sound like a cliché, but it combines multiple paradigms into real-life productivity and supports the .NET components and libraries natively as well as the Common Language Infrastructure (CLI). Functional programming has long been associated with academics and experts. F# is one of the few languages offering a complete environment that is mature enough to comfortably be integrated into an organization.

    Also, F# has extensive support for parallel programming, where advanced features such as asynchronous and multi-threaded concepts are implemented as language constructs. It hides a lot of implementation details from the programmer. In F#, the functional programming

    Enjoying the preview?
    Page 1 of 1