<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Paul Legato &#187; finance</title>
	<atom:link href="http://www.paullegato.com/blog/tag/finance/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.paullegato.com</link>
	<description></description>
	<lastBuildDate>Tue, 06 Dec 2011 00:52:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Swing-Clojure GUI for the Black-Scholes Option Modeler</title>
		<link>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/</link>
		<comments>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 07:55:56 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[finance]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=352</guid>
		<description><![CDATA[Now that we have implemented Black-Scholes in Clojure, let&#8217;s make a Swing GUI for it. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we have implemented <a href="http://www.paullegato.com/blog/black-scholes-clojure/" >Black-Scholes in Clojure</a>, let&#8217;s make <a target="_blank" href="http://github.com/pjlegato/clojure_options" >a Swing GUI for it</a>. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it looks like. <a href="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" ><img src="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" alt="Screenshot of the Swing GUI for the Black-Scholes option modeler, implemented in Clojure" title="Swing-GUI-Clojure-Black-Scholes" width="569" height="355" class="alignright size-full wp-image-354" /></a></p>
<p>The GUI is written entirely in Clojure with the Swing toolkit. Calculation state is stored in a series of atoms. Watches are used to update the output table automatically when an atom changes, <a target="_blank" href="http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html" >an idea from Kotka</a>. I used the excellent <a target="_blank" href="http://www.miglayout.com/" >MiG Layout</a> for general layout functionality, and generic Swing widgets (JTextFields and a JTable) for the input and output.<br />
<span id="more-352"></span></p>
<h2>Clojure code</h2>
<p>The Black-Scholes GUI is launched with the<code>main</code> function. The Swing GUI is actually created in the <code>initialize-gui</code> function, but since <a target="_blank" href="http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html" >Swing widgets are not threadsafe</a>, we must use the <code>do-swing*</code> helper function from Clojure Contrib to spin off the real GUI creation code into the Swing event thread.</p>
<pre class="brush: clojure; title: ; notranslate">
(defn initialize-gui
  []
  (let [frame (JFrame. &quot;Black-Scholes Option Modeler&quot;)]

    (doto frame
      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (-&gt; .getContentPane
          (.add (miglayout (JPanel.)

                           (input-panel
                            (fn [_]
                              (do-swing
                               (doto frame
                                 (.setVisible false)
                                 (.dispose)))))

                           (result-table)

                           )))

      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (.pack)
      (.setVisible true))
     ))

(defn main
  []
  (do-swing* :now initialize-gui))
</pre>
<p>This is pretty straightforward. We make a (locally scoped) JFrame to be the main container at line 3. Within the context of the <code>let</code>, we add a JPane using MiG Layout to its content area (starting at line 8). The JPanel itself contains two subwidgets, which are those returned from the <code>input-panel</code> and <code>result-table</code> functions.</p>
<p>Note that we are passing an anonymous function to <code>input-panel</code> at line 11. The input panel contains the &#8220;Quit&#8221; button, and that button needs to know what to do when it&#8217;s pressed. We want it to close the GUI; that is, it should destroy the outer JFrame. To do that, it needs a reference to it. However, as a local variable in <code>initialize-gui</code>, the JFrame is not in scope elsewhere; we have to pass it in. The given function closes over the JFrame reference (line 13) and transports it to <code>input-panel</code>, where that function will be called as an event listener when the &#8220;Quit&#8221; button is pressed.</p>
<p>We could also have simply passed the bare JFrame rather than a function, and moved the frame-closing code into <code>input-panel</code>, but that would imply that the input panel must always be in a JFrame, which will not necessarily the case. Passing in an external anonymous function to be activated by the &#8220;Quit&#8221; button allows the input panel to be used generically in any sort of container, with the container deciding what to do when &#8220;Quit&#8221; is pressed.</p>
<h3>The Input Panel</h3>
<pre class="brush: clojure; title: ; notranslate">

(defn- input-panel [quit-action]
    (let [
          ;; Fields
          spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                 (.setColumns 6)
                 (.setValue @*spot*))

          strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                   (.setColumns 6)
                   (.setValue @*strike*))

          days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance))
                             (.setColumns 6)
                             (.setValue @*days-till-expiry*))

          riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                     (.setColumns 6)
                     (.setValue @*riskfree*))

          volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                       (.setColumns 6)
                       (.setValue @*volatility*))

          ;; Buttons
          calculate (JButton. &quot;Calculate&quot;)
          quit (JButton. &quot;Quit&quot;)
          ]

      (add-action-listener
       calculate
       (fn [_]
         (update-all-calculations
          (Double/parseDouble (.getText spot))
          (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*)
          (Double/parseDouble (.getText strike))
          (Double/parseDouble (.getText riskfree))
          (Double/parseDouble (.getText volatility)))))

      (add-action-listener
       quit
       quit-action)

      (miglayout (JPanel.)
                 :layout  [:wrap 2 ]

                 (JLabel. &quot;Spot&quot;) [:align &quot;right&quot;]
                 spot

                 (JLabel. &quot;Strike&quot;) [:align &quot;right&quot;]
                 strike

                 (JLabel. &quot;Risk-free rate&quot;) [:align &quot;right&quot;]
                 riskfree

                 (JLabel. &quot;Volatility&quot;) [:align &quot;right&quot;]
                 volatility

                 (JLabel. &quot;Days till expiry&quot;) [:align &quot;right&quot;]
                 days-till-expiry

                 calculate
                 quit)))
