F# for Quantitative Finance - Johan Astborg - E-Book

F# for Quantitative Finance E-Book

Johan Astborg

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

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 various parts of finance in the real world. If you are interested in using F# for your day-to-day work or research in quantitative finance, this book is a must-have.This book will cover everything you need to know about using functional programming for quantitative finance. Using a functional programming language will enable you to concentrate more on the problem itself rather than implementation details. Tutorials and snippets are summarized into an automated trading system throughout the book.This book will introduce you to F#, using Visual Studio, and provide examples with functional programming and finance combined. The book also covers topics such as downloading, visualizing and calculating statistics from data.

F# is a first class programming language for the financial domain.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 293

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



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 <[email protected]> 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 PacktCopy and paste, print, and bookmark contentOn 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.

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 erratasubmissionform 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 2012How to use F# Interactive to write the code in a new exploratory wayThe basics of F# and how to write your first non-toy applicationHow 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 paradigm is the main philosophy used to solve problems. The other paradigms, object-oriented and imperative programming, are prioritized to be used as subsidiaries and complements for this main paradigm. Reasons for them to coexist, involves compatibility and pragmatic, real-world productivity concerns.

Getting started with Visual Studio

We will start by introducing Visual Studio as the main tool of choice for this book. Although it's possible to use the standalone F# compiler and your favorite editor, you will most likely be more productive using Visual Studio 2012, as we will do throughout this book.

F# has been a part of Visual Studio since 2010. We will use the latest version of Visual Studio and F# throughout this book. This will enable us to use the latest functionality and enhancements available in Visual Studio 2012 and F# 3.0.

F# is open source, which means you can use it on any supported platform; it's not bound to Microsoft or Visual Studio. There is good support in other IDEs, such as MonoDevelop, which will run on Linux and Mac OS X.

Note

For more information about F# and the F# Software Foundation, visit http://fsharp.org.

Creating a new F# project

Create a new project in Visual Studio for F#, which is to be used in this guide to explore the basics, as shown in the following sections.

Creating a new project in Visual Studio

Using the following steps, we can create a new project in Visual Studio:

To create your first F# project, open Visual Studio 12 and navigate to File | New | Project, then, from the menu select New Project.Now you will see the New Project window appear. Select F# in the left panel and then select F# Application. You can name it anything you like. Finally, click on OK.Now you have created your first F# application, which will just print the arguments passed to it.

Understanding the program template

Let's have a brief look at the program template generated by Visual Studio.

If you run this program, which will just print out the arguments passed to it, you will see a terminal window appear.

The [<EntryPoint>] function in the preceding screenshot is the main function, which tells Visual Studio to use that particular function as the entry point for the program executable. We will not dig any deeper into this program template for now, but we will come back to this in the last three chapters when we'll build the trading system.

Adding an F# script file

We will use an F# script file after having looked at the standard program template instead of exploring the basics of the language in a more interactive fashion. You can think of F# script files as notebooks, where you have executable code that you can explore in pieces in an incremental style:

Add the F# script file by right-clicking on the Solution Explorer to the right of the code editor.Then navigate to Add | New Item…, as shown in the following screenshot:You can name the script file anything you like, such as GettingStarted.fsx.

Now that we have set up the basic project structure in Visual Studio, let's continue and explore F# Interactive.

Explaining type inference

Type inference means that the compiler will automatically deduce the type of an expression used in the code, based on the information provided from the programmer about the context of the expression. Type inference analyses the code, as you have seen in the preceding section, to determine types that are often obvious to the programmer. This spares the programmer from having to explicitly define the types of every single variable. It's not always needed to have the types defined to be able to understand the code, as seen in the preceding section for simple assignments of integers and floats. Type inference will make the code easier to write, and as a consequence, easier to read, leaving a lot of ceremony where it belongs.