Categories
Coding

Recursive Parameter Substitution Routine

I was recently looking at implementing a parameter substitution routine, along the lines of what Ant does for ${}-style properties. I initially picked up Spring’s PropertyPlaceholderConfigurer implementation, and created a modified version of the parseStringValue() routine, which is a recursive routine that unwraps delimited properties and resolves them. This did mostly what I want, but there were a few issues with it, mainly that it doesn’t handle truly recursive properties. For instance, if I want to do a Bash-style eval of a property ${FOO${BAR}}, where $BAR is mapped to "def", then I want the ultimate evaluation of this property to be ${FOOdef}.

This seems pretty simple to do in theory, as it would lend itself well to a recursive method, or an iterative method, possibly using a stack to store nested property names as we extract them from the string.

What I came up with was (if PREFIX is a property start delimiter, e.g. '{', and SUFFIX is a property end delimiter, e.g. '}'):

void recurse(StringBuilder str, int index) {
        if (str.indexOf(PREFIX, index) != -1)
            recurse(str, str.indexOf(PREFIX, index)+1);

            if (str.indexOf(PREFIX) == -1)
                return;

            String resolved = (str.substring(index, str.indexOf(SUFFIX, index)));
            str.replace(index-PREFIX.length(),
                    str.indexOf(SUFFIX, index)+SUFFIX.length(),
                    lookup(resolved));
    }

    private String lookup(String key) {
        System.out.println("looking up [" + key+  "] => [" + map.get(key) + "]");
        return map.get(key);
    }

Which does the job, although it could still be more elegant (not to mention efficient). The explicit check to str.indexOf(PREFIX) in order to exit the routine bugs me a little bit – I’m sure its possible to rearrange this to be more concise and skip the explicit check like that. Still this routine can now parse strings like TEXT{FOO}MORETEXT{BAR{GOO}} and resolve nested properties. I’m trrying to find a nicer recursive representation for this. maybe I should ask on #haskell.

Categories
Coding Finance R

Black-Scholes in R

Here is a simple implementation of the Black-Scholes pricing formula in R. This will return a two-element vector containing the calculated call and put price, respectively.

[source lang=”r”]
# Black-Scholes Option Value
# Call value is returned in values[1], put in values[2]
blackscholes <- function(S, X, rf, T, sigma) {
values <- c(2)

d1 <- (log(S/X)+(rf+sigma^2/2)*T)/(sigma*sqrt(T))
d2 <- d1 – sigma * sqrt(T)

values[1] <- S*pnorm(d1) – X*exp(-rf*T)*pnorm(d2)
values[2] <- X*exp(-rf*T) * pnorm(-d2) – S*pnorm(-d1)

values
}
[/source]

Example use:

> blackscholes(100,110,.05,1,.2)
[1] 6.040088 10.675325

Categories
Coding

Useful Regular Expressions, Part 2

Some useful regexes here that I have used recently here, saved in case I ever lose them (especially the last two). Firstly, an expression that parses NTLM credentials from HTTP BASIC authentication responses. Note the non-capturing groups ?: to keep indexing simple.

/* DOMAIN\\user(:pass)? or DOMAIN/user(:pass)? */
private static final Pattern CREDENTIALS_PATT = Pattern.compile("(?:(\\w+)(?:\\\\{1,2}|/))?(\\w+)(?::(\\w+))?");

Next, a regular expression to parse verbose garbage collection logs from JRockit GC log files:

s/^\[memory \]\[\([^]]\+\)\].*GC
\([0-9]\+\)K->\([0-9]\+\)K (\([0-9]\+\)K), \([0-9]\+\.[0-9]\+\) ms/\1,\2,\3,\4,\5/

This will return various columns including memory before and after collection, max heap size, and collection duration.

Similarly, for Sun JVMs:

s/.*GC \([0-9]\+\)K->\([0-9]\+\)K(\([0-9]\+\)K), \([0-9]\+\.[0-9]\+\) secs]/\1,\2,\3,\4/

Verbose GC logging is usually enabled via the -XXloggc option, e.g. -Xloggc:gc.log