首页 > 解决方案 > 基本二项式期权定价模型

问题描述

我尝试在 Java 中创建二项式期权定价模型树,但无法想出制作内部树的方法。

它应该是什么样子的图片

到目前为止,我拥有的代码是这个

  double[][] Price = new double[4][4];

  for (int i = 0; i < Price.length; i++) {
     Price[0][i] = Math.pow(m.U(), i);
     Price[i][0] = Math.pow(m.D(), i);
     System.out.println("u^" + i + ":" + Price[0][i]);
     System.out.println("d^" + i + ":" + Price[i][0]);
  }

这仅输出向上和向下分支,但我想要所有内部树分支,具体取决于存在的节点。

标签: javaalgorithm

解决方案


我认为要走的路是在自定义树结构上使用递归。

我将使用的结构类似于此处描述的结构,但作为二叉树(只有两个孩子)。例子 :

public class BinTree {
    private float data;
    private BinTree left; //left Sub-Tree
    private BinTree right; //right Sub-Tree

    /* creation of the tree */
    public Tree(float rootData) {
        data = rootData;
        /* left and right are NULL, which means that 
           there is no left child and no right child */
    }

    public addLeft(float data) {
        left = new BinTree(data);
        /* You can verify first if there's a child, 
           and maybe give an exception if there is */
    }
    public addRight(T data) {
        right = new BinTree(data);
        /* You can verify first if there's a child, 
           and maybe give an exception if there is */
    }

    /* methods like your algorithm */
    ...
}

您可以替换float为任何类型

使用这种结构,递归变得非常容易。

而要递归处理这个问题,你需要想象一下:你在一个节点上,你需要在这个节点上做什么?你需要在孩子身上涂抹一些东西吗?如果是,您如何使用相同的功能来获得预期的输出?

从我看到的你的照片来看,有3种情况:

1 - 当前节点的值为So

然后,你的孩子 left 应该得到 valueSo * u而你的孩子 right 应该得到 value So * d

2 - 当前节点的值为So * nd, 为n整数

然后,你的孩子左边应该得到价值So * (n-1)d(并且只是So如果n = 1),你的孩子右边应该得到价值So * (n+1)d

3 - 当前节点的值为So * nu, 为n整数

然后,你的孩子 left 应该得到 valueSo * (n+1)u而你的孩子 right 应该得到 value So * (n-1)u

所以(方法的)实现应该是这样的:

    public myAlgo(float s /*So*/, T/*the type of your variable m*/ m, int height) {
        myAlgo_rec(s, m, height, 0);
    }

    private myAlgo_rec(float s, T m, int height, int occurU) {
        /* occurU is equivalent to n, and indicates if we use U or D depending on the sign */
        if (height == 0) return; // Stop condition

        if (occurU = 0) {
            left = new BinTree(s * m.U);
            right = new BinTree(s * m.D);
            myAlgo_rec(s, m, height-1, 1);
            myAlgo_rec(s, m, height-1, -1);

        } else if (occurU < 0) {
            left = new BinTree(s * Math.pow(m.U(), -occurU+1));
            right = new BinTree(s * Math.pow(m.U(), -occurU-1));
            myAlgo_rec(s, m, height-1, occurU+1);
            myAlgo_rec(s, m, height-1, occurU-1);

        } else /*occurU > 0*/ {
            left = new BinTree(s * Math.pow(m.D(), occurU+1));
            right = new BinTree(s * Math.pow(m.D(), occurU-1));
            myAlgo_rec(s, m, height-1, occurU+1);
            myAlgo_rec(s, m, height-1, occurU-1);
        }
    }

这里是。通常,我认为如果您理解我所说的一切,您应该能够实现它或使用我的代码(并调试它)。


推荐阅读