Tuesday, October 22, 2013

Share Price Volatility and Swing Trading

Typing "volatility" into Google yields some pretty interesting and, in my opinion, pretty confused results.  The top result from my search was this one from Wikipedia and it says it all.  There seem to be many non-scientists regarding volatility as a financial market rainbow, with a crock of gold at the end of it.

Anyone with the most basic grounding in geometrical optics knows that a rain "bow" is really a segment of a rain "ring" and the centre of that ring, and your head, and the sun, all form a straight line, and the angle between that line and the line from your head to the colored rings is a function of the size of the rain droplets. So the rainbow moves with you.  You can never reach out and touch the rings, and you can certainly never navigate to the "base", conceptual or otherwise.

I suspect volatility is similar. From much of what is written there seem to be a fair few searching for crocks of gold, without a clear grasp of the mechanics.

The closest I found to a coherent definition of volatility is standard deviation.  This is is a widely used statistical measure which is easy enough to calculate. And while it may have applications in calculating the prices of certain esoteric financial instruments, I am not sure of its direct application to the construction of a trading strategy, or to the selection of shares suitable for short term swing trading.  To illustrate, I'll use my favorite mathematical construct, the sine wave.

The chart below shows a hypothetical price time graph for a hypothetical company, ABC Co. The mean share price is $1.50, and the standard deviation is 71c.
The chart below shows a hypothetical price time graph for a second hypothetical company, XYZ Co. The mean price is also $1.50, and the standard deviation is also 71c.
So the standard deviation is identical for both companies, and yet from a common sense perspective most people would describe the share price of XYZ Co as being much more volatile than that of ABC Co.  So on that basis, standard deviation, does not seem to represent a good estimate of volatility.

And from a swing trading perspective the two companies are very different.  ABC Co offers a swing trader one buy-sell cycle and a chance to buy back at the end of the period.  XYC Co offers a swing trader three buy-sell cycles over the same period, as well as a buy back opportunity at the end.

Without pretending to be a professional mathematician, my gut feeling is that there will be no simple mathematical formula to identify a share price pattern conducive to profitable trading. Rather a more long hand approach will be needed, setting trading parameters, and then tracking a share price over time to generate hypothetical trading results.

Wednesday, March 21, 2012

Windows 8 - my first impression

I was so excited about the first beta release of Vista that I built a computer specially to host it, and I liked enough to run it as my main OS for six months, although not quite enough to buy it. I installed Windows 7 on a spare HD sector of my main computer, but rarely used it. But I was so put off by the Microsoft propaganda with the release of Windows 8 "Customer preview" that I have installed it on a $200 used laptop from eBay.

And my first impression is that it will remain there. In fact, as I looked the array of icons on the opening screen, I felt I had been time warped back to the early 1990's, and was looking at Windows 3 not Windows 8. I knew clothing fashions went round in circles, but I didn't realize the designers of computer operating systems were that fickle.

Of course people will buy it, because it is built into the purchase of computers from shops. Will the corporate sector be bullied into adopting it? I guess if XP is no longer supported, they will have little choice.

In my first post on Windows 7, I said I had never quite got a Linux distro to work properly. Since then I have Linux Mint working so well on another second hand laptop that my children are allowed to use nothing else. They can browse the web, play games, and watch recorded TV and movies. So if XP becomes unusable in the future, for want of drivers or whatever, my plan will be to use Linux as a main OS, and to retain a box with XP for Excel spreadsheets and Access databases. I couldn't manage without Excel, and for all its faults as a production database, I still like using Access as a scratch pad and phone book.

As for Windows 8, I shall have to dedicate a few painful hours to navigating around it, because I know that in 12 months time, my customers will come pouring through the door wanting me to fix its gremlins. But I'm not looking forward to it. Maybe I shall have found something else to do before then. I shall pray for that.

Wednesday, December 7, 2011

HTML <div> tag revisited

I was abruptly forced to revisit this topic when I discovered that my <div> tag laid out login page, which seemed to look so great in Windows Internet Explorer (see below), looked absolutely crap in Firefox (see further below).

So I did some reading, and the theme seemed to be that tables were never intended to do layout. Well I reckon there should be a counter argument, that the <div> tag was never intended to present data.

It seems to me that much of the orthodoxy around HTML is written by graphic artists or publishers, and most of the web sites purported to show the power of <div> tags and CSS, are littered with graphic art and fancy fonts.

For anyone used to programming, meshing <div> tags and CSS is not technically difficult, but perhaps it is not second nature to graphic artists and literary publishers. The instructions emphasize the importance of closing tags, and they suggest using borders during the design phase to get a visual aid on the layout of the divisions.

So I tried that. I show below the HTML for the beginning of a login page:

