Book Image

Clojure for Finance

By : Timothy Washington
Book Image

Clojure for Finance

By: Timothy Washington

Overview of this book

<p>Clojure is a dynamic programming language with an emphasis on functional programming. Clojure is well suited to financial modeling as it is a functional programming language. Such languages help developers work with high-level mathematical abstractions without having to implement low-level code that handles the arithmetic operations.</p> <p>Starting with the importance of representing data and calculations effectively, this book will take you all the way to being competent in financial analytics and building financial applications.</p> <p>First, we introduce the notions of computation and finance, which will help you understand Clojure's utility to solve real-world problems in many domains, especially finance. Next, we will show you how to develop the simple-moving-average function by using the more advanced partition Clojure data transformation function. This function, along with others, will be used to calculate and manipulate data.</p> <p>You will then learn to implement slightly more complicated equations, how to traverse data, and deal with branching and conditional dispatch. Then, the concept of side-effecting and its various approaches are introduced, along with the strategy of how to use data as the interface to other systems. Finally, you will discover how to build algorithms while manipulating and composing functions.</p>
Table of Contents (16 chapters)
Clojure for Finance
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Clojure is a dynamic programming language with an emphasis on functional programming. As a functional language with immutability and laziness as the default, Clojure is well suited to financial modeling. Such languages help developers work at high-levels of abstraction, thus implementing features much more quickly and with more confidence, than is otherwise possible in languages without these facilities.

In this book, we will demonstrate Clojure's utility in processing and analyzing financial data. Whether it's core banking, risk assessment, compliance, or other domains, this book's audience mostly comprises finance professionals who can use Clojure to improve their Excel spreadsheets or existing toolsets.

What this book covers

Chapter 1, Orientation – Addressing the Questions Clojure Answers, gives you the background required to understand Clojure's utility to solve real-world problems in many domains, and finance in particular. It also orients and helps you understand Clojure's approach to computation.

Chapter 2, First Principles and a Useful Way to Think, provides you with an understanding of what a stream of stock price data may look like. It then applies some core functional programming features that Clojure provides to transform data into the stock price shape we desire.

Chapter 3, Developing the Simple Moving Average, aims to teach you how to translate requirements to data input, deriving the target data output, and reasoning about an equation needed to achieve your output. It also helps you understand Vars and bindings and how to implement a Simple Moving Average (SMA). This chapter focuses on developing a solid understanding of a problem, easily representing data, and quickly performing calculations.

Chapter 4, Strategies for Calculating and Manipulating Data, implements two more functions, the Exponential Moving Average (EMA) and Bollinger Band. These are both technical trading indicators, which involve more advanced mathematics. This chapter explores the math in each equation and the algorithmic steps needed to arrive at a desired endpoint.

Chapter 5, Traversing Data, Branching, and Conditional Dispatch, provides you with an understanding of more advanced branching and conditional logic. This chapter fleshes out the overall approach of Clojure's functions around recursion, list comprehensions, conditional dispatch, and first-order functions. This should then enable you to traverse and manipulate your data until you get what you want.

Chapter 6, Surveying the Landscape, takes a step back and reviews all of Clojure's features together. We'll review Clojure's scalars, collection types, and composite data types. Then, we'll take a look at how to use Clojure's functions to access, update, and compose data structures, I/O operations, and ways to approach what are known as side effects. We will also touch on Clojure's options when dealing with concurrency and parallelism.

Chapter 7, Dealing with Side Effects, shows how a componentized architecture can encapsulate all the functionality that we've developed so far. We will also develop a persistence strategy to write out our core tick list and accompanying analytics in the EDN format.

Chapter 8, Strategies for Using Macros, helps you understand how to read in data using Clojure. Once data is in our system, we will look at a few ways of querying it, including simple filtering and adding more constraints in a logical OR and AND fashion. We will also derive a a little query language using macros.

Chapter 9, Building Algorithms – Strategies to Manipulate and Compose Functions, uses all the knowledge you've gained so far to design buy and sell signals. It teaches you how to structure your data for further analysis, refactor your lagging indicator functions (SMA, EMA, and Bollinger Bands) to work lazily, and compose them together to get new information.

What you need for this book

You just need Leiningen and one of the common OSes, including OSX, Linux, Windows, and that's it!

Other than this, you need the following hardware:

  • MacBook Pro (Retina, Mid 2012)

  • A 2.3 GHz Intel Core i7 processor

  • 8 GB 1600 MHz DDR3 RAM

You also need the following software:

  • OSX Yosemite (10.10.2)

  • Java version "1.8.0_45"

  • Leiningen 2.5.2

  • Clojure 1.7.0

Who this book is for

If you're a finance professional who is currently using VBA (Excel) to perform financial calculations and quantitative analysis, and would like to use Clojure to augment your existing toolset, then this book is for you.

Basic knowledge of financial concepts is essential. Basic programming knowledge would also be an added advantage.

Conventions

In this book, you will find a number of text styles 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, and Twitter handles are shown as follows: "You can test this out by running java -version in the shell or command prompt provided by your system."

A block of code is set as follows:

(defn generate-prices [lower-bound upper-bound]
      (filter (fn [x] (>= x lower-bound))
              (repeatedly (fn [] (rand upper-bound)))))

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

(defn generate-sine-sequence []

  (let [ein (randomize-vertical-dilation sine 0.5 2.7)
        zwei (randomize-horizontal-dilation ein 0.3 2.7)
        sine-partial (partial zwei 0)

        xinterc-sine-left (find-xintercept - sine-xintercept)
        xinterc-sine-right (find-xintercept + sine-xintercept)

        granularityS (rand-double-in-range 0.1 1)
        xsequenceS (iterate (partial + granularityS) xinterc-sine-left)]

    (map sine-partial xsequenceS)))

(defn generate-oscillating-sequence []
  (four analytics/generate-prices-without-population 5 15))

Any command-line input or output is written as follows:

> (alter-var-root #'system component/start)
> (clojure.pprint/pprint system)
{:tms
 {:channel
  #object[clojure.core.async.impl.channels.ManyToManyChannel 0x14d1e55 "clojure.core.async.impl.channels.ManyToManyChannel@14d1e55"]},
 :cns
 {:timeseries
  {:channel
   #object[clojure.core.async.impl.channels.ManyToManyChannel 0x14d1e55 "clojure.core.async.impl.channels.ManyToManyChannel@14d1e55"]},
  :channel
  #object[clojure.core.async.impl.channels.ManyToManyChannel 0x14d1e55 "clojure.core.async.impl.channels.ManyToManyChannel@14d1e55"]}}

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "To be precise, these values are called Vars."

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 disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in 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 at 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 from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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 could 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 to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted 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 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

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.