</pre>
<p>The input widgets are local variables in the input panel function, along with the two buttons. The widgets are initialized from the state atoms (which are then unused again; see discussion below.) The &#8220;Quit&#8221; button is given the event callback passed in as an argument (so it can manipulate the enclosing JFrame as per above.) The &#8220;Calculate&#8221; button is given an event callback that calls the <code>update-all-calculations</code> function with the values in the input widgets.</p>
<p>The lot are then stuffed into a JPanel with a MiG Layout and returned.</p>
<h3>The Output Table</h3>
<pre class="brush: clojure; title: ; notranslate">
(defn- update-cell
  &quot;Updates the given AbstractTableModel cell and fires a change event for that cell.&quot;
  [model data row col]
  (.setValueAt model data row col)
  (.fireTableCellUpdated model row col))

(defn- result-table []
  (let [
        column-names [&quot;&quot; &quot;Call&quot; &quot;Put&quot;]
        row-names [&quot;Price&quot; &quot;Delta&quot; &quot;Theta&quot; &quot;Rho&quot; &quot;Gamma&quot; &quot;Vega&quot;]
        table-model (proxy [AbstractTableModel] []
                      (getColumnCount [] (count column-names))
                      (getRowCount [] (count row-names))
                      (isCellEditable [] false)
                      (getColumnName [col] (nth column-names col))
                      (getValueAt [row col]
                                  (condp = col
                                      0 (nth row-names row) ;; Return the row name for column zero
                                      (condp = [row col]
                                          [0 1] @*call-price*
                                          [0 2] @*put-price*

                                          [1 1] @*call-delta*
                                          [1 2] @*put-delta*

                                          [2 1] @*call-theta*
                                          [2 2] @*put-theta*

                                          [3 1] @*call-rho*
                                          [3 2] @*put-rho*

                                          [4 1] @*gamma*
                                          [4 2] &quot;==&quot;

                                          [5 1] @*vega*
                                          [5 2] &quot;==&quot;

                                          nil))))

        table (doto (JTable. table-model)
                (.setGridColor java.awt.Color/DARK_GRAY))
        ]

    (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1)))
    (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2)))

    (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1)))
    (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2)))

    (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1)))
    (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2)))

    (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1)))
    (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2)))

    (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1)))
    (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1)))

    ;; This shrinks the table's preferred viewport down to its actual size.
    ;; (The default is to make a huge viewport, even though the table is small.)
    (.setPreferredScrollableViewportSize table (.getPreferredSize table))

    (JScrollPane. table)
    ))
</pre>
<p>The output table itself is a standard JTable. Its model is initialized from the output state atoms. The watches at lines 44-57 are the most interesting part; they allow arbitrary code to be called when the output state atoms change. This allows the Black-Scholes calculation to happen independently of the output widget. When one of those atoms is changed, it self-updates automatically via the watches.</p>
<p>The helper function at lines 1-5 updates the appropriate model cell and fires an event to tell the JTable to repaint it.</p>
<p>The scrollable viewport business at line 61 is to work around a questionable Java design decision where a JTable, by default, tells its container to make its viewport enormous, even though it have very little data. (That&#8217;s not an error, that&#8217;s subjunctive.)</p>
<h2>Design considerations</h2>
<h3>GUI and business logic decoupling</h3>
<p>Above all, the GUI has to be decoupled from the model itself. Internal changes to one should never affect the other, and the two should be independently testable. In such a simple application, this was easy enough. A more complex app that requires several information round trips would be trickier. We now have a good foundation for such an app. No business calculations are performed in the GUI code namespace. The sole point of connection is in the update-all-calculations function:</p>
<pre class="brush: clojure; title: ; notranslate">

(defn- update-all-calculations [spot timeleft strike riskfree sigma]
  (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma)))
  (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma)))

  (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma)))
  (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma)))

  (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma)))
  (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma)))

  (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma)))
  (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma)))

  (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma)))
  (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma))))