<div id="container">
<div id="pageHeader">
<h3><span>A <a class="top" href="http://www.interactived.com/softway.htm">
Softway</a> Open Source Project <br>
Hosted by <a class="top" href="http://java.net/projects">Java.net</a></span></h3>
</div><!-- end of "pageHeader" -->
<div id="pageBody">
<h3><span><h3>Initial Login Screen</h3></span></h3>
<div id="cellA1">
<p><span>Please select user or administrator</span></p>
</div><!-- end of "cellA1" -->
<div id="cellB1">
<p><span><select name="usertype" class=cbox>
<option value="user">Student User</option>
<option value="admin">Administrator</option>
</div><!-- end of "cellB1" -->
</div><!-- end of "pageBody" -->
</div><!-- end of "container" -->

And below is the CSS to go with it:

#container {
padding: 0 25px 0 120px;
margin: 0;
position: relative;
border: 1px dotted red;
#pageHeader {
margin: 5px;
border: 1px dotted orange;
#pageBody {
margin: 5px;
border: 1px dotted green;
#cellA1 {
margin: 2px;
height: 35px;
float: left;
border: 1px dotted fuchsia;
#cellB1 {
margin: 2px;
height: 35px;
float: left;
border: 1px dotted fuchsia;

I put little margins around each "division", and I made the borders different colors for clarity. Having rainbows on my mind, I followed a rainbow sequence: Richard of .. gave .. vain. I show below how it came out:

Notice how the red border, which is supposed to embrace everything, stops short, and leaves off two divisions. And the green border, which was created to embrace the "table" and its heading, wraps itself around the heading only.

After many hours of fiddling, I noticed that the "divisions" behave better if they contain background images, but it strikes me that padding out divisions with background images to make them behave predictably, is conceptually not far removed from padding out real tables with spacer gifs.

So I shall put my login form, and all other forms back into tables. I may use CSS to format the tables, and I may use divisions in pages and areas of pages devoted to text and graphics. But my data and forms will be laid out in the traditional manner, using tables.

Monday, November 21, 2011

Bringing a Custom Swing Component to Life

I am sometimes down on the Java documentation, but in the sand plains of lugubrious and often confusing material there is the occasional gem. One example is a lesson from The Java Tutorial entitled Performing Custom Painting. I was directed to it by a reply to this thread in the Oracle Java Desktop forum.

