Now that we have implemented Black-Scholes in Clojure, let’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’s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here’s what it looks like.
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, an idea from Kotka. I used the excellent MiG Layout for general layout functionality, and generic Swing widgets (JTextFields and a JTable) for the input and output.
The Black-Scholes GUI is launched with the
main function. The Swing GUI is actually created in the
initialize-gui function, but since Swing widgets are not threadsafe, we must use the
do-swing* helper function from Clojure Contrib to spin off the real GUI creation code into the Swing event thread.
(defn initialize-gui  (let [frame (JFrame. "Black-Scholes Option Modeler")] (doto frame (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) (-> .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))
This is pretty straightforward. We make a (locally scoped) JFrame to be the main container at line 3. Within the context of the
let, 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
Note that we are passing an anonymous function to
input-panel at line 11. The input panel contains the “Quit” button, and that button needs to know what to do when it’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
initialize-gui, 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
input-panel, where that function will be called as an event listener when the “Quit” button is pressed.
We could also have simply passed the bare JFrame rather than a function, and moved the frame-closing code into
input-panel, 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 “Quit” button allows the input panel to be used generically in any sort of container, with the container deciding what to do when “Quit” is pressed.
The Input Panel
(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. "Calculate") quit (JButton. "Quit") ] (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. "Spot") [:align "right"] spot (JLabel. "Strike") [:align "right"] strike (JLabel. "Risk-free rate") [:align "right"] riskfree (JLabel. "Volatility") [:align "right"] volatility (JLabel. "Days till expiry") [:align "right"] days-till-expiry calculate quit)))
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 “Quit” button is given the event callback passed in as an argument (so it can manipulate the enclosing JFrame as per above.) The “Calculate” button is given an event callback that calls the
update-all-calculations function with the values in the input widgets.
The lot are then stuffed into a JPanel with a MiG Layout and returned.
The Output Table
(defn- update-cell "Updates the given AbstractTableModel cell and fires a change event for that cell." [model data row col] (.setValueAt model data row col) (.fireTableCellUpdated model row col)) (defn- result-table  (let [ column-names ["" "Call" "Put"] row-names ["Price" "Delta" "Theta" "Rho" "Gamma" "Vega"] 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] "==" [5 1] @*vega* [5 2] "==" 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) ))
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.
The helper function at lines 1-5 updates the appropriate model cell and fires an event to tell the JTable to repaint it.
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’s not an error, that’s subjunctive.)
GUI and business logic decoupling
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:
(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))))
Atoms to hold state
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 “Calculate” 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.)
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.
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.
For example, suppose we were using widgets-as-state, and we changed the “days left till expiry” 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?
Again, this seems trivial with such a very small application that is only a few lines long, but the design principle is what’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.
Auto-updating results when input changes
I wanted the results to auto-update anytime an input is changed, without resorting to a “Calculate” 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.
Due to typical Java overengineering, there is no straightforward way to simply
(add-action-listener) on the JTextField and get notifications when it changes. Instead, each Swing widget implements full-blown model-view separation, 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
DocumentListener to watch for such events.
In a real application, I’d bite the bullet and implement it, but it’s not worth the extra time for the purposes of this demo, so we are left with a “Calculate” button and manual updating.
Clojure-Options on Github
The entire package so far is now available on my GitHub page. Patches are welcome. Atomizing the input widgets and adding the appropriate event callbacks and watches to eliminate the “Calculate” button is particularly welcome. :)