</pre>
<h3>Atoms to hold state</h3>
<p>As we can see above, set of atoms holds state for the GUI, in keeping with the general Clojure principle of isolating state into transactional memory. (Actually, I cheated a bit. Our full state consists of the input values and the results of our Black-Scholes calculations. Although I created atoms for the input state values as well, I calculate the results directly from the widgets. It is a trivial exercise to alter the &#8220;Calculate&#8221; button callback to use the atoms. This would be more useful in the case where changes to a widget fire an event that triggers recalculation, which is not done in this demo as per below. I would use the atoms in a real application.)</p>
<p>I/O is inherently stateful, as are GUIs. There was therefore the temptation to use the Swing widget objects themselves as state-holders, and in fact it requires extra code to shuttle data back and forth between the widgets and the atoms. In such a simple app as this, using the GUI widgets as state-holders does not make much practical difference, but in a more complex app, a well designed set of state atoms and watches can automate much of the tedious GUI logic.</p>
<p>Using the widgets directly as state holders implies a tight coupling between the input widgets, the business logic, and the output widgets. Changing any one of them would invariably have required changes to the linking logic.</p>
<p>For example, suppose we were using widgets-as-state, and we changed the &#8220;days left till expiry&#8221; input to a slider rather than a text box, or suppose we wanted to read it from a file or from an API. We would have to update the code that reads it, calculates the model, and puts the results into the output table. Touching that code implies a non-zero likelihood of breaking it. Why even introduce the potential for breaking something that is unrelated to the task at hand, in this case the business logic and output code?</p>
<p>Again, this seems trivial with such a very small application that is only a few lines long, but the design principle is what&#8217;s important. Imagine applying it to a much larger application with hundreds of inputs spread across 4 windows, 3 databases, and 6 web feeds to see why this is a good idea.</p>
<h3>Auto-updating results when input changes</h3>
<p>I wanted the results to auto-update anytime an input is changed, without resorting to a &#8220;Calculate&#8221; button. Having the button trigger the calculation and output update allows the state of the input and the output to become decoupled, which can be confusing for the user. Worse, it could be unnoticed by a user who is doing other things at the same time.</p>
<p>Due to typical Java overengineering, there is no straightforward way to simply <code>(add-action-listener)</code> on the JTextField and get notifications when it changes. Instead, <a target="_blank" href="http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/generaltext.html#document" >each Swing widget implements full-blown model-view separation</a>, and so you have to get the document underlying the JTextField. Yes, the view components of your MVC application themselves contain both models and views. Each and every field contains an entire implementation of the document object and associated cruft, all for itself. If you want to monitor changes in the widget, you need to build out a <code>DocumentListener</code> to watch for such events.</p>
<p>In a real application, I&#8217;d bite the bullet and implement it, but it&#8217;s not worth the extra time for the purposes of this demo, so we are left with a &#8220;Calculate&#8221; button and manual updating.</p>
<h2>Clojure-Options on Github</h2>
<p>The entire package so far is now <a target="_blank" href="http://github.com/pjlegato/clojure_options" >available on my GitHub page</a>. Patches are welcome. Atomizing the input widgets and adding the appropriate event callbacks and watches to eliminate the &#8220;Calculate&#8221; button is particularly welcome. <img src='http://www.paullegato.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=352&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Black-Scholes in Clojure</title>
		<link>http://www.paullegato.com/blog/black-scholes-clojure/</link>
		<comments>http://www.paullegato.com/blog/black-scholes-clojure/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 00:51:27 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[finance]]></category>
		<category><![CDATA[quant]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=345</guid>
		<description><![CDATA[The Black-Scholes option pricing model, implemented in Clojure based on the description at Wikipedia and these code samples. This code uses the new Incanter Distributions module, which hasn&#8217;t been released yet, so it requires the latest master version from Github. Most of the values agree with those produced at BloBek&#8217;s calculator, with the exception of [...]]]></description>
			<content:encoded><![CDATA[<p>The Black-Scholes option pricing model, implemented in Clojure based on <a target="_blank" href="https://secure.wikimedia.org/wikipedia/en/wiki/Black–Scholes" >the description at Wikipedia</a> and <a target="_blank" href="http://www.espenhaug.com/black_scholes.html" >these code samples</a>.<br />
<span id="more-345"></span></p>
<pre class="brush: clojure; title: ; notranslate">
;;
;; Black-Scholes option pricing model
;;
;; Copyright (C) 2010 Paul Legato. All rights reserved.
;; Licensed under the New BSD License. See the README file for details.
;;
;; Disclaimer: This code comes with NO WARRANTY, express or implied.
;; There may be any number of bugs. Use at your own risk.
;;
;; References:
;; - https://secure.wikimedia.org/wikipedia/en/wiki/Black%E2%80%93Scholes
;; - http://www.espenhaug.com/black_scholes.html

(ns clojure-options.black-scholes
  (:require incanter.distributions))

(defn d1
  [spot timeleft strike riskfree sigma]
  (/
   (+ (Math/log (/ spot strike))
      (* (+ riskfree (/ (* sigma sigma) 2))
         timeleft))
   (* sigma (Math/sqrt timeleft))))

(defn d2
  [spot timeleft strike riskfree sigma]
  (- (d1 spot timeleft strike riskfree sigma) (* sigma (Math/sqrt timeleft))))

(defn- n [val] (incanter.distributions/cdf (incanter.distributions/normal-distribution) val))

(defn call
  &quot;Returns the theoretic value of a European call option on the given underlying based on the Black-Scholes model.

 * spot - spot price of the underlying
 * timeleft - time to expiration, in years
 * strike - option strike price
 * riskfree - annual continuous risk-free interest rate
 * sigma - volatility of the underlying

&quot;
  [spot timeleft strike riskfree sigma]
  (- (* spot (n (d1 spot timeleft strike riskfree sigma)))
     (* strike
        (Math/exp (* (- riskfree) timeleft))
        (n (d2 spot timeleft strike riskfree sigma)))))

(defn put
  &quot;Returns the theoretic value of a European put option on the given underlying based on the Black-Scholes model.

 * spot - spot price of the underlying
 * timeleft - time to expiration, in years
 * strike - option strike price
 * riskfree - annual continuous risk-free interest rate
 * sigma - volatility of the underlying

&quot;
  [spot timeleft strike riskfree sigma]
  (- (* strike
        (Math/exp (* (- riskfree) timeleft))
        (n (- (d2 spot timeleft strike riskfree sigma))))
     (* spot (n (- (d1 spot timeleft strike riskfree sigma))))))

(defn call-delta
  [spot timeleft strike riskfree sigma]
  (n (d1 spot timeleft strike riskfree sigma)))

(defn put-delta
  [spot timeleft strike riskfree sigma]
  (- (n (d1 spot timeleft strike riskfree sigma)) 1))

(defn- nprime [val] (incanter.distributions/pdf (incanter.distributions/normal-distribution) val))

(defn gamma
  [spot timeleft strike riskfree sigma]
  (/ (nprime (d1 spot timeleft strike riskfree sigma))
     (* spot sigma (Math/sqrt timeleft))))

(defn vega
  [spot timeleft strike riskfree sigma]
  (* spot (nprime (d1 spot timeleft strike riskfree sigma)) (Math/sqrt timeleft)))

(defn call-theta
  [spot timeleft strike riskfree sigma]
  (-
   (- (/ (* spot (nprime (d1 spot timeleft strike riskfree sigma)) sigma)
         (* 2 (Math/sqrt timeleft))))
   (* riskfree strike (Math/exp (* (- riskfree) timeleft)) (n (d2 spot timeleft strike riskfree sigma)))))

(defn put-theta
  [spot timeleft strike riskfree sigma]
  (-
   (- (/ (* spot (nprime (d1 spot timeleft strike riskfree sigma)) sigma)
         (* 2 (Math/sqrt timeleft))))
   (* riskfree strike (Math/exp (* (- riskfree) timeleft)) (n (- (d2 spot timeleft strike riskfree sigma))))))

(defn call-rho
  [spot timeleft strike riskfree sigma]
  (* strike timeleft (Math/exp (* (- riskfree) timeleft)) (n (d2 spot timeleft strike riskfree sigma))))

(defn put-rho
  [spot timeleft strike riskfree sigma]
  (* (- strike) timeleft (Math/exp (* (- riskfree) timeleft)) (n (- (d2 spot timeleft strike riskfree sigma)))))
</pre>
<p>This code uses the new <a target="_blank" href="http://liebke.github.com/incanter/distributions-api.html" >Incanter Distributions module</a>, which hasn&#8217;t been released yet, so it requires the latest master version from Github.</p>
<p>Most of the values agree with those produced at <a target="_blank" href="http://www.blobek.com/black-scholes.html"  class="broken_link">BloBek&#8217;s calculator</a>, with the exception of theta. I imagine this has to do with the units used for the &#8220;days left to expiration&#8221; field; my calculator uses fractions of a year, while BloBek doesn&#8217;t specify whether his days are to be trading days or calendar days. It could also be a bug in one of our implementations.</p>
<p>In Part 2, I&#8217;ll build a simple Swing GUI for the calculator.<br />
<b>Update:</b> <a href="http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/" >Part 2, with the Swing GUI</a>, is now available. You can also get <a target="_blank" href="http://github.com/pjlegato/clojure_options" >the entire project&#8217;s source code</a> from GitHub.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=345&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/black-scholes-clojure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