When I first began my efforts to create a rainbow colored Gaussian distribution curve I began with one of the Tutorial lessons on colors. I have unfortunately lost the URL for the lesson but the code began something like this:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Colors extends JPanel {

public void paintComponent(Graphics g) {

Graphics2D g2d = (Graphics2D) g;

g2d.setColor(new Color(255, 0, 0));//vivid red
g2d.fillRect(10, 15, 90, 60);



public static void main(String[] args) {

JFrame frame = new JFrame("Colors");
frame.add(new Colors());
frame.setSize(360, 300);

It looked as shown below.

I modified this by putting the rectangles side by side and end on to produce a crude histogram as shown below:

I reduced the width of the rectangles (to one pixel) and their number (to 800), and made their height and color the subject of mathematical functions. The colors were produced by three out of phase sine waves. That idea from that came from this article by Jim Bumgardner. His explanation is very thorough, so I shall not repeat it here, but in recognition of the idea, my first rainbow colored curve was a sine wave, as shown below:

The mathematical function for a sine wave in Java is really simple:

y = Math.sin(x);

There is, alas, no inbuilt function for a Normal/Gaussian distribution curve, but Wikipedia gives the function as:

I used the middle part of this expression to produce the rainbow colored Gaussian distribution curve shown at the bottom of my previous post. But as I said there, it did nothing. I could not send messages to it or make it change.

I will admit that when I first read the reply to my forum post recommending the Custom Painting tutorial, I was not that optimistic, and I didn't look at it properly until after I had tried all the articles described in my previous blog post. But my cynicism was misplaced, and I should have started there.

The essential code construction from the tutorial begins as follows:

import javax.swing.SwingUtilities;
import javax.swing.JFrame;

public class SwingPaintDemo1 {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {

private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
JFrame f = new JFrame("Swing Paint Demo");

And the first essential point to note is that it uses:

The SwingUtilities helper class to construct this GUI on the Event Dispatch Thread.

I don't fully understand this, but I've been told to do it before, and it was only when I used this structure for my "custom swing component" that I could get it to work properly.

The second slightly strange thing that the tutorial did was to create its own "custom" JPanel:

class MyPanel extends JPanel {

public MyPanel() {

public Dimension getPreferredSize() {
return new Dimension(250,200);

public void paintComponent(Graphics g) {

// Draw Text
g.drawString("This is my custom Panel!",10,20);

This was all in the same source file, which was modified by replacing:



f.add(new MyPanel());

It looks trivial, but by following this structure, I was able to use the .pack() command in my applet. Using my original code construction (as shown above), the first time I inserted the new component, I thought it hadn't worked at all because it did not show, and it was only after adding padding to the gridbaglayout and manually resizing the applet that I could see it.

Another point worth noting is the line which inherits functionality from the parent component. This is described in the tutorial as follows:

Most of the standard Swing components have their look and feel implemented by separate "UI Delegate" objects. The invocation of super.paintComponent(g) passes the graphics context off to the component's UI delegate, which paints the panel's background.

This avoided me having to mimic the code structure of the standard swing components. I could focus on the code that made my component different.

The third thing that the tutorial did was to create a "sprite" and code to move it around. My "sprite" is my rainbow colored histogram, and I didn't need "event" code to drag it around the page. But I did need code to alter one or more of the parameters used to build the histogram. The code used by the tutorial was:

... previous imports
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;

... previous unchanged code

public MyPanel() {


addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {

addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {


private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {

public Dimension getPreferredSize() {
return new Dimension(250,200);

protected void paintComponent(Graphics g) {
g.drawString("This is my custom Panel!",10,20);

The fourth slightly strange thing that the tutorial did was to put the "sprite" is its own class:

class RedSquare{

private int xPos = 50;
private int yPos = 50;
private int width = 20;
private int height = 20;

public void setX(int xPos){
this.xPos = xPos;

public int getX(){
return xPos;

... more set/get functions

public void paintSquare(Graphics g){

I'm not sure whether this was strictly necessary, but I followed the same structure, putting my histogram into the paintSquare(Graphics g) method, although I called it rainbowHist(Graphics g). I also renamed MyPanel() to MyHist(). The six set/get functions I replaced with two:

public void setMaxValue(int MaxValue){
this.MaxValue = MaxValue;

public void setActValue(int ActValue){
this.ActValue = ActValue;

The moveSquare(int x, int y) function I made as follows:

public void moveSquare(int MaxValue, int ActValue){

I didn't need the mouse listeners, so I removed them altogether.

Already my custom component was beginning to look a bit like a JProgressBar, with a MaxValue and an ActValue, and "progress" indicated by the relationship between the two. In my initial version I made the number of columns in the histogram a linear function of ActValue as a proportion of MaxValue, just like the colored bit in an ordinary JProgressBar.

But I needed to revise this, because I wanted "progress" to be indicated by the area under the curve, not the distance along the x axis.

Wikipedia gives the area under the curve, or "Cumulative distribution function" as:

In this expression "erf" is an abbreviation for "error function", and I was interested to read that much of the work around and even the name of the function derives from measurement theory. Indeed, one of the approximation expressions is:

And this could almost have been lifted straight from the Rasch book. I must say, I've never liked that expression (in fact it gives me the heebie jeebies), so I moved straight down to the Abramowitz and Stegun approximations, and used the first, because I'm aiming for a visual impression here, and don't need seven decimal places of accuracy:

Because we are talking about probability here, the theoretical total area under the graph is 1. So while in the initial version, the critical parameter was number of columns:

for (double i=0; i<ActNoofColumns; i++){

I now set the histogram to build completely by default:

for (double i=0; i<MaxNoofColumns; i++){

and inserted a break to trigger when the area approximation equates to ActValue as a proportion of MaxValue:

if (jonathan > ProportionofMax) break;

I used the variable jonathan, because Wikipedia was a bit vague about the left hand portion of the curve when the mean is zero (and x<0). I guess the measurement theorists who did this work didn't care, because they were only interested in the extreme right hand end of the curve. Wiki suggested:


This is correct, but I missed the leading minus sign on the right hand side of the expression, so I did a bit of fiddling around. Anyway, it eventually worked. The illustration below shows my custom component under the JprogressBar it will replace (as well as the curve shown in full for an instance of the component not yet callibrated).

Tuesday, November 15, 2011

Creating a Custom Swing Component

I always return to my blog when I'm stuck, and I'm stuck right now.

I want to create a custom Swing component. Specifically, I want something like a JProgressBar, with the following changes:

  1. In place of a flat Foreground color, I want a rainbow spectrum, showing only the red range for low Values, and the whole spectrum for values close to the Maximum value;
  2. Instead of a rectangular box, I want the progress "bar" to take the shape of a normal, or Gaussian, distribution curve;
  3. I want progress to be displayed by the area under the curve, rather than by a simple linear scale along the x axis.

It's not that there isn't stuff out there. I have five tabs open in my browser, specifically addressing the creation of custom components in Swing, as well as the source code for the JProgressBar. It is that, like everything to do with Java, it is bloody difficult to read.

I shall begin from the horse's mouth as it were, with an article on the Java.net website entitled: How to Write a Custom Swing Component. It begins by defining the "building blocks" of Swing components as:

  • The component class itself, which provides an API for creating, changing, and querying the component basic state.
  • The model interface and the model default implementation(s) that handle the component business logic and change notifications.
  • The UI delegate that handles component layout, event handling (mouse and keyboard), and painting.

I understand the first four words of that lot. I hate it when documents, especially formal ones, use abbreviations without definitions, but a Google search on API produces a first page full of formal Sun/Oracle documents, which do that, even in the title.

According to an archived (by which I mean so old or unimportant that Oracle has not woven itself into the URL) glossary, API is defined as:

Application Programming Interface. The specification of how a programmer writing an application accesses the behavior and state of classes and objects.

So if you insert the full definition into the first bullet, you get:

  • The component class itself, which provides a specification of how a programmer writing an application accesses the behavior and state of classes and objects for creating, changing, and querying the component basic state.

And that is gibberish, like so much of the material used to describe Java, and the closer you get to "the horse" often the more confusing it gets. To be fair, if you insert the words behind the acronym, it looks a little better:

  • The component class itself, which provides an Application Programming Interface for creating, changing, and querying the component basic state.

But then it starts to overlap with the second "building block", which begins:

The model interface ...

When I first read that, I wasn't sure whether it said model or modal. Either way it is not clear how the model interface differs from the Application Programming Interface.

The third "building block" opens with:

The UI delegate ...

I used the same glossary to look up UI, and it wasn't even in there. A Google search on UI brings up a slew of pages on GUI, and the weight of evidence suggests "User Interface". So now we have Application Programming Interface, model interface, and a User Interface, each purportedly in their own "building block".

Are we really dealing with distinct building "building blocks" here, or a "blob" of amorphous building material with fuzzily defined functionality zones?

The next title in the article, after Basic Building Blocks, is The Component Class: UI Delegate Plumbing, which looks to me very like a composite of building blocks 1 and 3. The third heading is The Model Interface, so presumably it refers to the second building block. It includes some code, with two class declarations, and it opens with:

This (sic) is ... the most important class for a custom component.

The article continues, on and on, in a similarly confusing fashion, so I thought I'd cut to the chase and have a look at the source code and see if I could make it work. The code for the main class JFlexiSlider.java, begins with:

package org.jvnet.flamingo.slider;

import javax.swing.*;

import org.jvnet.flamingo.slider.FlexiRangeModel.Range;
import org.jvnet.flamingo.slider.ui.BasicFlexiSliderUI;
import org.jvnet.flamingo.slider.ui.FlexiSliderUI;

Three questions arise from this. Is the web address given for the imported classes in the public domain? Are the classes listed still there? And if so, is Java smart enough to navigate through the Internet to find them? When I tried to compile the class. The first of 18 errors was:

package org.jvnet.flamingo.slider.FlexiRangeModel does not exist

Out of curiosity I typed jvnet.org into my browser and it came up blank. I ran a whois on jvnet.org, and this confirmed that the domain name is registered, and to Oracle. So I guess that when this code was written, all the package and import information was meaningful, but now it certainly isn't. And to cut a long story short, the effort of addressing each error in turn to make the code run outweighed any possible benefit, so I gave up.

My next port of call was to the source code of the existing JProgressBar. One of eleven imported classes was:

import javax.swing.plaf.ProgressBarUI;

So I checked out the source code for this, which was:

public abstract class ProgressBarUI extends ComponentUI {

To do a proper job I should have downloaded the source code for ComponentUI as well, but to honest, the whole thing was rendered virtually unreadable by all the comments, so I reached another boredom threshold.

I then went to a much more readable article entitled Creating a custom component in Swing by a Danish gentleman called Christian Petersen. As my Rasch Itembank Project is inspired by the Danish Mathematician, Georg Rasch, I was happy to be reading something by one of his countrymen.

There were no remote or unreachable packages in the code given with this article (in fact there were no packages at all), and the code compiled and ran perfectly first time. Inspired by this success, and the simplicity of his approach, I went right back to basics, to a lesson in The Java Tutorial entitled Compiling and Running Swing Programs. This lesson gives a link to source code for a "program" called HelloWorldSwing.

HelloWorldSwing essentially displays a Swing component called JLabel, in another component called JFrame. I took this code and replaced the JLabel with the class for my rainbow colored Gaussian curve as follows:

import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
//Add the ubiquitous "Hello World" label.
NormJ2 label2 = new NormJ2();
//Display the window.
frame.setSize(520, 300);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {


And it came up as shown below:

I've left all the comments and the HelloWorldSwing heading (and even the component name: label2) to emphasize that creating a custom swing component is really as simple as that. You don't need packages, collections of remote and difficult to find "ui" classes. You just insert one class, compiled with Swing components, into another.

As components go, mine is currently somewhat limited. It looks pretty (though I say it myself), but it does nothing else. The purpose of all the guff at the head of this post is to bring components alive, but there has to be a simpler, more commonsense, way to do it.