Pages

Monday, May 23, 2016

Memoization in Python

# -*- coding: utf-8 -*-
"""


File name: fib_mem.py

Created on Mon May 23 14:50:39 2016


Source: MITx: 6.00x Introduction to Computer Science and Programming

Output:  222232244629420445529739893461909967206666939096499764990979600

PEP8 Style Compliant:
In Spyder: Preferences -> Editor -> Code Introspection/Analysis,
 near the bottom right, check Style analysis (pep8).


The 2nd way to run it:
 - Comment out "@my_memoize"
 - Uncomment "fib = my_memoize(fib)"
 - Run


The 3rd way to run it:
 >> from fib_mem import fib
 >> print(fib(300))


Tested on Python 3.x
"""


##########################################
# Example 1



def my_memoize(f):
    cache = {}


    def helper(*x):  # Refer to Item 18 of "Effective Python"
        if x not in cache:
            cache[x] = f(*x)
        return cache[x]
    return helper


@my_memoize
def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n-1) + fib(n-2)

# fib = memoize(fib)
print(fib(300))



##########################################
# Example 2 (stack overflow)
def functionDecorator(f):
    def new_f():
        print("Begin", f.__name__)
        foo() # using f() instead
        print("End", f.__name__)
        return new_f


@functionDecorator
def foo():
    print("inside foo()")


foo()
print(foo.__name__)


###############################################################


"Python is basically pseudo code, ..." -- Brett Slatkin, The author of "Effective Python".


Saturday, May 7, 2016

Matrix Calculus

What's the partial derivatives (w.r.t. μ and Σ) of this function?

       \ln(L)= -\frac{1}{2} \ln (|\boldsymbol\Sigma|\,) -\frac{1}{2}(\mathbf{x}-\boldsymbol\mu)^{\rm T}\boldsymbol\Sigma^{-1}(\mathbf{x}-\boldsymbol\mu) - \frac{k}{2}\ln(2\pi)

Yes, it's a beautiful formula: log-likelihood function of mvn distribution.

The answer can be found on page 40 of this book: The Matrix Cookbook

You will find equation (81), (57) and (61) are useful to get the partial derivatives.


The partial derivatives are used in Vibrato Monte Carlo method, which is a Path-wise/LRM hybrid method.

Note that there are a few alternative approaches to valuate financial derivatives which have non-differentiable payoff functions.

  • Likelihood Ratio Method (LRM) 
  • Mallianvin Calculus (Stochastic Calculus of Variations)
  • "Vibrato" Monte Carlo Method