vmarket: /* $Id: vmarket.java,v 1.13 2004/02/06 23:43:31 pde Exp $ */
vmarket:
vmarket: import java.util.*;
vmarket: import java.text.*;
vmarket: import java.awt.*;
vmarket: import java.lang.Math;
vmarket: import java.applet.Applet;
vmarket:
vmarket:
vmarket:
vmarket: /*****************************************************************************
vmarket: * VMarket -- a virtual market calculator for financial products in java
vmarket: *
vmarket: * Andre JAUN (jaun@.kth.se). Copyright 2002-2005. All Rights Reserved.
vmarket: * @version 4.4 (CVS/RCS $Revision: 1.13 $)
vmarket: * Educational software distributed by www.lifelong-learners.com.
vmarket: *
vmarket: * The authors makes no representations or warranties about the suitability
vmarket: * of the software, either express or implied, including but not limited
vmarket: * to the implied warranties of merchantability, fitness for a particular
vmarket: * purpose, or non-infringement.
vmarket: * The authors shall not be liable for any damages suffered by licensee as
vmarket: * a result of using or modifying this software or its derivatives.
vmarket: ******************************************************************************/
vmarket: public class vmarket extends Applet implements RunDataNotable, Runnable {
vmarket:
vmarket: /** Stock option */
vmarket: final static String STKOPTION = "StckOption";
vmarket: /** Bond */
vmarket: final static String BOND = "ZeroCpBond";
vmarket: /** Caplet */
vmarket: final static String BNDOPTION = "BondOption";
vmarket: /** Swap */
vmarket: final static String SWAP = "IRateSwap";
vmarket: /** Financial models (Black, Vasicek, CIR, BDT, etc) */
vmarket: final static String FMODEL = "CreditModel";
vmarket: /** Random walk processes in physics */
vmarket: final static String RNDWALK = "RandomWalk";
vmarket: /** Exercise to be inserted */
vmarket: final static String EXERCISE = "Exercise";
vmarket: /** Vector of the names of different topics @see Solution */
vmarket: final static String[] topicNames = {STKOPTION, BOND, BNDOPTION, SWAP,
vmarket: FMODEL, RNDWALK, EXERCISE};
vmarket: /** GUI list of all the topics */
vmarket: private MyChoice topicSelection;
vmarket:
vmarket: /** Solve with finite differances */
vmarket: final static String FD = "FinDifferen";
vmarket: /** Solve with finite elements method */
vmarket: final static String FEM = "FinElements";
vmarket: /** Solve expected value with Monte-Carlo sampling methods */
vmarket: final static String SMP = "Monte-Carlo";
vmarket: /** Solve expected value with Monte-Carlo sampling methods plot dots */
vmarket: final static String SMPS= "Monte-Carlo*";
vmarket: /** Distribution function from a random walk of particles */
vmarket: final static String PPP = "DistribFct";
vmarket: /** Distribution function from a random walk of particles plot dots */
vmarket: final static String PPPS= "DistribFct*";
vmarket: /** Method selector */
vmarket: static String[] methodNames = {FD, FEM, SMP, SMPS, PPP, PPPS};
vmarket: /** GUI list of all the methods */
vmarket: private MyChoice methodSelection;
vmarket:
vmarket: /** Solve with Standard scheme */
vmarket: final static String DEFAULT = "Standard";
vmarket: /** European option without normalizing */
vmarket: final static String EUSTY = "European";
vmarket: /** European option in normalized variables */
vmarket: final static String EUNORM = "European logn";
vmarket: /** American option without normalizing */
vmarket: final static String AMSTY = "American";
vmarket: /** American option in normalized variables */
vmarket: final static String AMNORM = "American logn";
vmarket: /** Monte-Carlo for in-barrier option */
vmarket: final static String INBAR = "inBarrier";
vmarket: /** Monte-Carlo for out-barrier option */
vmarket: final static String OUTBAR = "outBarrier";
vmarket: /** Monte-Carlo particles*/
vmarket: final static String MCPART = "particles";
vmarket: /** Solve by sampling with a tree */
vmarket: final static String TREE2 = "binomTree";
vmarket: /** Vasicek model */
vmarket: final static String VASICEK = "Vasicek model";
vmarket: /** Cox Inggersoll and Ross model */
vmarket: final static String CIR = "CIR model";
vmarket: /** Black Derman and Toy model */
vmarket: final static String BDT = "BDT model";
vmarket: /** Hull and White model */
vmarket: final static String HW = "Hull White";
vmarket: /** Solution of exercise 1.01 */ final static String EXC1_01="Exercise 1.01";
vmarket: /** Solution of exercise 1.02 */ final static String EXC1_02="Exercise 1.02";
vmarket: /** Solution of exercise 1.03 */ final static String EXC1_03="Exercise 1.03";
vmarket: /** Solution of exercise 1.04 */ final static String EXC1_04="Exercise 1.04";
vmarket: /** Solution of exercise 1.05 */ final static String EXC1_05="Exercise 1.05";
vmarket: /** Solution of exercise 1.06 */ final static String EXC1_06="Exercise 1.06";
vmarket: /** Solution of exercise 1.07 */ final static String EXC1_07="Exercise 1.07";
vmarket: /** Solution of exercise 1.08 */ final static String EXC1_08="Exercise 1.08";
vmarket: /** Solution of exercise 1.09 */ final static String EXC1_09="Exercise 1.09";
vmarket: /** Solution of exercise 1.10 */ final static String EXC1_10="Exercise 1.10";
vmarket: /** Solution of exercise 2.01 */ final static String EXC2_01="Exercise 2.01";
vmarket: /** Solution of exercise 2.02 */ final static String EXC2_02="Exercise 2.02";
vmarket: /** Solution of exercise 2.03 */ final static String EXC2_03="Exercise 2.03";
vmarket: /** Solution of exercise 2.04 */ final static String EXC2_04="Exercise 2.04";
vmarket: /** Solution of exercise 2.05 */ final static String EXC2_05="Exercise 2.05";
vmarket: /** Solution of exercise 2.06 */ final static String EXC2_06="Exercise 2.06";
vmarket: /** Solution of exercise 2.07 */ final static String EXC2_07="Exercise 2.07";
vmarket: /** Solution of exercise 2.08 */ final static String EXC2_08="Exercise 2.08";
vmarket: /** Solution of exercise 2.09 */ final static String EXC2_09="Exercise 2.09";
vmarket: /** Solution of exercise 2.10 */ final static String EXC2_10="Exercise 2.10";
vmarket: /** Solution of exercise 3.01 */ final static String EXC3_01="Exercise 3.01";
vmarket: /** Solution of exercise 3.02 */ final static String EXC3_02="Exercise 3.02";
vmarket: /** Solution of exercise 3.03 */ final static String EXC3_03="Exercise 3.03";
vmarket: /** Solution of exercise 3.04 */ final static String EXC3_04="Exercise 3.04";
vmarket: /** Solution of exercise 3.05 */ final static String EXC3_05="Exercise 3.05";
vmarket: /** Solution of exercise 4.01 */ final static String EXC4_01="Exercise 4.01";
vmarket: /** Solution of exercise 4.02 */ final static String EXC4_02="Exercise 4.02";
vmarket: /** Solution of exercise 4.03 */ final static String EXC4_03="Exercise 4.03";
vmarket: /** Solution of exercise 4.04 */ final static String EXC4_04="Exercise 4.04";
vmarket: /** Solution of exercise 4.05 */ final static String EXC4_05="Exercise 4.05";
vmarket: /** Solution of exercise 4.06 */ final static String EXC4_06="Exercise 4.06";
vmarket: /** Solution of exercise 4.07 */ final static String EXC4_07="Exercise 4.07";
vmarket: /** Solution of exercise 4.08 */ final static String EXC4_08="Exercise 4.08";
vmarket: /** Solution of exercise 4.09 */ final static String EXC4_09="Exercise 4.09";
vmarket: /** Solution of exercise 4.10 */ final static String EXC4_10="Exercise 4.10";
vmarket: /** Solution of exercise 4.11 */ final static String EXC4_11="Exercise 4.11";
vmarket: /** Solution of exercise 4.12 */ final static String EXC4_12="Exercise 4.12";
vmarket: /** Solution of exercise 4.13 */ final static String EXC4_13="Exercise 4.13";
vmarket: /** Solution of exercise 4.14 */ final static String EXC4_14="Exercise 4.14";
vmarket: /** Solution of exercise 4.15 */ final static String EXC4_15="Exercise 4.15";
vmarket: /** Solution of exercise 5.01 */ final static String EXC5_01="Exercise 5.01";
vmarket: /** Solution of exercise 5.02 */ final static String EXC5_02="Exercise 5.02";
vmarket: /** Solution of exercise 5.03 */ final static String EXC5_03="Exercise 5.03";
vmarket: /** Solution of exercise 5.04 */ final static String EXC5_04="Exercise 5.04";
vmarket: /** Solution of exercise 5.05 */ final static String EXC5_05="Exercise 5.05";
vmarket: /** Solution of exercise 5.06 */ final static String EXC5_06="Exercise 5.06";
vmarket: /** Solution of exercise 5.07 */ final static String EXC5_07="Exercise 5.07";
vmarket: /** Solution of exercise 5.08 */ final static String EXC5_08="Exercise 5.08";
vmarket: /** Solution of exercise 5.09 */ final static String EXC5_09="Exercise 5.09";
vmarket: /** Solution of exercise 5.10 */ final static String EXC5_10="Exercise 5.10";
vmarket: /** Solution of exercise 5.11 */ final static String EXC5_11="Exercise 5.11";
vmarket: /** Solution of exercise 5.12 */ final static String EXC5_12="Exercise 5.12";
vmarket: /** Solution of exercise 5.13 */ final static String EXC5_13="Exercise 5.13";
vmarket: /** Solution of exercise 5.14 */ final static String EXC5_14="Exercise 5.14";
vmarket: /** Solution of exercise 5.15 */ final static String EXC5_15="Exercise 5.15";
vmarket: /** Solution of exercise 6.01 */ final static String EXC6_01="Exercise 6.01";
vmarket: /** Solution of exercise 6.02 */ final static String EXC6_02="Exercise 6.02";
vmarket: /** Solution of exercise 6.03 */ final static String EXC6_03="Exercise 6.03";
vmarket: /** Solution of exercise 6.04 */ final static String EXC6_04="Exercise 6.04";
vmarket: /** Solution of exercise 6.05 */ final static String EXC6_05="Exercise 6.05";
vmarket: /** Solution of exercise 6.06 */ final static String EXC6_06="Exercise 6.06";
vmarket: /** Solution of exercise 6.07 */ final static String EXC6_07="Exercise 6.07";
vmarket: /** Solution of exercise 6.08 */ final static String EXC6_08="Exercise 6.08";
vmarket: /** Solution of exercise 6.09 */ final static String EXC6_09="Exercise 6.09";
vmarket: /** Solution of exercise 6.10 */ final static String EXC6_10="Exercise 6.10";
vmarket: /** Solution of exercise 6.11 */ final static String EXC6_11="Exercise 6.11";
vmarket: /** Solution of exercise 6.12 */ final static String EXC6_12="Exercise 6.12";
vmarket: /** Solution of exercise 6.13 */ final static String EXC6_13="Exercise 6.13";
vmarket: /** Solution of exercise 6.14 */ final static String EXC6_14="Exercise 6.14";
vmarket: /** Solution of exercise 6.15 */ final static String EXC6_15="Exercise 6.15";
vmarket: /** Solution of exercise 7.01 */ final static String EXC7_01="Exercise 7.01";
vmarket: /** Solution of exercise 7.02 */ final static String EXC7_02="Exercise 7.02";
vmarket: /** Solution of exercise 7.03 */ final static String EXC7_03="Exercise 7.03";
vmarket: /** Solution of exercise 7.04 */ final static String EXC7_04="Exercise 7.04";
vmarket: /** Solution of exercise 7.05 */ final static String EXC7_05="Exercise 7.05";
vmarket: /** Solution of exercise 7.06 */ final static String EXC7_06="Exercise 7.06";
vmarket: /** Solution of exercise 7.07 */ final static String EXC7_07="Exercise 7.07";
vmarket: /** Solution of exercise 7.08 */ final static String EXC7_08="Exercise 7.08";
vmarket: /** Solution of exercise 7.09 */ final static String EXC7_09="Exercise 7.09";
vmarket: /** Solution of exercise 7.10 */ final static String EXC7_10="Exercise 7.10";
vmarket: /** Solution of exercise A.01 */ final static String EXCA_01="Exercise A.01";
vmarket: /** Solution of exercise B.01 */ final static String EXCB_01="Exercise B.01";
vmarket: /** Solution of exercise C.01 */ final static String EXCC_01="Exercise C.01";
vmarket: /** Solution of exercise D.01 */ final static String EXCD_01="Exercise D.01";
vmarket: /** Solution of exercise E.01 */ final static String EXCE_01="Exercise E.01";
vmarket: /** Solution of exercise F.01 */ final static String EXCF_01="Exercise F.01";
vmarket: /** Vector of the names of all the schemes @see Solution */
vmarket: final static String[] schemeNames =
vmarket: {EUSTY, AMSTY, EUNORM, AMNORM,
vmarket: INBAR, OUTBAR, MCPART, VASICEK,
vmarket: EXC1_01, EXC1_02, EXC1_03, EXC1_04, EXC1_05,
vmarket: EXC1_06, EXC1_07, EXC1_08, EXC1_09, EXC1_10,
vmarket: EXC2_01, EXC2_02, EXC2_03, EXC2_04, EXC2_05,
vmarket: EXC2_06, EXC2_07, EXC2_08, EXC2_09, EXC2_10,
vmarket: EXC3_01, EXC3_02, EXC3_03, EXC3_04, EXC3_05,
vmarket: EXC4_01, EXC4_02, EXC4_03, EXC4_04, EXC4_05,
vmarket: EXC4_06, EXC4_07, EXC4_08, EXC4_09, EXC4_10,
vmarket: EXC4_11, EXC4_12, EXC4_13, EXC4_14, EXC4_15,
vmarket: EXC5_01, EXC5_02, EXC5_03, EXC5_04, EXC5_05,
vmarket: EXC5_06, EXC5_07, EXC5_08, EXC5_09, EXC5_10,
vmarket: EXC5_11, EXC5_12, EXC5_13, EXC5_14, EXC5_15,
vmarket: EXC6_01, EXC6_02, EXC6_03, EXC6_04, EXC6_05,
vmarket: EXC6_06, EXC6_07, EXC6_08, EXC6_09, EXC6_10,
vmarket: EXC6_11, EXC6_12, EXC6_13, EXC6_14, EXC6_15,
vmarket: EXC7_01, EXC7_02, EXC7_03, EXC7_04, EXC7_05,
vmarket: EXC7_06, EXC7_07, EXC7_08, EXC7_09, EXC7_10,
vmarket: EXCA_01, EXCB_01, EXCC_01, EXCD_01, EXCE_01,
vmarket: EXCF_01};
vmarket: /** GUI list of all the schemes */
vmarket: private MyChoice schemeSelection;
vmarket:
vmarket: /** Call option teminal payoff */
vmarket: final static String CALL = "Call";
vmarket: /** Put option teminal payoff */
vmarket: final static String PUT = "Put";
vmarket: /** Binary or digital option teminal payoff */
vmarket: final static String BINARY = "VSpread";
vmarket: /** A box as initial condition */
vmarket: final static String BOX = "SuperShr";
vmarket: /** Discount function or Swap initial condition */
vmarket: final static String CONST = "Constant";
vmarket: /** Caplet initial condition */
vmarket: final static String CAPLET = "Caplet";
vmarket: /** Caplet initial condition */
vmarket: final static String FLOORLET = "Floorlet";
vmarket: /** A gaussian as initial condition */
vmarket: final static String GAUSSIAN = "Gaussian";
vmarket: /** Vector of the names of initial conditions @see ShapeFunction */
vmarket: final static String[] icNames = {PUT, CALL, BINARY, BOX, CONST,
vmarket: CAPLET, FLOORLET, GAUSSIAN};
vmarket: /** GUI list of all the ICs */
vmarket: private MyChoice icSelection;
vmarket:
vmarket: /** Operate edit mode with TAG parameters displayed by default */
vmarket: final static String EDIT = "Double-click below:";
vmarket: /** Operate edit mode with ALL parameters displayed */
vmarket: final static String EDITALL = "Show all parameters";
vmarket: /** Operate a console output of the function values */
vmarket: final static String CONSOLE = "Print data to console ";
vmarket: /** Vector of the names of all the operations */
vmarket: static String[] operNames = {EDIT, EDITALL, CONSOLE};
vmarket: /** GUI list of all the operations */
vmarket: private MyChoice operSelection;
vmarket:
vmarket: /** The plot area */
vmarket: private PlotArea plotArea;
vmarket: /** The run parameters */
vmarket: private RunData runData;
vmarket: /** Text for Start/Stop button */
vmarket: private final String startName = "Start/Stop";
vmarket: /** Text for Step 1 button */
vmarket: private final String step1Name = "Step 1";
vmarket: /** Text for toggle display button */
vmarket: private final String displayName = "Display";
vmarket: /** Text for print stop to console */
vmarket: private final String printCName = "Print Console";
vmarket: /** Text for initialize button */
vmarket: private final String initializeName = "Reset";
vmarket:
vmarket: /** Whether the simulation is running */
vmarket: private boolean frozen = true;
vmarket: /** Current step number */
vmarket: private int step = 0;
vmarket: /** Operate nsteps before stopping */
vmarket: private int nstep = -1;
vmarket: /** Milliseconds between plots */
vmarket: private int delay = 84;
vmarket: /** Thread label */
vmarket: Thread runThread;
vmarket: /** Potentially reset by main */
vmarket: private boolean isAnApplet = true;
vmarket: /** Inhibits events during creation of selectos */
vmarket: private boolean blockEvents = true;
vmarket: /** The solution */
vmarket: private Solution solution;
vmarket:
vmarket:
vmarket: /** Information
vmarket: ****************************************************************************/
vmarket: public String getAppletInfo() {
vmarket: return "VMARKET 4.0 -- an educational software (C) 2002-2004 by A. Jaun";
vmarket: }
vmarket:
vmarket: /** Master initialization and layout
vmarket: ****************************************************************************/
vmarket: public void init() {
vmarket: topicSelection = new MyChoice(topicNames);
vmarket: methodSelection = new MyChoice(methodNames);
vmarket: schemeSelection = new MyChoice(schemeNames);
vmarket: icSelection = new MyChoice(icNames);
vmarket: operSelection = new MyChoice(operNames);
vmarket: runData = new RunData(this);
vmarket:
vmarket: if (isAnApplet) tagModify();
vmarket: createWindow();
vmarket: createSolution();
vmarket: setInitialCondition(solution);
vmarket: blockEvents=false;
vmarket: } // init
vmarket:
vmarket: /** Instanciate a GUI window
vmarket: @see Solution
vmarket: ***************************************************************************/
vmarket: private void createWindow(){
vmarket: // First the layout
vmarket: GridBagLayout gb = new GridBagLayout();
vmarket: GridBagConstraints c = new GridBagConstraints();
vmarket:
vmarket: this.setBackground(new Color(Integer.parseInt("88FFFF",16)));
vmarket: setFont(new Font("Courier", Font.PLAIN, 12));
vmarket: setLayout(gb);
vmarket:
vmarket: // Prepare for top row of buttons
vmarket: c.gridwidth = 1;
vmarket: c.gridheight = 1;
vmarket: c.weightx = 1;
vmarket: c.fill = GridBagConstraints.HORIZONTAL;
vmarket:
vmarket: // Engage
vmarket: gbAdd(gb, c, methodSelection);
vmarket: gbAdd(gb, c, schemeSelection);
vmarket: gbAdd(gb, c, icSelection);
vmarket: gbAdd(gb, c, topicSelection);
vmarket: c.gridwidth = GridBagConstraints.REMAINDER; //end of row
vmarket: gbAdd(gb, c, operSelection);
vmarket:
vmarket: // Mr Data, take us to the next row please
vmarket: c.gridwidth = GridBagConstraints.RELATIVE;
vmarket: c.gridheight = 1;
vmarket: c.gridwidth = 4;
vmarket: c.weightx = 0;
vmarket: c.weighty = 1;
vmarket: c.fill = GridBagConstraints.BOTH;
vmarket: plotArea = new PlotArea();
vmarket: gbAdd(gb, c, plotArea);
vmarket: c.gridwidth = GridBagConstraints.REMAINDER; //end of row
vmarket:
vmarket: gbAdd(gb, c, runData);
vmarket:
vmarket: // Finally the last row
vmarket: c.gridwidth = 1;
vmarket: c.weighty = 0;
vmarket: c.fill = GridBagConstraints.HORIZONTAL;
vmarket: gbAdd(gb, c, new Button(startName));
vmarket: gbAdd(gb, c, new Button(step1Name));
vmarket: gbAdd(gb, c, new Button(displayName));
vmarket: gbAdd(gb, c, new Button(printCName));
vmarket: c.gridwidth = GridBagConstraints.REMAINDER; //end of row
vmarket: gbAdd(gb, c, new Button(initializeName));
vmarket:
vmarket: } // createWindow
vmarket:
vmarket:
vmarket: /** Helper method for adding objects to a GridBagLayout
vmarket: @param gb The layout
vmarket: @param c The constraints
vmarket: @param item The object to add
vmarket: */
vmarket: private void gbAdd(GridBagLayout gb, GridBagConstraints c, Component item){
vmarket: gb.setConstraints(item, c);
vmarket: add(item);
vmarket: } // gbAdd
vmarket:
vmarket:
vmarket: /** Instanciate a solution and select the method and scheme for computations
vmarket: @see Solution
vmarket: @return A new Solution
vmarket: ***************************************************************************/
vmarket: private void createSolution(){
vmarket: runData.createMesh();
vmarket: if(methodSelection.getSelectedItem().equals(FD)) {
vmarket: solution = new FDSolution(runData);
vmarket: } else if(methodSelection.getSelectedItem().equals(FEM)){
vmarket: solution = new FEMSolution(runData);
vmarket: } else if(methodSelection.getSelectedItem().equals(PPP)){
vmarket: solution = new MCPSolution(runData);
vmarket: } else if(methodSelection.getSelectedItem().equals(PPPS)){
vmarket: solution = new MCPDrawSolution(runData);
vmarket: } else if(methodSelection.getSelectedItem().equals(SMP)){
vmarket: solution = new MCSSolution(runData);
vmarket: } else if(methodSelection.getSelectedItem().equals(SMPS)){
vmarket: solution = new MCSDrawSolution(runData);
vmarket: } else {
vmarket: /** throw new MethodException("Can't find method"
vmarket: + methodSelection.getSelectedItem()); */
vmarket: } // if
vmarket:
vmarket: String ch; //Synchronize the choices is delicate
vmarket: topicSelection.sync(solution); //Assume that created consistent
vmarket: ch=topicSelection.getSelectedItem();
vmarket: if(ch==null) System.out.println("ERROR in vmarket: topicSelection ="+ch);
vmarket: solution.setTopic(ch);
vmarket: ch=methodSelection.getSelectedItem();
vmarket: if(ch==null) System.out.println("ERROR in vmarket: methodSelection ="+ch);
vmarket: solution.setMethod(ch);
vmarket: schemeSelection.sync(solution); //Assume that created consistent
vmarket: ch=schemeSelection.getSelectedItem();
vmarket: if(ch==null) System.out.println("ERROR in vmarket: schemeSelection ="+ch);
vmarket: solution.setScheme(ch);
vmarket: plotArea.setSolution(solution);
vmarket: } // createSolution
vmarket:
vmarket: /** Set the initial condition according to the runData parameters.
vmarket: @param solution The solution to initialize
vmarket: @see Solution
vmarket: ****************************************************************************/
vmarket: private void setInitialCondition(Solution solution){
vmarket: step = 0;
vmarket: double strike = runData.getParamValue(runData.strikePriceNm);
vmarket: double amplit = runData.getParamValue(runData.shape0Nm);
vmarket: double slope = runData.getParamValue(runData.shape1Nm);
vmarket: double convex = runData.getParamValue(runData.shape2Nm);
vmarket: double meshLen= runData.getParamValue(runData.meshLengthNm);
vmarket: if(icSelection.getSelectedItem().equals(CALL)){
vmarket: solution.discretize(new ShapeCall(strike));
vmarket: } else if(icSelection.getSelectedItem().equals(PUT)){
vmarket: solution.discretize(new ShapePut(strike));
vmarket: } else if(icSelection.getSelectedItem().equals(BOX)){
vmarket: solution.discretize(new ShapeBox(strike,amplit,slope));
vmarket: } else if(icSelection.getSelectedItem().equals(BINARY)){
vmarket: solution.discretize(new ShapeSpread(strike,amplit,slope));
vmarket: } else if(icSelection.getSelectedItem().equals(CONST)){
vmarket: solution.discretize(new ShapeBox(meshLen,amplit,2*meshLen));
vmarket: } else if(icSelection.getSelectedItem().equals(CAPLET)){
vmarket: solution.discretize(new ShapeBox(meshLen,amplit,2*meshLen));
vmarket: } else if(icSelection.getSelectedItem().equals(FLOORLET)){
vmarket: solution.discretize(new ShapeBox(meshLen,amplit,2*meshLen));
vmarket: } else if(icSelection.getSelectedItem().equals(GAUSSIAN)){
vmarket: solution.discretize(new ShapeGaussian(strike,amplit,slope));
vmarket: } else {
vmarket: /** throw new ShapeException("Can't find shape"
vmarket: + icSelection.getSelectedItem()); */
vmarket: } // if
vmarket: solution.setIC(icSelection.getSelectedItem());
vmarket: solution.setTime(0);
vmarket: solution.rescale(false);
vmarket: solution.previous(runData);
vmarket: solution.updateHeaders(runData, step);
vmarket: plotArea.repaint();
vmarket: } // setInitialCondition
vmarket:
vmarket: /** Modify defaults parameters the HTML tags from the web page
vmarket: ****************************************************************************/
vmarket: public void tagModify() {
vmarket: String tmp;
vmarket: if((tmp = getParameter("topic")) != null) topicSelection.select(tmp);
vmarket: if((tmp = getParameter("scheme")) != null) schemeSelection.select(tmp);
vmarket: if((tmp = getParameter("ic")) != null) icSelection.select(tmp);
vmarket: if((tmp = getParameter("method")) != null) methodSelection.select(tmp);
vmarket: runData.tagModify(this);
vmarket: } // tagModify
vmarket:
vmarket: /** Parameter info
vmarket: ****************************************************************************/
vmarket: public String[][] getParameterInfo() {
vmarket: String[][] info = {
vmarket: {"topic", "name", "Type of the financial product"},
vmarket: {"scheme", "name", "Particular flavour of the produt"},
vmarket: {"method", "name", "Numerical method to use for the calculation"},
vmarket: {"ic", "name", "Shape of the initial condition"},
vmarket: {"RunTime", "double", "Run time [years]"},
vmarket: {"Drift", "double", "Drift of the stochastic variable"},
vmarket: {"Volatility", "double", "Volatility of the stochastic variable"},
vmarket: {"LogNkappa", "double", "Exponent in the random walk"},
vmarket: {"SpotRate", "double", "Present value of the interest rate [1/year]"},
vmarket: {"Dividend", "double", "Dividend yield [1/years]"},
vmarket: {"StrikePrice", "double", "Option exercise price at expiry"},
vmarket: {"MktPriceRsk", "double", "Market price of risk"},
vmarket: {"MeanRevTarg", "double", "Target of mean reversion process"},
vmarket: {"MeanRevVelo", "double", "Velocity of mean reversion process"},
vmarket: {"Shape0", "double", "Initial shape amplitude"},
vmarket: {"Shape1", "double", "Initial shape slope"},
vmarket: {"Shape2", "double", "Initial shape convexity"},
vmarket: {"MeshLeft", "double", "Lower value of x-axis"},
vmarket: {"MeshLength", "double", "Length of x-axis"},
vmarket: {"MeshPoints", "int", "The number of mesh points on x-axis"},
vmarket: {"Walkers", "int", "The number of random walkers"},
vmarket: {"TimeStep", "double", "Time step [1/year]"},
vmarket: {"TimeTheta", "double", "Implicity parameter for time integration"},
vmarket: {"TuneQuad", "double", "Tunable quadrature parameter for FEM"},
vmarket: {"UserInteger", "int", "User defined data"},
vmarket: {"UserDouble", "double", "User defined data"}
vmarket: };
vmarket: return info;
vmarket: } // getParameterInfo
vmarket:
vmarket: /** Applet start a new thread
vmarket: ****************************************************************************/
vmarket: public void start() {
vmarket: if (runThread == null) { //Start a new thread
vmarket: runThread = new Thread(this);
vmarket: }
vmarket: if (frozen) { //Wait for an action from the user
vmarket: } else { runThread.start(); } //... or on with the calculation
vmarket: }
vmarket:
vmarket: /** Applet stop
vmarket: ****************************************************************************/
vmarket: public void stop() {
vmarket: runThread = null;
vmarket: frozen = true;
vmarket: }
vmarket:
vmarket: /** Contains the main loop for the time stepping.
vmarket: @see ShapeFunction
vmarket: @see Mesh
vmarket: @see Solution
vmarket: ****************************************************************************/
vmarket: public void run() {
vmarket: Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
vmarket: long startTime = System.currentTimeMillis();
vmarket: Thread currentThread = Thread.currentThread();
vmarket: double runTime = runData.getParamValue(runData.runTimeNm);
vmarket: double timeStep = runData.getParamValue(runData.timeStepNm);
vmarket:
vmarket: while (currentThread == runThread && !frozen &&
vmarket: ( solution.getTime() < runTime && nstep < 0 ||
vmarket: nstep > 0 ) ) {
vmarket: step++; nstep--; //One step forward in time
vmarket:
vmarket: solution.incTime(timeStep);
vmarket: solution.updateHeaders(runData, step);
vmarket: solution.next(runData);
vmarket:
vmarket: if(operSelection.getSelectedItem().equals(CONSOLE))
vmarket: solution.output(step); //Output in ASCII
vmarket: plotArea.repaint(); //Update graphics
vmarket:
vmarket: try { startTime += delay; //Delay according to lag
vmarket: Thread.sleep(Math.max(30, startTime-System.currentTimeMillis()));
vmarket: } catch (InterruptedException e) { break; }
vmarket: } // while
vmarket: frozen=true;
vmarket: } // run
vmarket:
vmarket: /** A new mesh is created by RunData
vmarket: @see RunData
vmarket: ****************************************************************************/
vmarket: public void runDataNotifyMesh(){
vmarket: createSolution();
vmarket: setInitialCondition(solution);
vmarket: } // runDataNotifyMesh
vmarket:
vmarket: /** The number of particles is changed by RunData
vmarket: @see RunData
vmarket: ****************************************************************************/
vmarket: public void runDataNotifyWalkers(){
vmarket: createSolution();
vmarket: setInitialCondition(solution);
vmarket: } // runDataNotifyWalkers
vmarket:
vmarket: /** Responds to the user actions through the mouse and buttons (Java1.0).
vmarket: Yes, we know this sucks compare to Java 1.1, but we want to be
vmarket: compatible with as many browsers as possible. There is a lot of
vmarket: old stuff out there...
vmarket: @deprecated
vmarket: ****************************************************************************/
vmarket: public boolean action(Event e, Object arg) {
vmarket: if (blockEvents) {
vmarket: return true;
vmarket: } else if (e.target instanceof Choice){
vmarket: for(int i = 0; i < topicNames.length; i++)
vmarket: if(((String)arg).equals(topicNames[i])){
vmarket: solution.setTopic(topicSelection.getSelectedItem());
vmarket: schemeSelection.sync(solution);
vmarket: solution.setScheme(schemeSelection.getSelectedItem());
vmarket: setInitialCondition(solution);
vmarket: return true;
vmarket: } // if
vmarket: for(int i = 0; i < methodNames.length; i++)
vmarket: if(((String)arg).equals(methodNames[i])){
vmarket: createSolution();
vmarket: solution.setScheme(schemeSelection.getSelectedItem());
vmarket: setInitialCondition(solution);
vmarket: return true;
vmarket: } // if
vmarket: for(int i = 0; i < schemeNames.length; i++)
vmarket: if(((String)arg).equals(schemeNames[i])){
vmarket: solution.setScheme(schemeSelection.getSelectedItem());
vmarket: setInitialCondition(solution);
vmarket: return true;
vmarket: } // if
vmarket: for(int i = 0; i < icNames.length; i++)
vmarket: if(((String)arg).equals(icNames[i])){
vmarket: setInitialCondition(solution);
vmarket: solution.setIC(icSelection.getSelectedItem());
vmarket: return true;
vmarket: } // if
vmarket: if (EDIT.equals(operSelection.getSelectedItem()))
vmarket: runData.displayTag(this);
vmarket: if (EDITALL.equals(operSelection.getSelectedItem()))
vmarket: runData.displayAll();
vmarket: } // if
vmarket: if(e.target instanceof Button) {
vmarket: boolean ret = false;
vmarket: if(((String)arg).equals(startName)) {
vmarket: frozen = !frozen;
vmarket: nstep = -1;
vmarket: ret = true;
vmarket: } else if(((String)arg).equals(step1Name)) {
vmarket: frozen = false;
vmarket: nstep = 1;
vmarket: ret = true;
vmarket: } else if(((String)arg).equals(printCName)) {
vmarket: solution.output(step);
vmarket: ret = true;
vmarket: } else if(((String)arg).equals(displayName)) {
vmarket: boolean headers=plotArea.toggleHeaders();
vmarket: solution.rescale(headers);
vmarket: plotArea.repaint();
vmarket: ret = true;
vmarket: } else if(((String)arg).equals(initializeName)) {
vmarket: frozen = true;
vmarket: runData.createMesh();
vmarket: createSolution();
vmarket: setInitialCondition(solution);
vmarket: step = 0;
vmarket: nstep = -1;
vmarket: ret = true;
vmarket: } // if
vmarket: if(ret) {
vmarket: runThread = null;
vmarket: start();
vmarket: } // if
vmarket: return ret;
vmarket: } // if
vmarket: return false;
vmarket: } // action
vmarket:
vmarket: /** Destroy application
vmarket: @deprecated
vmarket: ****************************************************************************/
vmarket: public boolean handleEvent(Event e) { //Java1.0
vmarket: if (e.id == Event.WINDOW_DESTROY) { System.exit(0); }
vmarket: return super.handleEvent(e);
vmarket: }
vmarket:
vmarket: /** Print mouse coordinates to console
vmarket: @deprecated
vmarket: ****************************************************************************/
vmarket: //Java1.0: public boolean mouseXXX(Event e, int x, int y)
vmarket: //Java1.0: with XXX={Up, Down, Drag, Enter, Exit}
vmarket: public boolean mouseDown(Event e, int x, int y) { //Java1.0
vmarket: double[] coord = solution.measure(x,y);
vmarket: double timeStep = runData.getParamValue(runData.timeStepNm);
vmarket:
vmarket: if (isAnApplet)
vmarket: showStatus("Clicked coord ("+coord[0]+" ; "+coord[1]+")");
vmarket: System.out.println("step="+step+
vmarket: " time="+(step*timeStep)+
vmarket: " coord=("+coord[0]+" ; "+coord[1]+")");
vmarket: return true;
vmarket: }
vmarket:
vmarket: /** Method to start the Applet as an application
vmarket: @param args Not used
vmarket: ****************************************************************************/
vmarket: public static void main(String[] args) {
vmarket: Frame f = new Frame("vmarket");
vmarket: vmarket vMarket = new vmarket();
vmarket: vMarket.isAnApplet = false;
vmarket: vMarket.init();
vmarket: f.add("Center", vMarket);
vmarket: f.pack();
vmarket: f.show();
vmarket: } // main
vmarket:
vmarket: } // vmarket
BandMatrix: /* $Id: BandMatrix.java,v 1.10 2002/07/24 16:22:55 pde Exp $ */
BandMatrix:
BandMatrix: /***************************************************************************
BandMatrix: * BandMatrix - Linear algebra package for band matrices
BandMatrix: ***************************************************************************/
BandMatrix: public class BandMatrix {
BandMatrix: double[][] m; //Matrix
BandMatrix: double[] d; //Temporary storage for diagonal
BandMatrix: double det;
BandMatrix: int diagos, lines, n;
BandMatrix: boolean isDecomposed = false;
BandMatrix: int l=0; //Band indices (left, center, right)
BandMatrix: int c=1;
BandMatrix: int r=2;
BandMatrix:
BandMatrix: /** Constructor */
BandMatrix: public BandMatrix(int diagos, int lines) {
BandMatrix: m = new double[diagos][lines];
BandMatrix: this.diagos =diagos;
BandMatrix: this.lines =lines;
BandMatrix: this.n =lines-1;
BandMatrix: }
BandMatrix:
BandMatrix: /** Store matrix elements */
BandMatrix: public void set(int i, int j, double v) { m[j][i]=v; }
BandMatrix: public void setL(int i, double v) { m[l][i]=v; }
BandMatrix: public void setD(int i, double v) { m[c][i]=v; }
BandMatrix: public void setR(int i, double v) { m[r][i]=v; }
BandMatrix:
BandMatrix: /** Retrieve value of matrix elements */
BandMatrix: public double get(int j, int i) { return m[j][i]; }
BandMatrix: public double getL(int i) { return m[l][i]; }
BandMatrix: public double getD(int i) { return m[c][i]; }
BandMatrix: public double getR(int i) { return m[r][i]; }
BandMatrix:
BandMatrix: /** Matrix times vector */
BandMatrix: public double[] dot(double[] v) {
BandMatrix: double[] res = new double[lines];
BandMatrix: int hw=(diagos-1)/2;
BandMatrix: for (int i=0; i<=n; i++) {
BandMatrix: for (int j=Math.max(0,hw-i); j<=Math.min(2,hw+n-i); j++) {
BandMatrix: res[i]=res[i]+m[j][i]*v[i+j-1];
BandMatrix: }
BandMatrix: }
BandMatrix: return res;
BandMatrix: }
BandMatrix:
BandMatrix: /** Direct LU solver for 3-banded matrix with multiple RHS and BC
BandMatrix: The matrix is decomposed once only for the first rhs vector
BandMatrix: Periodic boundary conditions are taken care of by the upper-left
BandMatrix: lower-right most matrix elements
BandMatrix: @param rhs Right hand side vector
BandMatrix: @return Solution of the linear system
BandMatrix: ****************************************************************************/
BandMatrix: public double[] solve3(double[] rhs) {
BandMatrix: double[] sol = new double[lines];
BandMatrix: int i;
BandMatrix:
BandMatrix: if (!isDecomposed) { //Forward substitution of matrix
BandMatrix: d = new double[lines];
BandMatrix: d[0]= m[c][0];
BandMatrix: m[r][0]= m[r][0]/d[0];
BandMatrix: m[l][0]=-m[l][0]/d[0];
BandMatrix: for (i=1; i<n; i++) {
BandMatrix: d[i] = m[c][i]-m[l][i]*m[r][i-1];
BandMatrix: m[r][i]= m[r][i]/d[i];
BandMatrix: m[c][i]=-m[l][i]/d[i];
BandMatrix: m[l][i]=-m[l][i]/d[i]*m[l][i-1];
BandMatrix: }
BandMatrix: d[n]=m[c][n]+m[l][n]*(m[l][n-1]-m[r][n-1]);
BandMatrix: m[r][n]= m[r][n]/d[n];
BandMatrix: m[c][n]=-m[l][n]/d[n];
BandMatrix:
BandMatrix: m[l][n-1]=m[l][n-1]-m[r][n-1]; //Backward substitution of matrix
BandMatrix: for (i=n-2; i>=0; i--) {
BandMatrix: m[l][i]= m[l][i]-m[r][i]*m[l][i+1];
BandMatrix: }
BandMatrix: det = 1.0 + m[r][n]*m[l][0];
BandMatrix: isDecomposed=true;
BandMatrix: }
BandMatrix:
BandMatrix: rhs[0]=rhs[0]/d[0];
BandMatrix: for (i=1; i<=n; i++) { //Forward substitution of rhs
BandMatrix: rhs[i]=rhs[i]/d[i] +m[c][i]*rhs[i-1];
BandMatrix: }
BandMatrix: for (i=n-2; i>=0; i--) { //Backward substitution of rhs
BandMatrix: rhs[i]=rhs[i] -m[r][i]*rhs[i+1];
BandMatrix: }
BandMatrix:
BandMatrix: sol[0]=(rhs[0]+m[l][0]*rhs[n])/det; //Built-in periodicity
BandMatrix: sol[n]=(rhs[n]-m[r][n]*rhs[0])/det;
BandMatrix: for (i=1;i<n;i++) {
BandMatrix: sol[i]=rhs[i]+m[l][i]*sol[n];
BandMatrix: }
BandMatrix: return sol;
BandMatrix: }
BandMatrix:
BandMatrix:
BandMatrix: /** Projected Symmetric Over Relaxation for 3-banded matrix
BandMatrix: Periodic boundary conditions are taken care of by the upper-left
BandMatrix: lower-right most matrix elements
BandMatrix: @param rhs Right hand side vector
BandMatrix: @param ini Initial iterate
BandMatrix: @param min Lower limit for obstacle problems
BandMatrix: @param max Upper limit for obstacle problems
BandMatrix: @param precision Relative precision required
BandMatrix: @param w Relaxation parameter to be chosen within [0;2]
BandMatrix: @param maxIterations Maximum number of iterations
BandMatrix: @return Solution of the linear system
BandMatrix: ****************************************************************************/
BandMatrix: public double[] ssor3(double[] rhs,double[] ini,double[] min,double[] max,
BandMatrix: double precision,double w,int maxIterations) {
BandMatrix: double[] hlf = new double[lines]; //Half-step
BandMatrix: double[] sol = new double[lines]; //Solution
BandMatrix: boolean converged = false;
BandMatrix: int iterations = 0;
BandMatrix: int i;
BandMatrix: while (!converged && iterations<maxIterations){
BandMatrix:
BandMatrix: //Gauss Seidel, forward one half-step
BandMatrix: hlf[0]=Math.max(min[0],Math.min(max[0],
BandMatrix: ( w *(rhs[0]-m[r][0]*ini[1]-m[l][0]*hlf[n])+
BandMatrix: (1-w)*m[c][0]*ini[0])/m[c][0] ));
BandMatrix: for(i=1;i<=n-1;i++)
BandMatrix: hlf[i]=Math.max(min[i],Math.min(max[i],
BandMatrix: ( w *(rhs[i]-m[r][i]*ini[i+1]-m[l][i]*hlf[i-1])+
BandMatrix: (1-w)*m[c][i]*ini[i])/m[c][i] ));
BandMatrix: hlf[n]=Math.max(min[n],Math.min(max[n],
BandMatrix: ( w *(rhs[n]-m[r][n]*ini[0]-m[l][n]*hlf[n-1])+
BandMatrix: (1-w)*m[c][n]*ini[n])/m[c][n] ));
BandMatrix:
BandMatrix: //Gauss Seidel, backward one half-step
BandMatrix: sol[n]=Math.max(min[n],Math.min(max[n],
BandMatrix: ( w *(rhs[n]-m[l][n]*hlf[n-1]-m[r][n]*sol[0])+
BandMatrix: (1-w)*m[c][n]*hlf[n])/m[c][n] ));
BandMatrix: for(i=n-1;i>=1;i--)
BandMatrix: sol[i]=Math.max(min[i],Math.min(max[i],
BandMatrix: ( w *(rhs[i]-m[l][i]*hlf[i-1]-m[r][i]*sol[i+1])+
BandMatrix: (1-w)*m[c][i]*hlf[i])/m[c][i] ));
BandMatrix: sol[0]=Math.max(min[0],Math.min(max[0],
BandMatrix: ( w *(rhs[0]-m[l][0]*hlf[n]-m[r][0]*sol[1])+
BandMatrix: (1-w)*m[c][0]*hlf[0])/m[c][0] ));
BandMatrix:
BandMatrix: converged=isEqual(sol,ini,precision);
BandMatrix: iterations++;
BandMatrix:
BandMatrix: //Diagnostic
BandMatrix: if (false && (iterations<30 || converged) ) {
BandMatrix: double err=0.;
BandMatrix: for (i=0;i<=n;i++) {
BandMatrix: err=Math.max(err,Math.abs(sol[i]-ini[i]));
BandMatrix: }
BandMatrix: System.out.println("PSSOR iteration "+iterations+", max(err)="+err);
BandMatrix: }
BandMatrix: for (i=0;i<=n;i++) {ini[i]=sol[i];}
BandMatrix: }
BandMatrix: return sol;
BandMatrix:
BandMatrix: }//ssor3
BandMatrix:
BandMatrix:
BandMatrix: /** Projected Symmetric Over Relaxation for 3-banded matrix
BandMatrix: Periodic boundary conditions are taken care of by the upper-left
BandMatrix: lower-right most matrix elements
BandMatrix: @param rhs Right hand side vector
BandMatrix: @param ini Initial iterate
BandMatrix: @return Solution of the linear system
BandMatrix: ****************************************************************************/
BandMatrix: public double[] ssor3(double[] rhs,double[] ini) {
BandMatrix: double precision = Math.pow(10.,-5); //Default SSOR parameters
BandMatrix: int maxIterations= 1000;
BandMatrix: double w = 1.2;
BandMatrix: double[] min = new double[n+1]; //No projection limits
BandMatrix: double[] max = new double[n+1];
BandMatrix: for (int i=0; i<=n; i++) {
BandMatrix: min[i]=Double.NEGATIVE_INFINITY;
BandMatrix: max[i]=Double.POSITIVE_INFINITY;
BandMatrix: }
BandMatrix: return ssor3(rhs, ini, min, max, precision, w, maxIterations);
BandMatrix: }
BandMatrix:
BandMatrix:
BandMatrix:
BandMatrix: /** Decide whether two vectors are equal to a certain degree of precision
BandMatrix: @param sol First vector
BandMatrix: @param ini Second vector
BandMatrix: @param precision Absolute precision
BandMatrix: @return true is both vectors are equal
BandMatrix: ****************************************************************************/
BandMatrix: public boolean isEqual(double[] sol, double[] ini, double precision) {
BandMatrix: test: for (int k=0 ; k<=n ; k++){
BandMatrix: if (Math.abs(sol[k]-ini[k]) >= precision )
BandMatrix: { return false; } else { continue test; }
BandMatrix: }
BandMatrix: return true;
BandMatrix: }//isEqual
BandMatrix:
BandMatrix: } //End of BandMatrix
FDSolution: /* $Id: FDSolution.java,v 1.14 2002/08/19 06:43:30 pde Exp $ */
FDSolution:
FDSolution: /******************************************************************************
FDSolution: * FDSolution -- contains the finite difference solver.
FDSolution: * @see FluidSolution
FDSolution: * @see Solution
FDSolution: ******************************************************************************/
FDSolution: public class FDSolution extends FluidSolution{
FDSolution:
FDSolution: /** Creates a FDSolution object.
FDSolution: @param runData The run time parameters
FDSolution: */
FDSolution: public FDSolution(RunData runData){
FDSolution: super(runData);
FDSolution: } // FDSolution
FDSolution:
FDSolution: /** Advance the solution forward one step in time.
FDSolution: The equation is set by the internal variable topic and
FDSolution: the numerical scheme by the internal variable scheme
FDSolution: @param runData List of run parameters
FDSolution: @see RunData
FDSolution: @return True if a scheme is implemented for that equation
FDSolution: ****************************************************************************/
FDSolution: public boolean next(RunData runData) {
FDSolution: int n=f.length-1;
FDSolution: boolean isDefined=true;
FDSolution: boolean isCall = ic.equals(vmarket.CALL);
FDSolution: boolean isPut = ic.equals(vmarket.PUT);
FDSolution:
FDSolution: for (int j=0; j<=n; j++) { gp[j]=g[j]; }
FDSolution:
FDSolution: if( topic.equals(vmarket.STKOPTION) &&
FDSolution: scheme.equals(vmarket.EUSTY)){
FDSolution: //=======================================================================
FDSolution: // FD - Black-Scholes - European Vanilla Put option - not normalized
FDSolution: //=======================================================================
FDSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
FDSolution: double strike = runData.getParamValue(runData.strikePriceNm);
FDSolution: double rate = runData.getParamValue(runData.spotRateNm);
FDSolution: double sigma = runData.getParamValue(runData.volatilityNm);
FDSolution: double sigmaSq = sigma*sigma;
FDSolution:
FDSolution: for (int j=1; j<n; j++) { //Explicit 2 levels
FDSolution: fp[j]=f[j+1]* 0.5*timeStep*(sigmaSq*j*j + rate*j)
FDSolution: +f[j ]*(1.0-timeStep*(sigmaSq*j*j + rate ))
FDSolution: +f[j-1]* 0.5*timeStep*(sigmaSq*j*j - rate*j);
FDSolution: }
FDSolution: if (isCall) { //Boundary condition
FDSolution: fp[0]=0;
FDSolution: fp[n]=n*dx[0] -strike*Math.exp(-rate*time);
FDSolution: } else if(isPut) {
FDSolution: fp[0]=strike*Math.exp(-rate*time);
FDSolution: fp[n]=fp[n-1];
FDSolution: } else {
FDSolution: fp[0]=fp[1];
FDSolution: fp[n]=fp[n-1];
FDSolution: }
FDSolution:
FDSolution: } else if(topic.equals(vmarket.STKOPTION)
FDSolution: && scheme.equals(vmarket.EUNORM)){
FDSolution: //=======================================================================
FDSolution: // FD - Black-Scholes - European Vanilla Put option - normalized
FDSolution: //=======================================================================
FDSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
FDSolution: double strike = runData.getParamValue(runData.strikePriceNm);
FDSolution: double rate = runData.getParamValue(runData.spotRateNm);
FDSolution: double divid = runData.getParamValue(runData.dividendNm);
FDSolution: double sigma = runData.getParamValue(runData.volatilityNm);
FDSolution: double sigmaSq = sigma*sigma;
FDSolution: int j,k;
FDSolution: double x0, x1, f0, f1, xk; //Change variables
FDSolution: double tau = 0.5*sigmaSq*time; // f(x,t) ->
FDSolution: double dtau= 0.5*sigmaSq*timeStep; // fm(xk,tau)
FDSolution: double xk0 = Math.log(x[1]/strike); // lognormal mesh
FDSolution: double xkn = Math.log(x[n]/strike);
FDSolution: double dxk =(xkn-xk0)/(n-1);
FDSolution: double k1 = 2*rate/sigmaSq;
FDSolution: double k2 = 2*(rate-divid)/sigmaSq;
FDSolution: double k2m1= k2-1.;
FDSolution: double k2p1= k2+1.;
FDSolution:
FDSolution: //=== Interpolate only once from (x,t) to lognormal variables (xk,tau)
FDSolution: if (time<=timeStep) {
FDSolution: if(isPut) { //Initialize fm[] directly as put-option
FDSolution: for (k=1; k<=n; k++) {
FDSolution: xk=xk0+(k-1)*dxk;
FDSolution: fm[k]=Math.max(0., Math.exp(0.5*k2m1*xk) -
FDSolution: Math.exp(0.5*k2p1*xk) );
FDSolution: }
FDSolution: } else if (isCall) { //Left as an exercise
FDSolution: } else { //Interpolate fm[] from IC in f[]
FDSolution: j=1; ; x0=xk0;
FDSolution: f0=f[1]/strike*Math.exp(0.5*k2m1*xk0);
FDSolution: x1=x0; f1=f0;
FDSolution: for (k=1; k<n; k++) { //Loop over lognormal mesh index
FDSolution: xk=xk0+(k-1)*dxk; // given xk, find x0,x1 | x[j] < xk < x[j+1]
FDSolution: while (xk>=x1) { j++; x0=x1; f0=f1; x1=Math.log(x[j]/strike); }
FDSolution: f1=f[j]/strike*Math.exp(0.5*k2m1*x1);
FDSolution: fm[k]= f0 + (xk-x0)*(f1-f0)/(x1-x0);
FDSolution: }
FDSolution: fm[n]= fm[n-1] + dxk*(fm[n-1]-fm[n-2]);
FDSolution: }
FDSolution: } else { //Retrieve fm[] from previous time step
FDSolution: }
FDSolution:
FDSolution: //===== Solve diffusion equation with an explicit 2 levels scheme
FDSolution: double D = dtau/(dxk*dxk);
FDSolution: for (j=2; j<n; j++)
FDSolution: f[j]= fm[j] + D*(fm[j+1]-2.*fm[j]+fm[j-1]);
FDSolution: if (isPut) {
FDSolution: f[1]= Math.exp(0.5*k2m1*xk0+0.25*k2m1*k2m1*tau);
FDSolution: f[n]= f[n-1];
FDSolution: fp[0]=strike*Math.exp(-rate*time);
FDSolution: // } else if (isCall) { //Left as an exercise
FDSolution: } else {
FDSolution: f[1]= f[2];
FDSolution: f[n]= f[n-1];
FDSolution: fp[0]=fp[1];
FDSolution: }
FDSolution:
FDSolution: //===== Interpolate rest from lognormal to financial mesh variables
FDSolution: k=1; x0=x[0]; x1=x0; f0=fp[0];
FDSolution: xk=xk0; f1=f[1]*strike*Math.exp(-0.5*k2m1*xk-(0.25*k2m1*k2m1+k1)*tau);
FDSolution: for (j=1; j<n; j++) { //Loop over financial mesh index
FDSolution: while (x[j]>=x1){
FDSolution: k++;x0=x1;f0=f1;xk=xk0+(k-1)*dxk;x1=strike*Math.exp(xk);}
FDSolution: f1=f[k]*strike*Math.exp(-0.5*k2m1*xk-(0.25*k2m1*k2m1+k1)*tau);
FDSolution: fp[j]= f0 +(x[j]-x0)/(x1-x0)*(f1-f0); //Lin interpol in x
FDSolution: // double gg=-0.5*k2m1;double dx=xk-Math.log(x[j]/strike);//Expand exp()
FDSolution: // gp[j]= f0*(1.+gg*dx +0.5*gg*gg*dx*dx); // is worse;
FDSolution: }
FDSolution: if (isPut) {
FDSolution: fp[n]=f[n]*strike*Math.exp(-0.5*k2m1*xkn-(0.25*k2m1*k2m1+k1)*tau);
FDSolution: } else if (isCall) { //Left as an exercise
FDSolution: for (j=0; j<=n; j++) fp[j]=0;
FDSolution: } else {
FDSolution: fp[0]=fp[1];
FDSolution: fp[n]=fp[n-1];
FDSolution: }
FDSolution:
FDSolution: } else if(topic.equals(vmarket.EXERCISE)
FDSolution: && scheme.equals(vmarket.EXC4_07)){
FDSolution: //=======================================================================
FDSolution: // FD - Exercise 4.07
FDSolution: //=======================================================================
FDSolution: //INCLUDE_sol4.07.java_INCLUDE//
FDSolution:
FDSolution: } else if(topic.equals(vmarket.EXERCISE)
FDSolution: && scheme.equals(vmarket.EXC4_08)){
FDSolution: //=======================================================================
FDSolution: // FD - Exercise 4.08
FDSolution: //=======================================================================
FDSolution: //INCLUDE_sol4.08.java_INCLUDE//
FDSolution:
FDSolution: } else if(topic.equals(vmarket.EXERCISE)
FDSolution: && scheme.equals(vmarket.EXCB_01)){
FDSolution: //=======================================================================
FDSolution: // FD - Exercise B.01
FDSolution: //=======================================================================
FDSolution: //INCLUDE_solB.01.java_INCLUDE//
FDSolution:
FDSolution: } // if
FDSolution:
FDSolution: if(isDefined && isForward)
FDSolution: shiftLevels();
FDSolution: return isDefined;
FDSolution: } // next
FDSolution:
FDSolution:
FDSolution: /** Take the solution backward one step to initialize schemes
FDSolution: with 3 time levels.
FDSolution: The equation is set by the internal variable topic and
FDSolution: the numerical scheme by the internal variable scheme
FDSolution: @param runData List of run parameters
FDSolution: @see RunData
FDSolution: @return True if an initialisation scheme is implemented for that equation
FDSolution: ****************************************************************************/
FDSolution: public boolean previous(RunData runData){
FDSolution: boolean isDefined=false;
FDSolution: return isDefined;
FDSolution: } // previous
FDSolution:
FDSolution: /** Tells whether the solution implements a option
FDSolution: @param option The the option to implement
FDSolution: @return True if the option is implemented
FDSolution: @see vmarket#topicNames
FDSolution: @see vmarket#schemeNames
FDSolution: */
FDSolution: public boolean hasOption(String option){
FDSolution: try {
FDSolution: if(option.equals(vmarket.STKOPTION))
FDSolution: return true;
FDSolution: else if (option.equals(vmarket.EXERCISE))
FDSolution: return true;
FDSolution: else if (topic.equals(vmarket.STKOPTION) && option.equals(vmarket.EUSTY))
FDSolution: return true;
FDSolution: else if (topic.equals(vmarket.STKOPTION) && option.equals(vmarket.EUNORM))
FDSolution: return true;
FDSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_07))
FDSolution: return true;
FDSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_08))
FDSolution: return true;
FDSolution: return false;
FDSolution: } catch (NullPointerException e){
FDSolution: return false;
FDSolution: } // try
FDSolution: } // hasOption
FDSolution:
FDSolution: } // class FDSolution
FEMSolution: /* $Id: FEMSolution.java,v 1.12 2002/08/19 06:43:31 pde Exp $ */
FEMSolution:
FEMSolution: /******************************************************************************
FEMSolution: * FEMSolution -- contains the finite elements solver.
FEMSolution: * @see FluidSolution
FEMSolution: * @see Solution
FEMSolution: ******************************************************************************/
FEMSolution: public class FEMSolution extends FluidSolution{
FEMSolution:
FEMSolution: /** Creates a FEMSolution object.
FEMSolution: @param runData The run time parameters
FEMSolution: */
FEMSolution: public FEMSolution(RunData runData){
FEMSolution: super(runData);
FEMSolution: } // FEMSolution
FEMSolution:
FEMSolution: /** Advance the solution forward one step in time.
FEMSolution: The equation is set by the internal variable topic and
FEMSolution: the numerical scheme by the internal variable scheme
FEMSolution: @param runData List of run parameters
FEMSolution: @see RunData
FEMSolution: @return True if a scheme is implemented for that equation
FEMSolution: ****************************************************************************/
FEMSolution: public boolean next(RunData runData) {
FEMSolution: int n=f.length-1;
FEMSolution: boolean isDefined=true;
FEMSolution: boolean isCall = ic.equals(vmarket.CALL);
FEMSolution: boolean isPut = ic.equals(vmarket.PUT);
FEMSolution:
FEMSolution: for (int j=0; j<=n; j++) { gp[j]=g[j]; }
FEMSolution:
FEMSolution: if(topic.equals(vmarket.STKOPTION) &&
FEMSolution: (scheme.equals(vmarket.EUSTY)||
FEMSolution: scheme.equals(vmarket.AMSTY) )){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Black-Scholes - American Vanilla Option - not normalized
FEMSolution: //=======================================================================
FEMSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
FEMSolution: double strike = runData.getParamValue(runData.strikePriceNm);
FEMSolution: double rate = runData.getParamValue(runData.spotRateNm);
FEMSolution: double divid = runData.getParamValue(runData.dividendNm);
FEMSolution: double sigma = runData.getParamValue(runData.volatilityNm);
FEMSolution: double theta = runData.getParamValue(runData.timeThetaNm);
FEMSolution: double tune = runData.getParamValue(runData.tuneQuadNm);
FEMSolution: double sigmaSq = sigma*sigma;
FEMSolution:
FEMSolution: double alp = timeStep*sigmaSq/2.; //--- PDE COEFFICIENTS
FEMSolution: double bet =-timeStep*(rate-divid-sigmaSq);
FEMSolution: double gam = timeStep*rate;
FEMSolution: //--- CONSTRUCT MATRICES
FEMSolution: BandMatrix a = new BandMatrix(3, f.length); // Linear problem
FEMSolution: BandMatrix b = new BandMatrix(3, f.length); // a*fp=b*f=c
FEMSolution: double[] c = new double[f.length];
FEMSolution: // Quadrature coeff
FEMSolution: double h,h0,h0o; // independent of j
FEMSolution: double t0m,t0,t0p,t1m,t1,t1p,t2m,t2,t2p; // depending on j
FEMSolution: h= dx[0];
FEMSolution: h0o= h*(1-tune)/4; h0= h*0.5*(1+tune);
FEMSolution: for (int i=0; i<=n; i++) {
FEMSolution: t1m=h*0.25*( -2*i-tune+1); t1=h*0.5*(tune-1);
FEMSolution: t1p=h*0.25*( 2*i-tune+1);
FEMSolution: t2m=h*0.25*(-4*i*i+4*i-tune-1); t2=h*0.5*(4*i*i+tune+1);
FEMSolution: t2p=h*0.25*(-4*i*i-4*i-tune-1);
FEMSolution: a.setL(i,h0o*(1.+gam* theta) +(t1m*bet +t2m*alp)* theta );
FEMSolution: a.setD(i,h0 *(1.+gam* theta) +(t1 *bet +t2 *alp)* theta );
FEMSolution: a.setR(i,h0o*(1.+gam* theta) +(t1p*bet +t2p*alp)* theta );
FEMSolution: b.setL(i,h0o*(1.+gam*(theta-1)) +(t1m*bet +t2m*alp)*(theta-1));
FEMSolution: b.setD(i,h0 *(1.+gam*(theta-1)) +(t1 *bet +t2 *alp)*(theta-1));
FEMSolution: b.setR(i,h0o*(1.+gam*(theta-1)) +(t1p*bet +t2p*alp)*(theta-1));
FEMSolution: }
FEMSolution: c=b.dot(f);
FEMSolution: //--- BC
FEMSolution: a.setL(0, 0.);a.setD(0,1.);a.setR(0,-1.);c[0]=0.;// default:Neuman
FEMSolution: a.setL(n,-1.);a.setD(n,1.);a.setR(n, 0.);c[n]=0.;
FEMSolution:
FEMSolution: if (ic.equals(vmarket.PUT)) { // Vanilla Put:
FEMSolution: a.setR(0,0.); // In-money: Dirichlet
FEMSolution: c[0]=strike*Math.exp(-rate*time);
FEMSolution: } else if (ic.equals(vmarket.CALL)) { // Vanilla Call
FEMSolution: a.setL(n,0.); // Out-money:Dirichlet
FEMSolution: c[n]=n*dx[0]*Math.exp(-divid*time)
FEMSolution: -strike*Math.exp( -rate*time);
FEMSolution: }
FEMSolution: //--- SOLVE
FEMSolution: if (scheme.equals(vmarket.EUSTY)) { // European option
FEMSolution: fp=a.ssor3(c,f);
FEMSolution: } else if (scheme.equals(vmarket.AMSTY)) { // American option
FEMSolution: double[] min = new double[f.length];
FEMSolution: double[] max = new double[f.length];
FEMSolution: for (int i=0; i<=n; i++) {
FEMSolution: min[i]=f0[i]; // constraints
FEMSolution: max[i]=Double.POSITIVE_INFINITY;
FEMSolution: }
FEMSolution: double precision = strike*Math.pow(10.,-6); // relative to strike
FEMSolution: int maxIter = 30;
FEMSolution: double w = 1.2; // relaxation parameter
FEMSolution: fp=a.ssor3(c,f,min,max,precision,w,maxIter); // projected-SSOR
FEMSolution: }
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.STKOPTION) &&
FEMSolution: (scheme.equals(vmarket.EUNORM)||
FEMSolution: scheme.equals(vmarket.AMNORM) )){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Black-Scholes - American Vanilla Option - normalized
FEMSolution: //=======================================================================
FEMSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
FEMSolution: double strike = runData.getParamValue(runData.strikePriceNm);
FEMSolution: double rate = runData.getParamValue(runData.spotRateNm);
FEMSolution: double divid = runData.getParamValue(runData.dividendNm);
FEMSolution: double sigma = runData.getParamValue(runData.volatilityNm);
FEMSolution: double theta = runData.getParamValue(runData.timeThetaNm);
FEMSolution: double tune = runData.getParamValue(runData.tuneQuadNm);
FEMSolution: double sigmaSq = sigma*sigma;
FEMSolution: int j,k;
FEMSolution: double x0, x1, y0, y1, xk; //--- CHANGE VARIABLES
FEMSolution: double tau = 0.5*sigmaSq*time; // f(x,t) ->
FEMSolution: double dtau= 0.5*sigmaSq*timeStep; // fm(xk,tau)
FEMSolution: double xk0 = Math.log(x[1]/strike); // lognormal mesh
FEMSolution: double xkn = Math.log(x[n]/strike);
FEMSolution: double dxk =(xkn-xk0)/(n-1);
FEMSolution: double k1 = 2*rate/sigmaSq;
FEMSolution: double k2 = 2*(rate-divid)/sigmaSq;
FEMSolution: double k2m1= k2-1.;
FEMSolution: double k2p1= k2+1.;
FEMSolution:
FEMSolution: //=== Interpolate only once from (x,t) to lognormal variables (xk,tau)
FEMSolution: if (time<=timeStep) {
FEMSolution: if(ic.equals(vmarket.PUT)) { //Initialize fm[] as put option
FEMSolution: for (k=1; k<=n; k++) {
FEMSolution: xk=xk0+(k-1)*dxk;
FEMSolution: fm[k]=Math.max(0., Math.exp(0.5*k2m1*xk) -
FEMSolution: Math.exp(0.5*k2p1*xk) );
FEMSolution: }
FEMSolution: } else if (ic.equals(vmarket.CALL)) { //Left as an exercise
FEMSolution: } else { //Interpolate fm[] from IC in f[]
FEMSolution: j=1; ; x0=xk0;
FEMSolution: y0=f[1]/strike*Math.exp(0.5*k2m1*xk0);
FEMSolution: x1=x0; y1=y0;
FEMSolution: for (k=1; k<n; k++) { //Loop over lognormal mesh index
FEMSolution: xk=xk0+(k-1)*dxk; // given xk, find x0,x1 | x[j] < xk < x[j+1]
FEMSolution: while (xk>=x1) { j++; x0=x1; y0=y1; x1=Math.log(x[j]/strike); }
FEMSolution: y1=f[j]/strike*Math.exp(0.5*k2m1*x1);
FEMSolution: fm[k]= y0 + (xk-x0)*(y1-y0)/(x1-x0);
FEMSolution: }
FEMSolution: fm[n]= fm[n-1] + dxk*(fm[n-1]-fm[n-2]);
FEMSolution: }
FEMSolution: } else { //Retrieve fm[] from previous time step
FEMSolution: }
FEMSolution:
FEMSolution: //===== Solve diffusion equation with tunable finite elements
FEMSolution: //--- CONSTRUCT MATRICES
FEMSolution: BandMatrix a = new BandMatrix(3, f.length); // Linear problem
FEMSolution: BandMatrix b = new BandMatrix(3, f.length); // a*fp=b*f=c
FEMSolution: double[] c = new double[f.length];
FEMSolution: double htm = dxk*(1-tune)/4; // Quadrature coeff
FEMSolution: double htp = dxk*(1+tune)/4;
FEMSolution: double halpha = dtau/dxk; // PDE coefficient
FEMSolution: for (int i=0; i<=n; i++) {
FEMSolution: a.setL(i, htm -halpha* theta );
FEMSolution: a.setD(i,2*(htp +halpha* theta ));
FEMSolution: a.setR(i, htm -halpha* theta );
FEMSolution: b.setL(i, htm -halpha*(theta-1) );
FEMSolution: b.setD(i,2*(htp +halpha*(theta-1)));
FEMSolution: b.setR(i, htm -halpha*(theta-1) );
FEMSolution: }
FEMSolution: c=b.dot(fm);
FEMSolution: a.setL(0,0.);a.setD(0,1.);a.setR(0,0.);c[0]=0; // First equation idle
FEMSolution:
FEMSolution: //--- BC + SOLVE
FEMSolution: if (scheme.equals(vmarket.EUNORM)) { // European option
FEMSolution: a.setL(1, 0.);a.setD(1,1.);a.setR(1,0.); // in-money: Dirichlet
FEMSolution: c[1]=Math.exp(0.5*k2m1*xk0+0.25*k2m1*k2m1*tau);
FEMSolution: a.setL(n,-1.);a.setD(n,1.);a.setR(n,0.);c[n]=0.; // out-money: Neuman
FEMSolution: f=a.ssor3(c,fm);
FEMSolution: y0=strike*Math.exp(-rate*time);
FEMSolution: } else if (scheme.equals(vmarket.AMNORM)) { // American option
FEMSolution: double[] min = new double[f.length]; // Obstacle
FEMSolution: double[] max = new double[f.length];
FEMSolution: for (int i=0; i<=n; i++) {
FEMSolution: xk=xk0+(i-1)*dxk;
FEMSolution: min[i]=Math.exp((0.25*k2m1*k2m1 +k1)*tau) *
FEMSolution: Math.max(0., Math.exp(0.5*k2m1*xk) -
FEMSolution: Math.exp(0.5*k2p1*xk) );
FEMSolution: max[i]=Double.POSITIVE_INFINITY;
FEMSolution: fm[i]=Math.max(min[i],f[i]); // IC interp error
FEMSolution: }
FEMSolution: a.setL(1, 0.);a.setD(1,1.);a.setR(1,0.); // In-money: Dirichlet
FEMSolution: c[1]=Math.max(min[1],Math.exp(0.5*k2m1*xk0+0.25*k2m1*k2m1*tau));
FEMSolution: a.setL(n,-1.);a.setD(n,1.);a.setR(n,0.);c[n]=0.; //out-money: Neuman
FEMSolution: double precision = strike*Math.pow(10.,-6); // relativ.to strike
FEMSolution: int maxIter = 30;
FEMSolution: double w = 1.2; // relaxation parameter
FEMSolution: f=a.ssor3(c,fm,min,max,precision,w,maxIter); // projected-SSOR
FEMSolution: fp[0]=strike;
FEMSolution: }
FEMSolution:
FEMSolution: //===== Interpolate rest from lognormal to financial mesh variables
FEMSolution: k=1; x0=x[0]; x1=x0; y0=fp[0];
FEMSolution: xk=xk0; y1=f[1]*strike*Math.exp(-0.5*k2m1*xk-(0.25*k2m1*k2m1+k1)*tau);
FEMSolution: for (j=1; j<n; j++) { //Loop over financial mesh index
FEMSolution: while (x[j]>=x1){
FEMSolution: k++;x0=x1;y0=y1;xk=xk0+(k-1)*dxk;x1=strike*Math.exp(xk);}
FEMSolution: y1=f[k]*strike*Math.exp(-0.5*k2m1*xk-(0.25*k2m1*k2m1+k1)*tau);
FEMSolution: fp[j]= y0 +(x[j]-x0)/(x1-x0)*(y1-y0); //Lin interpol in x
FEMSolution: }
FEMSolution: if (ic.equals(vmarket.PUT)) {
FEMSolution: fp[0]=strike*Math.exp(-rate*time);
FEMSolution: fp[n]=f[n]*strike*Math.exp(-0.5*k2m1*xkn-(0.25*k2m1*k2m1+k1)*tau);
FEMSolution: } else if (ic.equals(vmarket.CALL)) { //Left as an exercise
FEMSolution: for (j=0; j<=n; j++) fp[j]=0;
FEMSolution: } else {
FEMSolution: fp[0]=fp[1];
FEMSolution: fp[n]=fp[n-1];
FEMSolution: }
FEMSolution:
FEMSolution: } else if(scheme.equals(vmarket.VASICEK) ){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Vasicek models (bonds, swaps and cap-/ floorlets)
FEMSolution: //=======================================================================
FEMSolution: double twopi = 8.*Math.atan(1.);
FEMSolution: double runTime = runData.getParamValue(runData.runTimeNm);
FEMSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
FEMSolution: double X = runData.getParamValue(runData.strikePriceNm);
FEMSolution: double sigma = runData.getParamValue(runData.volatilityNm);
FEMSolution: double theta = runData.getParamValue(runData.timeThetaNm);
FEMSolution: double tune = runData.getParamValue(runData.tuneQuadNm);
FEMSolution: double lambda = runData.getParamValue(runData.mktPriceRskNm);
FEMSolution: //--- TERM STRUCTURE
FEMSolution: double t = 1.-time/runTime; // normalized time
FEMSolution: double hump = 1.7*(t-t*t*t*t*t*t); // volatility shaping
FEMSolution: double ca = runData.getParamValue(runData.meanRevVeloNm);
FEMSolution: double cb = runData.getParamValue(runData.meanRevTargNm);
FEMSolution: double cycles = runData.getParamValue(runData.userDoubleNm);
FEMSolution: double cd = ca*cb-lambda*sigma*Math.cos(twopi*cycles*t);
FEMSolution: double ce = sigma*hump; ce=ce*ce;
FEMSolution: //--- CONSTRUCT MATRICES
FEMSolution: BandMatrix a = new BandMatrix(3, f.length); // Linear problem
FEMSolution: BandMatrix b = new BandMatrix(3, f.length); // a*fp=b*f=c
FEMSolution: double[] c = new double[f.length];
FEMSolution: // Quadrature coeff
FEMSolution: double h,h0,h0o,h1,h1m,h1p,h2,h2o; // independent of i
FEMSolution: double t0,t0m,t0p,t1,t1m,t1p; // depending on i
FEMSolution: h= dx[0];
FEMSolution: h0o= 0.25*h*(1-tune); h0= 0.5*h*(1+tune);
FEMSolution: h1m=-0.5; h1p=-h1m; h1= 0.;
FEMSolution: h2o=-1./h; h2= 2./h;
FEMSolution: for (int i=0; i<=n; i++) {
FEMSolution: t0m=h*h*0.125*(1-tune)*(2*i-1);
FEMSolution: t0p=h*h*0.125*(1-tune)*(2*i+1); t0=h*h*0.5*i*(tune+1);
FEMSolution: t1m=h*h*0.25*(-2*i-tune+1);
FEMSolution: t1p=h*h*0.25*(-2*i+tune+1); t1=h*h*0.5*(tune-1);
FEMSolution: a.setL(i,h0o + theta *timeStep*(t0m +0.5*ce*h2o +ca*t1m +cd*h1m));
FEMSolution: a.setD(i,h0 + theta *timeStep*(t0 +0.5*ce*h2 +ca*t1 +cd*h1 ));
FEMSolution: a.setR(i,h0o + theta *timeStep*(t0p +0.5*ce*h2o +ca*t1p +cd*h1p));
FEMSolution: b.setL(i,h0o +(theta-1)*timeStep*(t0m +0.5*ce*h2o +ca*t1m +cd*h1m));
FEMSolution: b.setD(i,h0 +(theta-1)*timeStep*(t0 +0.5*ce*h2 +ca*t1 +cd*h1 ));
FEMSolution: b.setR(i,h0o +(theta-1)*timeStep*(t0p +0.5*ce*h2o +ca*t1p +cd*h1p));
FEMSolution: }
FEMSolution: c=b.dot(f);
FEMSolution:
FEMSolution:
FEMSolution: double dPdy0, dPdyn, c0, cn; //--- BC
FEMSolution: double a00= a.getL(1) -3.*a.getR(1); // left: Neuman
FEMSolution: double a01= a.getD(1) +4.*a.getR(1); // O(h^2)
FEMSolution: double a1n= a.getD(n-1) +4.*a.getL(n-1); // right: Neuman
FEMSolution: double ann= a.getR(n-1) -3.*a.getL(n-1); // O(h^2)
FEMSolution:
FEMSolution: if (topic.equals(vmarket.BOND)) { //--- Bond
FEMSolution: a.setL(0, 0.);a.setD(0, 1.);a.setR(0, 0.);c[0]=1.;//left: Dirichlet
FEMSolution: dPdyn=-time*f[n]; cn=c[n-1]-2*dx[0]*a.getL(n-1)*dPdyn;
FEMSolution: a.setL(n,a1n);a.setD(n,ann);a.setR(n, 0.);c[n]=cn;//right:Neuman
FEMSolution:
FEMSolution: } else if (topic.equals(vmarket.SWAP)) { //--- Swap
FEMSolution: for (int i=1; i<n; i++)
FEMSolution: c[i]+= timeStep*h*(i*h-X);
FEMSolution: c0=(f[0]+(x[0]-X)*timeStep)*Math.exp(timeStep*x[0]);
FEMSolution: a.setL(0, 0.);a.setD(0, 1.);a.setR(0, 0.);c[0]=c0;//left: Dirichlet
FEMSolution: dPdyn=(f[n]-f[n-1])/h; cn=c[n-1]-2*dx[0]*a.getL(n-1)*dPdyn;
FEMSolution: a.setL(n,a1n);a.setD(n,ann);a.setR(n, 0.);c[n]=cn;//right:Neuman
FEMSolution:
FEMSolution: } else if (topic.equals(vmarket.BNDOPTION)) {
FEMSolution: if (ic.equals(vmarket.CAPLET)) { //--- Caplet
FEMSolution: for (int i=1; i<n; i++)
FEMSolution: if (i*h<X) c[i]+=0;
FEMSolution: else c[i]+=timeStep*h*(i*h-X);
FEMSolution: a.setL(0, 0.);a.setD(0, 1.);a.setR(0, 0.);c[0]=0.;//left: Dirichlet
FEMSolution: dPdyn=0; cn=c[n-1]-2*dx[0]*a.getL(n-1)*dPdyn;
FEMSolution: a.setL(n,a1n);a.setD(n,ann);a.setR(n, 0.);c[n]=cn;//right:Neuman
FEMSolution:
FEMSolution: } else if (ic.equals(vmarket.FLOORLET)) { //--- Floorlet
FEMSolution: for (int i=1; i<n; i++)
FEMSolution: if (i*h<X) c[i]+=timeStep*h*(X-i*h);
FEMSolution: else c[i]+=0;
FEMSolution: c0=(f[0]+(X-x[0])*timeStep)*Math.exp(timeStep*x[0]);
FEMSolution: a.setL(0, 0.);a.setD(0, 1.);a.setR(0, 0.);c[0]=c0;//left: Dirichlet
FEMSolution: dPdyn=0; cn=c[n-1]-2*dx[0]*a.getL(n-1)*dPdyn;
FEMSolution: a.setL(n,a1n);a.setD(n,ann);a.setR(n, 0.);c[n]=cn;//right:Neuman
FEMSolution: }
FEMSolution: }
FEMSolution:
FEMSolution: fp=a.solve3(c); //--- SOLVE
FEMSolution:
FEMSolution: if (topic.equals(vmarket.BOND)) {
FEMSolution: for (int i=0; i<=n; i++) { //--- PLOT
FEMSolution: gp[i]=-Math.log(fp[i])/time; // yield(r)
FEMSolution: if (time<=timeStep) f0[i]=0.;
FEMSolution: }
FEMSolution: int i=(int)((time/runTime*n)); // yield(t)
FEMSolution: double rate = runData.getParamValue(runData.spotRateNm);
FEMSolution: f0[i]=gp[(int)(n*(rate-x[0])/(x[n]-x[0]))];
FEMSolution: }
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC5_05)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 5.05
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol5.05.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC5_06)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 5.06
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol5.06.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC5_07)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 5.07
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol5.07.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC5_08)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 5.08
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol5.08.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC5_09)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 5.09
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol5.09.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_03)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.03
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.03.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_04)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.04
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.04.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_05)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.05
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.05.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_06)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.06
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.06.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_07)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.07
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.07.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXC6_08)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise 6.08
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_sol6.08.java_INCLUDE//
FEMSolution:
FEMSolution: } else if(topic.equals(vmarket.EXERCISE)
FEMSolution: && scheme.equals(vmarket.EXCC_01)){
FEMSolution: //=======================================================================
FEMSolution: // FEM - Exercise C.01
FEMSolution: //=======================================================================
FEMSolution: //INCLUDE_solC.01.java_INCLUDE//
FEMSolution:
FEMSolution: } // if
FEMSolution:
FEMSolution: if(isDefined)
FEMSolution: shiftLevels();
FEMSolution: return isDefined;
FEMSolution: } // next
FEMSolution:
FEMSolution:
FEMSolution: /** Take the solution backward one step to initialize schemes
FEMSolution: with 3 time levels; not really appropriate in this context.
FEMSolution: @param runData List of run parameters
FEMSolution: @return False since it is not used here
FEMSolution: ****************************************************************************/
FEMSolution: public boolean previous(RunData runData){ return false; }
FEMSolution:
FEMSolution: /** Tells whether the solution implements a option
FEMSolution: @param option The the option to implement
FEMSolution: @return True if the option is implemented
FEMSolution: @see vmarket#topicNames
FEMSolution: @see vmarket#schemeNames
FEMSolution: */
FEMSolution: public boolean hasOption(String option){
FEMSolution: try {
FEMSolution: if(option.equals(vmarket.STKOPTION))
FEMSolution: return true;
FEMSolution: else if(option.equals(vmarket.BOND))
FEMSolution: return true;
FEMSolution: else if(option.equals(vmarket.BNDOPTION))
FEMSolution: return true;
FEMSolution: else if(option.equals(vmarket.SWAP))
FEMSolution: return true;
FEMSolution: else if (option.equals(vmarket.EXERCISE))
FEMSolution: return true;
FEMSolution: else if(topic.equals(vmarket.STKOPTION)
FEMSolution: &&(option.equals(vmarket.EUSTY)||option.equals(vmarket.EUNORM)
FEMSolution: ||option.equals(vmarket.AMSTY)||option.equals(vmarket.AMNORM) ))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.BOND) && option.equals(vmarket.VASICEK))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.SWAP) && option.equals(vmarket.VASICEK))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.BNDOPTION) && option.equals(vmarket.VASICEK))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC5_05))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC5_06))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC5_07))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC5_08))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC5_09))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_03))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_04))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_05))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_06))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_07))
FEMSolution: return true;
FEMSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC6_08))
FEMSolution: return true;
FEMSolution: return false;
FEMSolution: } catch (NullPointerException e){
FEMSolution: return false;
FEMSolution: } // try
FEMSolution: } // hasOption
FEMSolution:
FEMSolution: } // class FEMSolution
FluidSolution: /* $Id: FluidSolution.java,v 1.10 2002/07/24 16:22:55 pde Exp $ */
FluidSolution:
FluidSolution: /*****************************************************************************
FluidSolution: * FluidSolution -- Is an abstract class at the top of all the solvers that
FluidSolution: * that operate directly on the fluid function.
FluidSolution: * @version $Revision: 1.10 $
FluidSolution: * @see Solution
FluidSolution: ******************************************************************************/
FluidSolution: abstract class FluidSolution extends Solution{
FluidSolution:
FluidSolution: /** True if needs to shiftLevels */
FluidSolution: protected boolean isForward = true;
FluidSolution:
FluidSolution: /** Creates a FluidSolution object.
FluidSolution: @param runData The run time parameters
FluidSolution: ****************************************************************************/
FluidSolution: public FluidSolution(RunData runData){
FluidSolution: super(runData);
FluidSolution: } // FluidSolution
FluidSolution:
FluidSolution: /** Discretize the initial Shape function and initialize the moments
FluidSolution: @param function The initial shape to be approximated
FluidSolution: ****************************************************************************/
FluidSolution: public void discretize(ShapeFunction function){
FluidSolution: for (int j = 0; j < mesh.size(); j++){ //Discretizing is very simple
FluidSolution: f[j] = function.getValue(mesh, j);
FluidSolution: f0[j] = f[j];
FluidSolution: g[j] = 0.;
FluidSolution: }
FluidSolution: initialMoments[0]=calculateMoments(0); //Set conserved quantities
FluidSolution: initialMoments[1]=calculateMoments(1);
FluidSolution: rescale(true);
FluidSolution: } // discretize
FluidSolution:
FluidSolution: /** Internal function for copying new -> old
FluidSolution: ****************************************************************************/
FluidSolution: protected void shiftLevels() {
FluidSolution: for (int i=0;i<f.length;i++) {
FluidSolution: fm[i]=f[i]; dfm[i]=df[i]; f[i]=fp[i]; df[i]=dfp[i]; fp[i]=0.; dfp[i]=0.;
FluidSolution: gm[i]=g[i]; dgm[i]=dg[i]; g[i]=gp[i]; dg[i]=dgp[i]; gp[i]=0.; dgp[i]=0.;
FluidSolution: }
FluidSolution: }
FluidSolution:
FluidSolution: } // class FluidSolution
MCPDrawSolution: /* $Id: MCPDrawSolution.java,v 1.10 2002/07/24 16:22:55 pde Exp $ */
MCPDrawSolution:
MCPDrawSolution: import java.awt.*;
MCPDrawSolution:
MCPDrawSolution: /** Solves the equation with a Monte Carlo method and draws the particles
MCPDrawSolution: @version $Revision: 1.10 $
MCPDrawSolution: @see Solution
MCPDrawSolution: @see MCPSolution
MCPDrawSolution: */
MCPDrawSolution: public class MCPDrawSolution extends MCPSolution {
MCPDrawSolution:
MCPDrawSolution: /** Creates a MCPSolution object. Note that discretize must be called
MCPDrawSolution: before next is called for the first time.
MCPDrawSolution: @param runData The run time parameters
MCPDrawSolution: @see Solution#next
MCPDrawSolution: @see Solution#discretize
MCPDrawSolution: */
MCPDrawSolution: public MCPDrawSolution(RunData runData){
MCPDrawSolution: super(runData);
MCPDrawSolution: } // MCPDrawSolution
MCPDrawSolution:
MCPDrawSolution: /** Plots the solution
MCPDrawSolution: @param plotArea The plot area
MCPDrawSolution: @param offScrImage The off screen image to draw on
MCPDrawSolution: @param headers Whether to draw headers
MCPDrawSolution: */
MCPDrawSolution: public void plot(Canvas plotArea, Image offScrImage, boolean headers){
MCPDrawSolution: if(!distributionUpToDate)
MCPDrawSolution: generateDistribution();
MCPDrawSolution: super.plot(plotArea, offScrImage, headers);
MCPDrawSolution:
MCPDrawSolution: int[] win=this.getWinSize();
MCPDrawSolution: xSize=win[0]; xOffset=win[2];
MCPDrawSolution: ySize=win[1]; xOffset=win[3];
MCPDrawSolution: Graphics g = offScrImage.getGraphics();
MCPDrawSolution: double dx = (xSize-2*xOffset)/(x_1-x_0);
MCPDrawSolution: double dy = (ySize-2*yOffset)/(y_1-y_0);
MCPDrawSolution: int[] x = new int[mesh.size() + 2];
MCPDrawSolution: int[] y = new int[mesh.size() + 2];
MCPDrawSolution: g.setColor(Color.red);
MCPDrawSolution: if (numberOfRealisations>10) {
MCPDrawSolution: for(int i = 0; i < numberOfRealisations; i++)
MCPDrawSolution: g.fillRect((int)Math.round((currentState[i][0]-x_0)*dx)+xOffset-1,
MCPDrawSolution: ySize -(i%(ySize-2*yOffset))-yOffset-2,3,3);
MCPDrawSolution: } else {
MCPDrawSolution: for(int i = 0; i < numberOfRealisations; i++)
MCPDrawSolution: g.fillRect((int)Math.round((currentState[i][0]-x_0)*dx)+xOffset-1,
MCPDrawSolution: ySize -(i*8)-yOffset-12,8,8);
MCPDrawSolution: }
MCPDrawSolution: } // plot
MCPDrawSolution:
MCPDrawSolution: } // class MCPDrawSolution
MCPSolution: /* $Id: MCPSolution.java,v 1.16 2002/08/19 06:43:31 pde Exp $ */
MCPSolution: import java.awt.*;
MCPSolution: import java.util.Random;
MCPSolution: /******************************************************************************
MCPSolution: * MCPSolution -- contains the Monte Carlo simulations
MCPSolution: * @version $Revision: 1.16 $
MCPSolution: * @see ParticleSolution
MCPSolution: * @see Solution
MCPSolution: ******************************************************************************/
MCPSolution: public class MCPSolution extends ParticleSolution{
MCPSolution:
MCPSolution: /** Creates a MCPSolution object.
MCPSolution: discretize must be called before next is called for the first time.
MCPSolution: @param runData The run time parameters
MCPSolution: @see Solution#next
MCPSolution: @see Solution#discretize
MCPSolution: */
MCPSolution: public MCPSolution(RunData runData){
MCPSolution: super(runData);
MCPSolution: } // MCPSolution
MCPSolution:
MCPSolution:
MCPSolution: /** Advance the solution forward one step in time.
MCPSolution: The equation is set by the internal variable topic and
MCPSolution: the numerical scheme by the internal variable scheme
MCPSolution: @param runData List of run parameters
MCPSolution: @see RunData
MCPSolution: @return True if a scheme is implemented for that equation
MCPSolution: */
MCPSolution: public boolean next(RunData runData) {
MCPSolution: int n=f.length-1;
MCPSolution: boolean isDefined = true;
MCPSolution: distributionUpToDate = false;
MCPSolution:
MCPSolution: for (int i=0; i<f.length; i++) { gp[i]=g[i]; }
MCPSolution:
MCPSolution: if(scheme.equals(vmarket.MCPART)) {
MCPSolution:
MCPSolution: double kappa = runData.getParamValue(runData.logNkappaNm);
MCPSolution:
MCPSolution: if(Math.abs(kappa)<0.001) {
MCPSolution: //========================================================================
MCPSolution: // MCP - Random motion with normal distribution of increments
MCPSolution: //========================================================================
MCPSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCPSolution: double mu = runData.getParamValue(runData.driftNm);
MCPSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCPSolution: double strike = runData.getParamValue(runData.strikePriceNm);
MCPSolution:
MCPSolution: for(int j=0; j<numberOfRealisations; j++){
MCPSolution: currentState[j][0] += strike *
MCPSolution: ( mu*timeStep +
MCPSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCPSolution: }
MCPSolution:
MCPSolution: } else if(Math.abs(kappa-1)<0.001) {
MCPSolution: //========================================================================
MCPSolution: // MCP - Random motion with log-normal distribution of increments
MCPSolution: //========================================================================
MCPSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCPSolution: double mu = runData.getParamValue(runData.driftNm);
MCPSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCPSolution:
MCPSolution: for(int j=0; j<numberOfRealisations; j++){
MCPSolution: currentState[j][0] += currentState[j][0] *
MCPSolution: ( mu*timeStep +
MCPSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCPSolution: }
MCPSolution: } else {
MCPSolution: //========================================================================
MCPSolution: // MCP - Radom motion with power kappa
MCPSolution: //========================================================================
MCPSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCPSolution: double mu = runData.getParamValue(runData.driftNm);
MCPSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCPSolution:
MCPSolution: for(int j=0; j<numberOfRealisations; j++){
MCPSolution: currentState[j][0] += Math.pow(currentState[j][0],kappa) *
MCPSolution: ( mu*timeStep +
MCPSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCPSolution: }
MCPSolution: }
MCPSolution: } else if(scheme.equals(vmarket.EXC2_02)){
MCPSolution: //=======================================================================
MCPSolution: // MCP - Exercise 2.02
MCPSolution: //=======================================================================
MCPSolution: //INCLUDE_sol2.02.java_INCLUDE//
MCPSolution:
MCPSolution: } else if(scheme.equals(vmarket.EXC2_03)){
MCPSolution: //=======================================================================
MCPSolution: // MCP - Exercise 2.03
MCPSolution: //=======================================================================
MCPSolution: //INCLUDE_sol2.03.java_INCLUDE//
MCPSolution:
MCPSolution: } else if(scheme.equals(vmarket.EXC2_04)){
MCPSolution: //=======================================================================
MCPSolution: // MCP - Exercise 2.04
MCPSolution: //=======================================================================
MCPSolution: //INCLUDE_sol2.04.java_INCLUDE//
MCPSolution:
MCPSolution: } else if(scheme.equals(vmarket.EXCE_01)){
MCPSolution: //=======================================================================
MCPSolution: // MCP - Exercise E.01
MCPSolution: //=======================================================================
MCPSolution: //INCLUDE_solE.01.java_INCLUDE//
MCPSolution:
MCPSolution: } // if
MCPSolution:
MCPSolution: for (int i=0; i<f.length; i++) { f0[i]=fp[i]; }
MCPSolution:
MCPSolution: return isDefined;
MCPSolution: } // next
MCPSolution:
MCPSolution: /** Tells whether the solution implements a option
MCPSolution: @param option The the option to implement
MCPSolution: @return True if the option is implemented
MCPSolution: @see vmarket#topicNames
MCPSolution: @see vmarket#schemeNames
MCPSolution: */
MCPSolution: public boolean hasOption(String option){
MCPSolution: try {
MCPSolution: if (option.equals(vmarket.RNDWALK))
MCPSolution: return true;
MCPSolution: else if (option.equals(vmarket.EXERCISE))
MCPSolution: return true;
MCPSolution: else if(topic.equals(vmarket.RNDWALK) && option.equals(vmarket.MCPART))
MCPSolution: return true;
MCPSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC2_02))
MCPSolution: return true;
MCPSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC2_03))
MCPSolution: return true;
MCPSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC2_04))
MCPSolution: return true;
MCPSolution: return false;
MCPSolution: } catch (NullPointerException e){
MCPSolution: return false;
MCPSolution: } // try
MCPSolution: } // hasOption
MCPSolution:
MCPSolution: /** Plots the solution
MCPSolution: @param plotArea The plot area
MCPSolution: @param offScrImage The off screen image to draw on
MCPSolution: @param headers Whether to draw headers
MCPSolution: */
MCPSolution: public void plot(Canvas plotArea, Image offScrImage, boolean headers){
MCPSolution: if(!distributionUpToDate)
MCPSolution: generateDistribution();
MCPSolution: super.plot(plotArea, offScrImage, headers);
MCPSolution: } // plot
MCPSolution:
MCPSolution: } // class MCPSolution
MCSDrawSolution: /* $Id: MCSDrawSolution.java,v 1.10 2002/07/24 16:22:55 pde Exp $ */
MCSDrawSolution:
MCSDrawSolution: import java.awt.*;
MCSDrawSolution:
MCSDrawSolution: /** Solves the equation with a Monte Carlo sampling of possible configurations
MCSDrawSolution: and drawn on the plot area
MCSDrawSolution: @version $Revision: 1.10 $
MCSDrawSolution: @see Solution
MCSDrawSolution: @see MCSSolution
MCSDrawSolution: */
MCSDrawSolution: public class MCSDrawSolution extends MCSSolution {
MCSDrawSolution:
MCSDrawSolution: /** Creates a MCSSolution object. Note that discretize must be called
MCSDrawSolution: before next is called for the first time.
MCSDrawSolution: @param runData The run time parameters
MCSDrawSolution: @see Solution#next
MCSDrawSolution: @see Solution#discretize
MCSDrawSolution: */
MCSDrawSolution: public MCSDrawSolution(RunData runData){
MCSDrawSolution: super(runData);
MCSDrawSolution: } // MCSDrawSolution
MCSDrawSolution:
MCSDrawSolution: /** Plots the solution
MCSDrawSolution: @param plotArea The plot area
MCSDrawSolution: @param offScrImage The off screen image to draw on
MCSDrawSolution: @param headers Whether to draw headers
MCSDrawSolution: */
MCSDrawSolution: public void plot(Canvas plotArea, Image offScrImage, boolean headers){
MCSDrawSolution: if(!solutionUpToDate)
MCSDrawSolution: expectedValue();
MCSDrawSolution: super.plot(plotArea, offScrImage, headers);
MCSDrawSolution:
MCSDrawSolution: int[] win=this.getWinSize();
MCSDrawSolution: xSize=win[0]; xOffset=win[2];
MCSDrawSolution: ySize=win[1]; xOffset=win[3];
MCSDrawSolution: Graphics g = offScrImage.getGraphics();
MCSDrawSolution: double dx = (xSize-2*xOffset)/(x_1-x_0);
MCSDrawSolution: double dy = (ySize-2*yOffset)/(y_1-y_0);
MCSDrawSolution: int[] x = new int[mesh.size() + 2];
MCSDrawSolution: int[] y = new int[mesh.size() + 2];
MCSDrawSolution: int dotX, dotY, dotSize;
MCSDrawSolution:
MCSDrawSolution: if(scheme.equals(vmarket.INBAR)||scheme.equals(vmarket.OUTBAR)){
MCSDrawSolution: for(int k=0; k<numberOfRealisations; k++){
MCSDrawSolution: if (mark[k][0]==0.) g.setColor(Color.blue);
MCSDrawSolution: else g.setColor(Color.red);
MCSDrawSolution: dotX=(int)Math.round((currentState[k][0]-x_0)*dx)+xOffset-1;
MCSDrawSolution: if (numberOfRealisations<10) {
MCSDrawSolution: dotSize=8; dotY=ySize-(k*dotSize)-yOffset-12;
MCSDrawSolution: } else {
MCSDrawSolution: dotSize=3; dotY=ySize-(k%(ySize-2*yOffset))-yOffset-2;
MCSDrawSolution: }
MCSDrawSolution: g.fillRect(dotX,dotY,dotSize,dotSize);
MCSDrawSolution: }
MCSDrawSolution: } else {
MCSDrawSolution: g.setColor(Color.red);
MCSDrawSolution: for(int k=0; k<numberOfRealisations; k++) {
MCSDrawSolution: dotX=(int)Math.round((currentState[k][0]-x_0)*dx)+xOffset-1;
MCSDrawSolution: if (numberOfRealisations<10) {
MCSDrawSolution: dotSize=8; dotY=ySize-(k*dotSize)-yOffset-12;
MCSDrawSolution: } else {
MCSDrawSolution: dotSize=3; dotY=ySize-(k%(ySize-2*yOffset))-yOffset-2;
MCSDrawSolution: }
MCSDrawSolution: g.fillRect(dotX,dotY,dotSize,dotSize);
MCSDrawSolution: }
MCSDrawSolution: }
MCSDrawSolution: } // plot
MCSDrawSolution:
MCSDrawSolution: } // class MCSDrawSolution
MCSSolution: /* $Id: MCSSolution.java,v 1.13 2002/08/19 06:43:31 pde Exp $ */
MCSSolution: import java.awt.*;
MCSSolution: import java.util.Random;
MCSSolution: /******************************************************************************
MCSSolution: * MCSSolution -- contains the Monte Carlo Sampling solution
MCSSolution: * @version $Revision: 1.13 $
MCSSolution: * @see ParticleSolution
MCSSolution: * @see Solution
MCSSolution: ******************************************************************************/
MCSSolution: public class MCSSolution extends SamplingSolution{
MCSSolution:
MCSSolution: /** Creates a MCSSolution object.
MCSSolution: discretize must be called before next is called for the first time.
MCSSolution: @param runData The run time parameters
MCSSolution: @see Solution#next
MCSSolution: @see Solution#discretize
MCSSolution: */
MCSSolution: public MCSSolution(RunData runData){
MCSSolution: super(runData);
MCSSolution: } // MCSSolution
MCSSolution:
MCSSolution:
MCSSolution: /** Advance the solution forward one step in time.
MCSSolution: The equation is set by the internal variable method and
MCSSolution: the numerical scheme by the internal variable scheme
MCSSolution: @param runData List of run parameters
MCSSolution: @see RunData
MCSSolution: @return True if a scheme is implemented for that equation
MCSSolution: */
MCSSolution: public boolean next(RunData runData) {
MCSSolution: int n=f.length-1;
MCSSolution: boolean isDefined = true;
MCSSolution: solutionUpToDate = false;
MCSSolution:
MCSSolution: for (int j=0; j<f.length; j++) { gp[j]=g[j]; }
MCSSolution:
MCSSolution: if(scheme.equals(vmarket.EUSTY) || scheme.equals(vmarket.OUTBAR)||
MCSSolution: scheme.equals(vmarket.INBAR) ) {
MCSSolution:
MCSSolution: double kappa = runData.getParamValue(runData.logNkappaNm);
MCSSolution:
MCSSolution: if( Math.abs(kappa)<0.001 ){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Separable normal walk
MCSSolution: //=======================================================================
MCSSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCSSolution: double strike = runData.getParamValue(runData.strikePriceNm);
MCSSolution: double mu = runData.getParamValue(runData.driftNm);
MCSSolution: double divid = runData.getParamValue(runData.dividendNm);
MCSSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCSSolution: double barrier = runData.getParamValue(runData.barrierNm);
MCSSolution:
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: currentState[k][0]+= strike*( (mu-divid)*timeStep +
MCSSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCSSolution:
MCSSolution: //Barriers
MCSSolution: if (scheme.equals(vmarket.OUTBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][0]-strike > strike*barrier)||
MCSSolution: (barrier < 0. && currentState[k][0]-strike < strike*barrier) )
MCSSolution: mark[k][0]=0.;
MCSSolution: } else if (scheme.equals(vmarket.INBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][0]-strike > strike*barrier)||
MCSSolution: (barrier < 0. && currentState[k][0]-strike < strike*barrier) )
MCSSolution: mark[k][0]=1.;
MCSSolution: }
MCSSolution:
MCSSolution: } else if( Math.abs(kappa-1.)<0.001 ){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Separable log-normal walk
MCSSolution: //=======================================================================
MCSSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCSSolution: double strike = runData.getParamValue(runData.strikePriceNm);
MCSSolution: double mu = runData.getParamValue(runData.driftNm);
MCSSolution: double divid = runData.getParamValue(runData.dividendNm);
MCSSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCSSolution: double barrier = runData.getParamValue(runData.barrierNm);
MCSSolution:
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: currentState[k][0]+= currentState[k][0]*( (mu-divid)*timeStep +
MCSSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCSSolution:
MCSSolution: //Barriers
MCSSolution: if (scheme.equals(vmarket.OUTBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][0]-strike > strike*barrier)||
MCSSolution: (barrier < 0. && currentState[k][0]-strike < strike*barrier) )
MCSSolution: mark[k][0]=0.;
MCSSolution: } else if (scheme.equals(vmarket.INBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][0]-strike > strike*barrier)||
MCSSolution: (barrier < 0. && currentState[k][0]-strike < strike*barrier) )
MCSSolution: mark[k][0]=1.;
MCSSolution: }
MCSSolution:
MCSSolution: } else {
MCSSolution: //=======================================================================
MCSSolution: // MCS - Non-separable (drift, volatility) can be fct of price
MCSSolution: //=======================================================================
MCSSolution: double timeStep = runData.getParamValue(runData.timeStepNm);
MCSSolution: double strike = runData.getParamValue(runData.strikePriceNm);
MCSSolution: double mu = runData.getParamValue(runData.driftNm);
MCSSolution: double divid = runData.getParamValue(runData.dividendNm);
MCSSolution: double sigma = runData.getParamValue(runData.volatilityNm);
MCSSolution: double barrier = runData.getParamValue(runData.barrierNm);
MCSSolution:
MCSSolution: for(int j=0; j<f.length; j++) {
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: currentState[k][j]+= Math.pow(currentState[k][j],kappa)*
MCSSolution: ( (mu-divid)*timeStep +
MCSSolution: random.nextGaussian()*sigma*Math.sqrt(timeStep) );
MCSSolution:
MCSSolution: //Absolute barriers
MCSSolution: if (scheme.equals(vmarket.OUTBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][j] > barrier)||
MCSSolution: (barrier < 0. && currentState[k][j] <-barrier) )
MCSSolution: mark[k][0]=0.;
MCSSolution: } else if (scheme.equals(vmarket.INBAR)){
MCSSolution: for(int k=0; k<numberOfRealisations; k++)
MCSSolution: if ((barrier >= 0. && currentState[k][j] > barrier)||
MCSSolution: (barrier < 0. && currentState[k][j] <-barrier) )
MCSSolution: mark[k][0]=1.;
MCSSolution: }
MCSSolution: }
MCSSolution: }
MCSSolution:
MCSSolution: } else if(scheme.equals(vmarket.EXC4_06)){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Exercise 4.06
MCSSolution: //=======================================================================
MCSSolution: //INCLUDE_sol4.06.java_INCLUDE//
MCSSolution:
MCSSolution: } else if(scheme.equals(vmarket.EXC4_09)){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Exercise 4.09
MCSSolution: //=======================================================================
MCSSolution: //INCLUDE_sol4.09.java_INCLUDE//
MCSSolution:
MCSSolution: } else if(scheme.equals(vmarket.EXC4_10)){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Exercise 4.10
MCSSolution: //=======================================================================
MCSSolution: //INCLUDE_sol4.10.java_INCLUDE//
MCSSolution:
MCSSolution: } else if(scheme.equals(vmarket.EXC4_11)){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Exercise 4.11
MCSSolution: //=======================================================================
MCSSolution: //INCLUDE_sol4.11.java_INCLUDE//
MCSSolution:
MCSSolution: } else if(scheme.equals(vmarket.EXCE_01)){
MCSSolution: //=======================================================================
MCSSolution: // MCS - Exercise E.01
MCSSolution: //=======================================================================
MCSSolution: //INCLUDE_solE.01.java_INCLUDE//
MCSSolution:
MCSSolution: } // if
MCSSolution: return isDefined;
MCSSolution: } // next
MCSSolution:
MCSSolution: /** Tells whether the solution implements a option
MCSSolution: @param option The the option to implement
MCSSolution: @return True if the option is implemented
MCSSolution: @see vmarket#topicNames
MCSSolution: @see vmarket#schemeNames
MCSSolution: */
MCSSolution: public boolean hasOption(String option){
MCSSolution: try {
MCSSolution: if (option.equals(vmarket.STKOPTION))
MCSSolution: return true;
MCSSolution: else if (option.equals(vmarket.EXERCISE))
MCSSolution: return true;
MCSSolution: else if(topic.equals(vmarket.STKOPTION) &&
MCSSolution: (option.equals(vmarket.MCPART)|| option.equals(vmarket.EUSTY)||
MCSSolution: option.equals(vmarket.INBAR) || option.equals(vmarket.OUTBAR) ))
MCSSolution: return true;
MCSSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_06))
MCSSolution: return true;
MCSSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_09))
MCSSolution: return true;
MCSSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_10))
MCSSolution: return true;
MCSSolution: else if (topic.equals(vmarket.EXERCISE) && option.equals(vmarket.EXC4_11))
MCSSolution: return true;
MCSSolution: return false;
MCSSolution: } catch (NullPointerException e){
MCSSolution: return false;
MCSSolution: } // try
MCSSolution: } // hasOption
MCSSolution:
MCSSolution: /** Plots the solution
MCSSolution: @param plotArea The plot area
MCSSolution: @param offScrImage The off screen image to draw on
MCSSolution: @param headers Whether to draw headers
MCSSolution: */
MCSSolution: public void plot(Canvas plotArea, Image offScrImage, boolean headers){
MCSSolution: if(!solutionUpToDate)
MCSSolution: expectedValue();
MCSSolution: super.plot(plotArea, offScrImage, headers);
MCSSolution: } // plot
MCSSolution:
MCSSolution: } // class MCSSolution
Mesh: /* $Id: Mesh.java,v 1.10 2002/07/24 16:22:55 pde Exp $ */
Mesh:
Mesh: /******************************************************************************
Mesh: * Mesh - Discretization in one dimension
Mesh: ******************************************************************************/
Mesh: class Mesh {
Mesh:
Mesh: /** Coordinates */ double[] x;
Mesh: /** Interval sizes */ double[] dx;
Mesh:
Mesh: /** Constructor
Mesh: @param numberOfMeshPoints The number of mesh points
Mesh: @param meshLeft The left coordinate of the mesh
Mesh: @param meshLength The width of the mesh
Mesh: */
Mesh: public Mesh(int numberOfMeshPoints, double meshLeft, double meshLength) {
Mesh: double start = meshLeft;
Mesh: double end = meshLeft + meshLength;
Mesh:
Mesh: x = new double[numberOfMeshPoints];
Mesh: dx = new double[numberOfMeshPoints];
Mesh: double dx0=(end-start)/((double)(numberOfMeshPoints-1));
Mesh: for (int j=0; j<x.length; j++) {
Mesh: x[j]=start+dx0*(double)j;
Mesh: dx[j]=dx0;
Mesh: }
Mesh: }
Mesh:
Mesh: /** Grid Size
Mesh: @return Number of mesh points */
Mesh: public int size() { return x.length; }
Mesh:
Mesh: /** Coordinate values
Mesh: @return An Array with coordinates */
Mesh: public double[] points() { return x; }
Mesh:
Mesh: /** Coordinate value
Mesh: @param i The index of a coordinate
Mesh: @return The value of a coordinate */
Mesh: public double point(int i) { return x[i]; }
Mesh:
Mesh: /** Spacing between mesh points
Mesh: @return An Array with the interval sizes */
Mesh: public double[] intervals() { return dx; }
Mesh:
Mesh: /** Space to next grid point
Mesh: @param i The index of a coordinate
Mesh: @return The interval size */
Mesh: public double interval(int i) { return dx[i]; }
Mesh:
Mesh: /** Coordinate boundaries
Mesh: @return {min(x), max(x) */
Mesh: public double[] limits() {
Mesh: double[] lim = {x[0], x[0]};
Mesh: for (int i=1;i<x.length;i++) {
Mesh: if (x[i]<lim[0]) {lim[0]=x[i];};
Mesh: if (x[i]>lim[1]) {lim[1]=x[i];};
Mesh: }
Mesh: return lim;
Mesh: }
Mesh:
Mesh: /** For debugging */
Mesh: public String toString() {
Mesh: StringBuffer str = new StringBuffer();
Mesh: str.append("RegularMesh[").append(Double.toString(x[0]))
Mesh: .append(" , ").append(Double.toString(x[2]))
Mesh: .append(" .. ").append(Double.toString(x[x.length-1]))
Mesh: .append("]");
Mesh: return str.toString();
Mesh: }
Mesh:
Mesh: }//End of Mesh
MyChoice: /* $Id: MyChoice.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyChoice:
MyChoice: import java.awt.Choice;
MyChoice:
MyChoice: /** Class for handling the choices of the PDE type, scheme etc
MyChoice: @version $Revision: 1.10 $
MyChoice: */
MyChoice: class MyChoice extends Choice{
MyChoice:
MyChoice: /** List of the possible options of the choice */
MyChoice: String[] options;
MyChoice:
MyChoice: /** Constructor
MyChoice: @param item A list of the possible choices
MyChoice: */
MyChoice: public MyChoice(String[] item){
MyChoice: for(int i=0; i < item.length; i++)
MyChoice: this.addItem(item[i]);
MyChoice: if (this.countItems()==0) this.addItem(" ");
MyChoice: select(0);
MyChoice: // Make a copy of the object
MyChoice: this.options = (String[])item.clone();
MyChoice: } // MyChoice
MyChoice:
MyChoice: /** Synchronize the list with the valid choices for a solution
MyChoice: @param solution The Solution to sync
MyChoice: */
MyChoice: public void sync(Solution solution){
MyChoice: String newSelected = null;
MyChoice: String oldSelected = this.getSelectedItem();
MyChoice:
MyChoice: boolean exist = false; //Check what available
MyChoice: for(int i=0; i<options.length; i++) {
MyChoice: if(solution.hasOption(options[i])) {
MyChoice: if (!oldSelected.equals(null) &&
MyChoice: oldSelected.equals(options[i])) exist = true;
MyChoice: if (newSelected == null) newSelected=options[i];
MyChoice: }
MyChoice: }
MyChoice:
MyChoice: // this.removeAll(); //Does not work properly
MyChoice: if (exist) this.insert(oldSelected,0); //Work around
MyChoice: else this.insert(newSelected,0);
MyChoice: for (int i=1; i<this.getItemCount(); i++) this.remove(i);
MyChoice: for (int i=1; i<this.getItemCount(); i++) this.remove(i);
MyChoice: // for (int i=1; i<this.getItemCount(); i++) this.remove(i);
MyChoice: // for (int i=1; i<this.getItemCount(); i++) this.remove(i);
MyChoice:
MyChoice: for(int i=0; i<options.length; i++)
MyChoice: if(solution.hasOption(options[i])) this.addItem(options[i]);
MyChoice:
MyChoice: if (!oldSelected.equals(null) && exist) {
MyChoice: try { this.select(oldSelected); }
MyChoice: catch (IllegalArgumentException e) { this.select(0); }
MyChoice: } else {
MyChoice: this.select(0);
MyChoice: }
MyChoice: } // sync
MyChoice: } // class MyChoice
MyChoice:
MyDoubleEditor: /* $Id: MyDoubleEditor.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyDoubleEditor:
MyDoubleEditor: /** Editor of double values
MyDoubleEditor: @version $Revision: 1.10 $
MyDoubleEditor: */
MyDoubleEditor: public class MyDoubleEditor extends MyEditor{
MyDoubleEditor: /** Constructor
MyDoubleEditor: @param desc The description
MyDoubleEditor: @param value The current value
MyDoubleEditor: @param caller The calling class
MyDoubleEditor: */
MyDoubleEditor: public MyDoubleEditor(String desc, double value, MyEditorNotable caller){
MyDoubleEditor: super(desc, value, caller);
MyDoubleEditor: field.setText(String.valueOf(value));
MyDoubleEditor: } // MyDoubleEditor
MyDoubleEditor:
MyDoubleEditor: /** Parses the field and tryes to put in the value. If not
MyDoubleEditor: succeeded, this method will fail silently
MyDoubleEditor: */
MyDoubleEditor: protected void parseField() {
MyDoubleEditor: try {
MyDoubleEditor: value = Double.valueOf(field.getText()).doubleValue();
MyDoubleEditor: } catch (NumberFormatException e){
MyDoubleEditor: } // try
MyDoubleEditor: } // parseField
MyDoubleEditor:
MyDoubleEditor: } // class MyDoubleEditor
MyEditor: /* $Id: MyEditor.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyEditor:
MyEditor: import java.awt.*;
MyEditor: import java.text.*;
MyEditor:
MyEditor: /** Class for editing run time parameters
MyEditor: @version $Revision: 1.10 $
MyEditor: */
MyEditor: abstract public class MyEditor extends Frame {
MyEditor: /** Description of the editor */
MyEditor: private String desc;
MyEditor: /** The Set button */
MyEditor: private Button setButton;
MyEditor: /** The Cancel button */
MyEditor: private Button cancelButton;
MyEditor: /** The text field where the value is edited */
MyEditor: protected TextField field = new TextField(10);
MyEditor: /** The value */
MyEditor: protected double value;
MyEditor: /** The class calling */
MyEditor: private MyEditorNotable caller;
MyEditor:
MyEditor: /** Read-edit constructor for registered users
MyEditor: @param desc The description
MyEditor: @param value The current value
MyEditor: @param caller The calling class
MyEditor: */
MyEditor: public MyEditor(String desc, double value, MyEditorNotable caller){
MyEditor: this.desc = new String(desc);
MyEditor: this.value = value;
MyEditor: this.caller = caller;
MyEditor:
MyEditor: Panel p1 = new Panel();
MyEditor: p1.add(new Label(desc));
MyEditor: p1.add(field);
MyEditor: add("Center", p1);
MyEditor:
MyEditor: Panel p2 = new Panel();
MyEditor: p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
MyEditor: cancelButton = new Button("Cancel");
MyEditor: setButton = new Button("Set");
MyEditor: p2.add(cancelButton);
MyEditor: p2.add(setButton);
MyEditor: add("South", p2);
MyEditor:
MyEditor: pack();
MyEditor: show();
MyEditor: } // MyEditor
MyEditor:
MyEditor: /** Read-only constructor for non-registered users
MyEditor: @param desc The description
MyEditor: @param value The current value
MyEditor: */
MyEditor: public MyEditor(String desc, double value){
MyEditor: this.desc = new String(desc);
MyEditor: this.value = value;
MyEditor:
MyEditor: Panel p1 = new Panel();
MyEditor: p1.add(new Label(desc));
MyEditor: p1.add(field);
MyEditor: add("Center", p1);
MyEditor:
MyEditor: Panel p2 = new Panel();
MyEditor: p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
MyEditor: cancelButton = new Button("Cancel");
MyEditor: p2.add(new Label("Restricted: please login to edit"));
MyEditor: p2.add(cancelButton);
MyEditor: add("South", p2);
MyEditor:
MyEditor: pack();
MyEditor: show();
MyEditor: } // MyEditor
MyEditor:
MyEditor: /** Double-click on parameter requires editing
MyEditor: @deprecated
MyEditor: **************************************************************************/
MyEditor: public boolean action(Event event, Object arg) {
MyEditor: if (event.target == setButton || event.target == field) {
MyEditor: parseField();
MyEditor: if (caller != null)
MyEditor: caller.myEditorNotify(desc, value);
MyEditor: } // if
MyEditor: hide();
MyEditor: return true;
MyEditor: } // action
MyEditor:
MyEditor: /** Parses the field and tryes to put in the value. If not
MyEditor: succeeded, this method will fail silently
MyEditor: */
MyEditor: abstract protected void parseField();
MyEditor:
MyEditor: } // MyEditor
MyEditorNotable: /* $Id: MyEditorNotable.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyEditorNotable:
MyEditorNotable: /** Interface supplying the methods needed for a calls to be
MyEditorNotable: notified by MyEditor
MyEditorNotable: @see MyEditor
MyEditorNotable: @version $Revision: 1.10 $
MyEditorNotable: */
MyEditorNotable: interface MyEditorNotable{
MyEditorNotable: /** Called by MyEditor
MyEditorNotable: @param desc The description of the property
MyEditorNotable: @param value The value to set
MyEditorNotable: @see MyEditor
MyEditorNotable: @see MyEditorNotable
MyEditorNotable: */
MyEditorNotable: public void myEditorNotify(String desc, double value);
MyEditorNotable: } // interface MyEditorNotable
MyIntEditor: /* $Id: MyIntEditor.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyIntEditor:
MyIntEditor: /** Editor of int values
MyIntEditor: @version $Revision: 1.10 $
MyIntEditor: */
MyIntEditor: public class MyIntEditor extends MyEditor{
MyIntEditor: /** Constructor
MyIntEditor: @param desc The description
MyIntEditor: @param value The current value
MyIntEditor: @param caller The calling class
MyIntEditor: */
MyIntEditor: public MyIntEditor(String desc, double value, MyEditorNotable caller){
MyIntEditor: super(desc, value, caller);
MyIntEditor: field.setText(String.valueOf((int)value));
MyIntEditor: } // MyIntEditor
MyIntEditor:
MyIntEditor: /** Parses the field and tryes to put in the value. If not
MyIntEditor: succeeded, this method will fail silently
MyIntEditor: */
MyIntEditor: protected void parseField() {
MyIntEditor: try {
MyIntEditor: value = Integer.parseInt(field.getText());
MyIntEditor: } catch (NumberFormatException e){
MyIntEditor: } // try
MyIntEditor: } // parseField
MyIntEditor:
MyIntEditor: } // class MyIntEditor
MyNullEditor: /* $Id: MyNullEditor.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
MyNullEditor:
MyNullEditor: /** Editor demo preventing change of values
MyNullEditor: @version $Revision: 1.10 $
MyNullEditor: */
MyNullEditor: public class MyNullEditor extends MyEditor{
MyNullEditor: /** Constructor
MyNullEditor: @param desc The description
MyNullEditor: @param value The current value
MyNullEditor: */
MyNullEditor: public MyNullEditor(String desc, double value){
MyNullEditor: super(desc, value);
MyNullEditor: field.setText(String.valueOf(value));
MyNullEditor: } // MyNullEditor
MyNullEditor:
MyNullEditor: /** Idle */
MyNullEditor: protected void parseField() {
MyNullEditor: try {
MyNullEditor: // value = Double.valueOf(field.getText()).doubleValue();
MyNullEditor: } catch (NumberFormatException e){
MyNullEditor: } // try
MyNullEditor: }
MyNullEditor:
MyNullEditor: } // class MyNullEditor
ParticleSolution: /* $Id: ParticleSolution.java,v 1.12 2002/07/24 16:22:56 pde Exp $ */
ParticleSolution:
ParticleSolution: import java.util.Random;
ParticleSolution:
ParticleSolution: /*****************************************************************************
ParticleSolution: * ParticleSolution -- Is an abstract class at the top of all the solvers that
ParticleSolution: * that push particles in phase space.
ParticleSolution: * @version $Revision: 1.12 $
ParticleSolution: * @see Solution
ParticleSolution: ******************************************************************************/
ParticleSolution: abstract class ParticleSolution extends Solution{
ParticleSolution:
ParticleSolution: /** The number of test particles in the simulation */
ParticleSolution: protected int numberOfRealisations;
ParticleSolution: /** A vector with the position of the particles */
ParticleSolution: protected double[][] currentState;
ParticleSolution: /** The amount of mass each test particle represents */
ParticleSolution: protected double stateDensity;
ParticleSolution: /** Whether the distribution function is up to date */
ParticleSolution: protected boolean distributionUpToDate;
ParticleSolution: /** Random number generator */
ParticleSolution: protected Random random;
ParticleSolution:
ParticleSolution: /** Creates a ParticleSolution object. The method discretize() must be called
ParticleSolution: before next() is called for the first time.
ParticleSolution: @param runData The run time parameters
ParticleSolution: @see Solution#next
ParticleSolution: @see Solution#discretize
ParticleSolution: ****************************************************************************/
ParticleSolution: public ParticleSolution(RunData runData){
ParticleSolution: super(runData);
ParticleSolution: numberOfRealisations = runData.getParamValueInt(runData.walkersNm);
ParticleSolution: currentState = new double[numberOfRealisations][1];
ParticleSolution: random = new Random();
ParticleSolution: } // ParticleSolution
ParticleSolution:
ParticleSolution: /** Take the solution backward one step to initialize 3 time level schemes;
ParticleSolution: not appropriate in this context.
ParticleSolution: @param runData List of run parameters
ParticleSolution: @return False since it is not used here
ParticleSolution: ****************************************************************************/
ParticleSolution: public boolean previous(RunData runData){
ParticleSolution: return false;
ParticleSolution: } // previous
ParticleSolution:
ParticleSolution: /** Discretize the initial Shape function and initialize the moments
ParticleSolution: Initializes a new set of particles, the number being determined by
ParticleSolution: the numerical scheme parameter.
ParticleSolution: @param function The initial shape to be approximated
ParticleSolution: @see Solution#setScheme
ParticleSolution: ****************************************************************************/
ParticleSolution: public void discretize(ShapeFunction function){
ParticleSolution: int j;
ParticleSolution: for (j=0; j<mesh.size(); j++){ //Initial condition
ParticleSolution: f[j] = function.getValue(mesh, j);
ParticleSolution: f0[j] = f[j];
ParticleSolution: g[j] = 0.;
ParticleSolution: }
ParticleSolution: double[] fLim = super.limits(true); //Min, max
ParticleSolution: double[] xLim = mesh.limits();
ParticleSolution: double meshDensity=(mesh.size()-1.)/(xLim[1]-xLim[0]);
ParticleSolution:
ParticleSolution: int jmax=0; //----- Detect Dirac function
ParticleSolution: for (j=0; j<mesh.size(); j++){
ParticleSolution: if (f[j]>f[jmax]) jmax=j;
ParticleSolution: }
ParticleSolution: if ( function.getValue(mesh,Math.max(jmax-1,0) ) < 0.1 *
ParticleSolution: function.getValue(mesh,jmax) &&
ParticleSolution: function.getValue(mesh,Math.min(jmax+1,mesh.size())) < 0.1 *
ParticleSolution: function.getValue(mesh,jmax) ){
ParticleSolution: initialMoments[0]=dx[jmax]*f[jmax];
ParticleSolution: initialMoments[1]=0.;
ParticleSolution: initialMoments[2]=0.;
ParticleSolution: stateDensity =
ParticleSolution: initialMoments[0]* meshDensity*meshDensity/numberOfRealisations;
ParticleSolution:
ParticleSolution: for(j=0; j<mesh.size(); j++)
ParticleSolution: f[j]=(f[j]-fLim[0])/(fLim[1]-fLim[0]);
ParticleSolution:
ParticleSolution: for(j=0; j<numberOfRealisations; j++)
ParticleSolution: currentState[j][0] = mesh.point(jmax);
ParticleSolution:
ParticleSolution: } else { //----- Regular function
ParticleSolution:
ParticleSolution: initialMoments[0]=calculateMoments(0); //Conserved quantities
ParticleSolution: initialMoments[1]=calculateMoments(1);
ParticleSolution: initialMoments[2]=calculateMoments(2);
ParticleSolution:
ParticleSolution: stateDensity =
ParticleSolution: initialMoments[0]* meshDensity*meshDensity/numberOfRealisations;
ParticleSolution:
ParticleSolution: for(j=0; j<mesh.size(); j++) //Normalize to (0,1)
ParticleSolution: f[j]=(f[j]-fLim[0])/(fLim[1]-fLim[0]);
ParticleSolution:
ParticleSolution: double x;
ParticleSolution: distributionUpToDate = true;
ParticleSolution: for(j=0; j<numberOfRealisations; j++){ // Randomize the positions
ParticleSolution: while(random.nextDouble() >
ParticleSolution: getValue(x = xLim[0]+(xLim[1]-xLim[0])*random.nextDouble())
ParticleSolution: );
ParticleSolution: currentState[j][0] = x;
ParticleSolution: } // for
ParticleSolution: }
ParticleSolution: distributionUpToDate = false;
ParticleSolution: rescale(true);
ParticleSolution: } // discretize
ParticleSolution:
ParticleSolution: /** Calculates the deviation from the m:th initial moment.
ParticleSolution: @param m The order of the moment
ParticleSolution: @return The deviation of the m:th moment from the beginning
ParticleSolution: ****************************************************************************/
ParticleSolution: public double momentsDeviation(int m){
ParticleSolution: if(!distributionUpToDate)
ParticleSolution: generateDistribution();
ParticleSolution: return super.momentsDeviation(m);
ParticleSolution: } // moments
ParticleSolution:
ParticleSolution: /** Calculates the limits of the solution.
ParticleSolution: @return A vector consisting of {min(solution), max(solution)}
ParticleSolution: ****************************************************************************/
ParticleSolution: public double[] limits(){
ParticleSolution: if(!distributionUpToDate)
ParticleSolution: generateDistribution();
ParticleSolution: return super.limits(true);
ParticleSolution: } // limits
ParticleSolution:
ParticleSolution: /** Gives the value of the function for an index
ParticleSolution: @param index The index for which to get the value
ParticleSolution: @return The value of the distribution function at a given index
ParticleSolution: ****************************************************************************/
ParticleSolution: public double getValue(int index) {
ParticleSolution: if(!distributionUpToDate)
ParticleSolution: generateDistribution();
ParticleSolution: return super.getValue(index);
ParticleSolution: } // getValue
ParticleSolution:
ParticleSolution: /** Linear interpolation of the solution. Assumes a uniform mesh.
ParticleSolution: @param arg Argument
ParticleSolution: @return A linear interpolation of the function for a given argument
ParticleSolution: ****************************************************************************/
ParticleSolution: public double getValue(double arg){
ParticleSolution: if(!distributionUpToDate)
ParticleSolution: generateDistribution();
ParticleSolution: return super.getValue(arg);
ParticleSolution: } // getValue
ParticleSolution:
ParticleSolution: /** Generates the distribution function from the set of test particles.
ParticleSolution: Assumes a uniform mesh.
ParticleSolution: ****************************************************************************/
ParticleSolution: protected void generateDistribution(){
ParticleSolution: int j;
ParticleSolution: for(j=0; j<mesh.size(); j++) f[j] = 0;
ParticleSolution: double[] xLim = mesh.limits();
ParticleSolution: for(j=0; j<numberOfRealisations; j++){
ParticleSolution: // Lower mesh cell index
ParticleSolution: int index = (int)Math.floor((currentState[j][0] - xLim[0])
ParticleSolution: / (xLim[1] - xLim[0]) *
ParticleSolution: (mesh.size() - 1));
ParticleSolution:
ParticleSolution: if(index >= 0 && index < mesh.size()){ //Particle is in plot region
ParticleSolution: double x_low = mesh.point(index);
ParticleSolution: double x_high = mesh.point(index)+dx[0];
ParticleSolution: double a = (currentState[j][0]-x_low)/(x_high-x_low);
ParticleSolution: double cell_area_left = 1/dx[0]; // Assume uniform mesh
ParticleSolution: double cell_area_right = 1/dx[0];
ParticleSolution: f[index] += (1-a)* stateDensity/cell_area_left;
ParticleSolution: if (index+1<mesh.size())
ParticleSolution: f[index+1] += a * stateDensity/cell_area_right;
ParticleSolution: } // if
ParticleSolution: } // for
ParticleSolution: distributionUpToDate = true;
ParticleSolution: } // generateDistribution
ParticleSolution:
ParticleSolution: } // ParticleSolution
PlotArea: /* $Id: PlotArea.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
PlotArea:
PlotArea: import java.awt.*;
PlotArea:
PlotArea: /** Class used for the plot area
PlotArea: @version $Revision: 1.10 $
PlotArea: */
PlotArea: class PlotArea extends Canvas{
PlotArea:
PlotArea: /** The solution to plot */
PlotArea: private Solution solution;
PlotArea:
PlotArea: /** Whether to draw headers */
PlotArea: private boolean headers = true;
PlotArea:
PlotArea: /** Set the solution to plot
PlotArea: @param solution The solution to plot
PlotArea: */
PlotArea: public void setSolution(Solution solution){
PlotArea: this.solution = solution;
PlotArea: } // setSolution
PlotArea:
PlotArea: /** Toggles whether to draw headers
PlotArea: */
PlotArea: public boolean toggleHeaders() {
PlotArea: headers = !headers;
PlotArea: return headers;
PlotArea: } // toggleHeaders
PlotArea:
PlotArea: /** Plot the graphics
PlotArea: @param g Graphics to plot
PlotArea: */
PlotArea: public void paint(Graphics g){
PlotArea: Dimension d;
PlotArea: try{
PlotArea: // Java 1.1
PlotArea: d = getSize();
PlotArea: } catch (NoSuchMethodError e) {
PlotArea: //Java1.0
PlotArea: d = size();
PlotArea: } // try
PlotArea: Image offScrImage = createImage(d.width, d.height);
PlotArea: solution.plot(this, offScrImage, headers);
PlotArea: g.drawImage(offScrImage, 0, 0, this);
PlotArea: } // paint
PlotArea:
PlotArea: /**
PlotArea: * No need to clear anything; just paint.
PlotArea: */
PlotArea: public void update(Graphics g) {
PlotArea: paint(g);
PlotArea: }
PlotArea:
PlotArea: } // PlotArea
RunData: /* $Id: RunData.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
RunData:
RunData: import java.awt.*;
RunData: import java.text.*;
RunData: import java.applet.Applet;
RunData:
RunData: /** Class taking care of run time parameters
RunData: @version $Revision: 1.10 $
RunData: */
RunData: public class RunData extends List implements MyEditorNotable {
RunData:
RunData: /** Final time to reach*/
RunData: public final static String runTimeNm = "RunTime";
RunData: /** Option exercise price or swap price */
RunData: public final static String strikePriceNm = "StrikePrice";
RunData: /** Option barrier relative to present value */
RunData: public final static String barrierNm = "Barrier";
RunData: /** Drift of the stochastic variable */
RunData: public final static String driftNm = "Drift";
RunData: /** Present value of interest rate */
RunData: public final static String spotRateNm = "SpotRate";
RunData: /** Dividend yield of underlying */
RunData: public final static String dividendNm = "Dividend";
RunData: /** Market price of risk */
RunData: public final static String mktPriceRskNm = "MktPriceRsk";
RunData: /** Mean reversion process target value */
RunData: public final static String meanRevTargNm = "MeanRevTarg";
RunData: /** Mean reversion process velocity */
RunData: public final static String meanRevVeloNm = "MeanRevVelo";
RunData: /** Volatility of the stochastic variable */
RunData: public final static String volatilityNm = "Volatility";
RunData: /** Exponent in the random walk */
RunData: public final static String logNkappaNm = "LogNkappa";
RunData: /** Initial shape offset */
RunData: public final static String shape0Nm = "Shape0";
RunData: /** Initial shape slope */
RunData: public final static String shape1Nm = "Shape1";
RunData: /** Initial shape convexity */
RunData: public final static String shape2Nm = "Shape2";
RunData: /** Lower value of x-axis */
RunData: public final static String meshLeftNm = "MeshLeft";
RunData: /** Length of x-axis */
RunData: public final static String meshLengthNm = "MeshLength";
RunData: /** Number of mesh points on x-axis */
RunData: public final static String meshPointsNm = "MeshPoints";
RunData: /** Number of random walkers */
RunData: public final static String walkersNm = "Walkers";
RunData: /** Time step duration */
RunData: public final static String timeStepNm = "TimeStep";
RunData: /** Implicit time parameter */
RunData: public final static String timeThetaNm = "TimeTheta";
RunData: /** FEM tunable integration*/
RunData: public final static String tuneQuadNm = "TuneQuad";
RunData: /** User data */
RunData: public final static String userDoubleNm = "UserDouble";
RunData: /** User data */
RunData: public final static String userIntegerNm = "UserInteger";
RunData:
RunData: /** Drift of the second stochastic variable */
RunData: public final static String drift2Nm = "Drift2";
RunData: /** Volatility of the second stochastic variable */
RunData: public final static String volatility2Nm = "Volatility2";
RunData: /** Correlation between stochastic variables 1 and 2 */
RunData: public final static String correlNm = "Correlation";
RunData: /** Coefficient */
RunData: public final static String alpha1Nm = "Alpha1";
RunData: /** Coefficient */
RunData: public final static String beta1Nm = "Beta1";
RunData: /** Coefficient */
RunData: public final static String alpha2Nm = "Alpha2";
RunData: /** Coefficient */
RunData: public final static String beta2Nm = "Beta2";
RunData: /** Maximum length of the parameters strings */
RunData: private int maxLength;
RunData: /** The names of all the run time parameters */
RunData: private final static String[] paramNames = {
RunData: runTimeNm, strikePriceNm, barrierNm,
RunData: driftNm, spotRateNm, dividendNm,
RunData: mktPriceRskNm, meanRevTargNm, meanRevVeloNm,
RunData: volatilityNm, logNkappaNm, walkersNm,
RunData: shape0Nm, shape1Nm, shape2Nm,
RunData: meshLeftNm, meshLengthNm, meshPointsNm,
RunData: timeStepNm, timeThetaNm, tuneQuadNm,
RunData: userDoubleNm, userIntegerNm,
RunData: volatility2Nm, drift2Nm, correlNm,
RunData: alpha1Nm, alpha2Nm,
RunData: beta1Nm, beta2Nm};
RunData: /** The type (integer or double) of the parameter */
RunData: private final static boolean[] paramIsInt = {
RunData: false, false, false,
RunData: false, false, false,
RunData: false, false, false,
RunData: false, false, true,
RunData: false, false, false,
RunData: false, false, true,
RunData: false, false, false,
RunData: false, true,
RunData: false, false, false,
RunData: false, false,
RunData: false, false};
RunData: /** The value of the parameter converted to double */
RunData: private double[] paramVal;
RunData: /** Display the parameters in the applet or not */
RunData: private boolean[] paramShow;
RunData:
RunData: /** Discretization mesh*/ Mesh mesh;
RunData: /** The calling class */ private RunDataNotable caller;
RunData: /** Dessert */ private boolean cookme = false;
RunData:
RunData: /** Creates the mesh from the parameters */
RunData: public void createMesh(){
RunData: int meshPoints = getParamValueInt(meshPointsNm);
RunData: double meshLeft = getParamValue(meshLeftNm);
RunData: double meshLength = getParamValue(meshLengthNm);
RunData: mesh = new Mesh(meshPoints, meshLeft, meshLength);
RunData: } // createMesh
RunData:
RunData: /** Constructor */
RunData: public RunData(RunDataNotable caller) {
RunData: super(paramNames.length, false); // for window height if not applet
RunData: this.caller = caller;
RunData: // initialize parameters
RunData: maxLength = 0; int i;
RunData: paramShow = new boolean[paramNames.length];
RunData: paramVal = new double[paramNames.length];
RunData: for(i=0; i<paramNames.length; i++) {
RunData: paramShow[i] = false;
RunData: if(paramNames[i].length() > maxLength)
RunData: maxLength = paramNames[i].length();
RunData: }
RunData: maxLength =+ 11;
RunData:
RunData: setParamValue(runTimeNm, 1.); //final time [years]
RunData: setParamValue(strikePriceNm, 10); //strike price
RunData: setParamValue(barrierNm,-0.1); //barrier
RunData: setParamValue(driftNm, 0.); //drift of stochastic var 1
RunData: setParamValue(spotRateNm, 0.03); //spot rate
RunData: setParamValue(dividendNm, 0.); //dividend yield
RunData: setParamValue(mktPriceRskNm, 0.); //market price of risk
RunData: setParamValue(meanRevTargNm, 0.05); //reversion target
RunData: setParamValue(meanRevVeloNm, 0.); //reversion speed
RunData: setParamValue(volatilityNm, 0.5); //volatility of stochastic var 1
RunData: setParamValue(logNkappaNm, 1.); //exponent in rnd walk
RunData: setParamValue(shape0Nm, 1.); //IC amplitude
RunData: setParamValue(shape1Nm, 0.001); //IC slope
RunData: setParamValue(shape2Nm,-0.05); //IC convexity
RunData: setParamValue(meshLeftNm, 0); //Lower value x-axis
RunData: setParamValue(meshLengthNm, 20); //Length of x-axis
RunData: setParamValue(meshPointsNm, 21); //Points on x-axis
RunData: setParamValue(walkersNm, 300); //Nbr of walkers
RunData: setParamValue(timeStepNm,.00397); //Time step [years]
RunData: setParamValue(timeThetaNm, 0.7); //Implicit time integr
RunData: setParamValue(tuneQuadNm, 0.333); //Tunable quadrature
RunData: setParamValue(userDoubleNm, 0.); //Undefined double
RunData: setParamValue(userIntegerNm, 0); //Undefined integer
RunData: setParamValue(drift2Nm, 0.); //drift of stochastic var 2
RunData: setParamValue(volatility2Nm, 0.5); //volatility of stochastic var 2
RunData: setParamValue(correlNm, 0.9); //correlation between var 1 & 2
RunData: setParamValue(alpha1Nm, 0.); //coefficient
RunData: setParamValue(beta1Nm, 0.); //coefficient
RunData: setParamValue(alpha2Nm, 0.); //coefficient
RunData: setParamValue(beta2Nm, 0.); //coefficient
RunData:
RunData: // update panel
RunData: this.setBackground(new Color(Integer.parseInt("88FFFF",16)));
RunData: setFont(new Font("Courier", Font.PLAIN, 12));
RunData: syncList();
RunData: createMesh();
RunData:
RunData: } // RunData
RunData:
RunData: /** Returns index of a parameter
RunData: @param name String The parameter name
RunData: @return The parameter index */
RunData: final public int getParamIndex(String name){
RunData: for(int i=0; i<paramNames.length; i++)
RunData: if (name.equals(paramNames[i])) return i;
RunData: return -1;
RunData: }
RunData:
RunData: /** Returns the value a double parameter
RunData: @param name String The parameter name
RunData: @return The parameter value */
RunData: final public double getParamValue(String name){
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if (name.equals(paramNames[i])) return paramVal[i];
RunData: }
RunData: // This should not happen
RunData: System.out.println("Unknown param '"+name+"' in RunData.getParamValue()!");
RunData: return 0.;
RunData: }
RunData:
RunData: /** Returns the value of an integer parameter
RunData: @param name String The parameter name
RunData: @return The parameter value */
RunData: final public int getParamValueInt(String name){
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if (name.equals(paramNames[i])) {
RunData: return (int)paramVal[i];
RunData: }
RunData: }
RunData: // This should not happen
RunData: System.out.println("Unknown param '"+name+"' in RunData.getParamValue()!");
RunData: return 0;
RunData: }
RunData:
RunData: /** Sets the value of a parameter
RunData: @param name String The parameter name
RunData: @return The parameter value */
RunData: final public void setParamValue(String name, double value){
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if (name.equals(paramNames[i])) {
RunData: paramVal[i]=value;
RunData: syncList();
RunData: return;
RunData: }
RunData: }
RunData: // This should not happen
RunData: System.out.println("Unknown param '"+name+"' in RunData.setParamValue()!");
RunData: return;
RunData: }
RunData:
RunData: /** Synchronizes the list with the current parameters */
RunData: final public void syncList(){
RunData: removeAll();
RunData: StringBuffer buffer;
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if (paramShow[i]) {
RunData: buffer = new StringBuffer(maxLength);
RunData: buffer.append(paramNames[i]); pad(buffer, maxLength);
RunData: if (paramIsInt[i])
RunData: buffer.append(" = " + String.valueOf((int)paramVal[i]));
RunData: else
RunData: buffer.append(" = " + String.valueOf(paramVal[i]));
RunData: addItem(buffer.toString());
RunData: }
RunData: }
RunData: } // syncList
RunData:
RunData: /** Modify defaults parameters the HTML tags from the web page
RunData: @param a The applet to get the parameters from
RunData: */
RunData: final public void tagModify(Applet a) {
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: try { String tmp = a.getParameter(paramNames[i]);
RunData: if(tmp!=null) {
RunData: paramVal[i]=Double.valueOf(tmp).doubleValue();
RunData: paramShow[i]=true;
RunData: }
RunData: } catch (NumberFormatException e) {}
RunData: }
RunData: String tmp = a.getParameter("Cookme");
RunData: if(tmp!=null) cookme = true;
RunData: syncList();
RunData: } // TagModify
RunData:
RunData: /** Selects all the parameters for display in the applet
RunData: */
RunData: final public void displayAll() {
RunData: for(int i=0; i<paramNames.length; i++)
RunData: paramShow[i]=true;
RunData: syncList();
RunData: } // displayAll
RunData:
RunData: /** Selects only tag parameters for display in the applet
RunData: */
RunData: final public void displayTag(Applet a) {
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if(a.getParameter(paramNames[i]) !=null)
RunData: paramShow[i]=true;
RunData: else
RunData: paramShow[i]=false;
RunData: }
RunData: syncList();
RunData: } // displayTag
RunData:
RunData: /** Copy the string padding it up with sapces to a specified length
RunData: @param d The output string
RunData: @param length The length to pad to
RunData: */
RunData: private void pad(StringBuffer d, int length){
RunData: while(d.length() < length)
RunData: d.append(" ");
RunData: } // pad
RunData:
RunData: /** Responds to the user actions through the mouse and buttons (Java1.0).
RunData: Yes, we know this sucks compare to Java 1.1, but we want to be
RunData: compatible with as many browsers as possible. There is a lot of
RunData: old stuff out there...
RunData: @deprecated
RunData: */
RunData: final public boolean action(Event e, Object arg) {
RunData: if(e.target instanceof RunData) {
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if(stringPartCompare(paramNames[i], (String)arg)) {
RunData: if (!cookme) {
RunData: if (paramIsInt[i]) {
RunData: MyEditor ed=new MyIntEditor(paramNames[i],(int)paramVal[i],this);
RunData: } else {
RunData: MyEditor ed=new MyDoubleEditor(paramNames[i],paramVal[i],this);
RunData: }
RunData: } else { // cookme
RunData: if (paramIsInt[i]) {
RunData: MyEditor ed=new MyNullEditor(paramNames[i],(int)paramVal[i]);
RunData: } else {
RunData: MyEditor ed=new MyNullEditor(paramNames[i],paramVal[i]);
RunData: }
RunData: } // cookme
RunData: return true;
RunData: } // stringCompare
RunData: } // for
RunData: }
RunData: return false;
RunData: } // action
RunData:
RunData: /** Called by MyEditor
RunData: @param name The description of the property
RunData: @param value The value to set
RunData: @see MyEditor
RunData: @see MyEditorNotable
RunData: */
RunData: final public void myEditorNotify(String name, double value){
RunData: for(int i=0; i<paramNames.length; i++) {
RunData: if(paramNames[i].equals(name)) paramVal[i]=value;
RunData: }
RunData: syncList();
RunData: } // myEditorNote
RunData:
RunData: /** Internal method usedin action for camparing if two strings are
RunData: alike upon the length of the shortest string
RunData: @param s1 String 1 (the sortest)
RunData: @param s2 String 2
RunData: @return True if s1 == s2 upon the length of s1
RunData: */
RunData: final private boolean stringPartCompare(String s1, String s2) {
RunData: return s2.substring(0, s1.length()).equals(s1);
RunData: } // stringPartCompare
RunData:
RunData: /** Returns the mesh @return The mesh */
RunData: final public Mesh getMesh(){ return mesh; }
RunData:
RunData: } // class RunData
RunDataNotable: /* $Id: RunDataNotable.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
RunDataNotable:
RunDataNotable: /** Interface suppying the methods needed for a calls to be
RunDataNotable: notified by RunData
RunDataNotable: @see MyEditor
RunDataNotable: @version $Revision: 1.10 $
RunDataNotable: */
RunDataNotable: interface RunDataNotable{
RunDataNotable: /** Invoked by RunData
RunDataNotable: @see RunData
RunDataNotable: */
RunDataNotable: public void runDataNotifyMesh();
RunDataNotable: /** Invoked by RunData
RunDataNotable: @see RunData
RunDataNotable: */
RunDataNotable: public void runDataNotifyWalkers();
RunDataNotable: } // interface RunDataWalkers
SamplingSolution: /* $Id: SamplingSolution.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
SamplingSolution:
SamplingSolution: import java.util.Random;
SamplingSolution:
SamplingSolution: /*****************************************************************************
SamplingSolution: * SamplingSolution -- Is an abstract class at the top of all the solvers that
SamplingSolution: * that evolve an expected solution by sampling possible realisation.
SamplingSolution: * @version $Revision: 1.10 $
SamplingSolution: * @see Solution
SamplingSolution: ******************************************************************************/
SamplingSolution: abstract class SamplingSolution extends Solution{
SamplingSolution:
SamplingSolution: /** The terminal payoff */
SamplingSolution: protected ShapeFunction option;
SamplingSolution: /** The number of independent realisations to evolve */
SamplingSolution: protected int numberOfRealisations;
SamplingSolution: /** A vector with the current realisation(s) evolved from initial price(s) */
SamplingSolution: protected double[][] currentState;
SamplingSolution: /** A vector with the current markers keeping track of price history */
SamplingSolution: protected double[][] mark;
SamplingSolution: /** The exponent in the random walk */
SamplingSolution: protected double kappa;
SamplingSolution: /** The interest rate */
SamplingSolution: protected double rate;
SamplingSolution: /** The default initial / terminal condition */
SamplingSolution: protected double strike;
SamplingSolution: /** Whether the expected solution is up to date */
SamplingSolution: protected boolean solutionUpToDate;
SamplingSolution: /** Random number generator */
SamplingSolution: protected Random random;
SamplingSolution:
SamplingSolution: /** Creates a SamplingSolution object. Note that discretize must be called
SamplingSolution: before next is called for the first time.
SamplingSolution: @param runData The run time parameters
SamplingSolution: @see Solution#next
SamplingSolution: @see Solution#discretize
SamplingSolution: ****************************************************************************/
SamplingSolution: public SamplingSolution(RunData runData){
SamplingSolution: super(runData);
SamplingSolution: numberOfRealisations = runData.getParamValueInt(runData.walkersNm);
SamplingSolution: strike = runData.getParamValue(runData.strikePriceNm);
SamplingSolution: kappa = runData.getParamValue(runData.logNkappaNm);
SamplingSolution: rate = runData.getParamValue(runData.spotRateNm);
SamplingSolution: random = new Random();
SamplingSolution: } // SamplingSolution
SamplingSolution:
SamplingSolution: /** Take the solution backward one step to initialize schemes
SamplingSolution: with 3 time levels; not really appropriate in this context.
SamplingSolution: @param runData List of run parameters
SamplingSolution: @return False since it is not used here
SamplingSolution: ****************************************************************************/
SamplingSolution: public boolean previous(RunData runData){
SamplingSolution: this.kappa = runData.getParamValue(runData.logNkappaNm); //Synchronize
SamplingSolution: this.rate = runData.getParamValue(runData.spotRateNm);
SamplingSolution: return false;
SamplingSolution: } // previous
SamplingSolution:
SamplingSolution: /** Discretize the initial Shape function and initialize the moments
SamplingSolution: Initializes a new set of particles, the number being determined by
SamplingSolution: the numerical scheme parameter.
SamplingSolution: @param function The initial shape to be approximated
SamplingSolution: @see Solution#setScheme
SamplingSolution: ****************************************************************************/
SamplingSolution: public void discretize(ShapeFunction function){
SamplingSolution: int j,k;
SamplingSolution: option = function; //Terminal payoff
SamplingSolution: for (j=0; j<mesh.size(); j++){ //Initial condition
SamplingSolution: f[j] = function.getValue(mesh, j);
SamplingSolution: f0[j]= f[j];
SamplingSolution: g[j] = 0.;
SamplingSolution: } //Initialize separable samples
SamplingSolution: if((Math.abs(kappa)<0.001) ||(Math.abs(kappa-1.)<0.001)){
SamplingSolution: currentState = new double[numberOfRealisations][1];
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: currentState[k][0]=strike;
SamplingSolution: if(scheme.equals(vmarket.INBAR)){
SamplingSolution: mark = new double[numberOfRealisations][1];
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: mark[k][0]=0.;
SamplingSolution: } else if (scheme.equals(vmarket.OUTBAR)){
SamplingSolution: mark = new double[numberOfRealisations][1];
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: mark[k][0]=1.;
SamplingSolution: }
SamplingSolution: } else { //Initialize non-separable
SamplingSolution: currentState = new double[numberOfRealisations][mesh.size()];
SamplingSolution: for (j=0; j<mesh.size(); j++)
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: currentState[k][j]=x[j];
SamplingSolution: if(scheme.equals(vmarket.INBAR)){
SamplingSolution: mark = new double[numberOfRealisations][mesh.size()];
SamplingSolution: for (j=0; j<mesh.size(); j++)
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: mark[k][j]=0.;
SamplingSolution: } else if (scheme.equals(vmarket.OUTBAR)){
SamplingSolution: mark = new double[numberOfRealisations][mesh.size()];
SamplingSolution: for (j=0; j<mesh.size(); j++)
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: mark[k][j]=1.;
SamplingSolution: }
SamplingSolution: }
SamplingSolution: solutionUpToDate = false;
SamplingSolution: } // discretize
SamplingSolution:
SamplingSolution: /** Calculates the deviation from the m:th initial moment.
SamplingSolution: @param m The order of the moment
SamplingSolution: @return The deviation of the m:th moment from the beginning
SamplingSolution: ****************************************************************************/
SamplingSolution: public double momentsDeviation(int m){
SamplingSolution: if(!solutionUpToDate)
SamplingSolution: expectedValue();
SamplingSolution: return super.momentsDeviation(m);
SamplingSolution: } // moments
SamplingSolution:
SamplingSolution: /** Calculates the limits of the solution.
SamplingSolution: @return A vector consisting of {min(solution), max(solution)}
SamplingSolution: ****************************************************************************/
SamplingSolution: public double[] limits(){
SamplingSolution: if(!solutionUpToDate)
SamplingSolution: expectedValue();
SamplingSolution: return super.limits(true);
SamplingSolution: } // limits
SamplingSolution:
SamplingSolution: /** Gives the value of the function for an index
SamplingSolution: @param index The index for which to get the value
SamplingSolution: @return The value of the distribution function at a given index
SamplingSolution: ****************************************************************************/
SamplingSolution: public double getValue(int index) {
SamplingSolution: if(!solutionUpToDate)
SamplingSolution: expectedValue();
SamplingSolution: return super.getValue(index);
SamplingSolution: } // getValue
SamplingSolution:
SamplingSolution: /** Linear interpolation of the solution. Assumes a uniform mesh.
SamplingSolution: @param arg Argument
SamplingSolution: @return A linear interpolation of the function for a given argument
SamplingSolution: ****************************************************************************/
SamplingSolution: public double getValue(double arg){
SamplingSolution: if(!solutionUpToDate)
SamplingSolution: expectedValue();
SamplingSolution: return super.getValue(arg);
SamplingSolution: } // getValue
SamplingSolution:
SamplingSolution: /** Generates a probability distribution and an expectation from the
SamplingSolution: set of sampled values. Assumes a uniform mesh.
SamplingSolution: ****************************************************************************/
SamplingSolution: protected void expectedValue(){
SamplingSolution: int j,k;
SamplingSolution: boolean markers =
SamplingSolution: scheme.equals(vmarket.INBAR)||scheme.equals(vmarket.OUTBAR);
SamplingSolution:
SamplingSolution: for (j=0; j<mesh.size(); j++){ //Arithmetic average estimatates
SamplingSolution: f[j]=0; g[j]=0.;
SamplingSolution: if (Math.abs(kappa)<0.001){ // separable normal
SamplingSolution: if (markers){
SamplingSolution: for (k=0; k<numberOfRealisations; k++) {
SamplingSolution: f[j]+= option.getValue(currentState[k][0] +x[j]-strike) *mark[k][0];
SamplingSolution: g[j]+= option.getValue(currentState[k][0] +x[j]-strike);
SamplingSolution: }
SamplingSolution: } else
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: f[j]+= option.getValue(currentState[k][0] +x[j]-strike);
SamplingSolution:
SamplingSolution: } else if(Math.abs(kappa-1.)<0.001){ // separable log-normal
SamplingSolution: if (markers){
SamplingSolution: for (k=0; k<numberOfRealisations; k++){
SamplingSolution: f[j]+= option.getValue(currentState[k][0] *x[j]/strike) *mark[k][0];
SamplingSolution: g[j]+= option.getValue(currentState[k][0] *x[j]/strike);
SamplingSolution: }
SamplingSolution: } else
SamplingSolution: for (k=0; k<numberOfRealisations; k++)
SamplingSolution: f[j]+= option.getValue(currentState[k][0] *x[j]/strike);
SamplingSolution:
SamplingSolution: } else // unseparable
SamplingSolution: if (markers){
SamplingSolution: for (k=0; k<numberOfRealisations; k++){
SamplingSolution: f[j]+= option.getValue(currentState[k][j]) *mark[k][j];
SamplingSolution: f[j]+= option.getValue(currentState[k][j]);
SamplingSolution: }
SamplingSolution: } else
SamplingSolution: for (k=0; k<numberOfRealisations; k++){
SamplingSolution: f[j]+= option.getValue(currentState[k][j]);
SamplingSolution: }
SamplingSolution: f[j]=Math.exp(-time*rate)*f[j]/numberOfRealisations;
SamplingSolution: g[j]=Math.exp(-time*rate)*g[j]/numberOfRealisations;
SamplingSolution: } // for
SamplingSolution: solutionUpToDate = true;
SamplingSolution:
SamplingSolution: }//expectedValue
SamplingSolution:
SamplingSolution: } // SamplingSolution
ShapeFunction: /* $Id: ShapeFunction.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
ShapeFunction:
ShapeFunction: /** Abstract class for a describing initial shapes
ShapeFunction: @see Solution#discretize
ShapeFunction: */
ShapeFunction: abstract public class ShapeFunction{
ShapeFunction: /** The shape's abscissa */ protected double position;
ShapeFunction: /** The shape's vertical offset */ protected double amplitude;
ShapeFunction: /** The shape's width */ protected double width;
ShapeFunction: /** The shape's slope */ protected double slope;
ShapeFunction: /** The shape's curvature */ protected double curvature;
ShapeFunction:
ShapeFunction: /** Evaluates the shape for a real argument
ShapeFunction: @param x The argument
ShapeFunction: @return The value of the function for this argument
ShapeFunction: */
ShapeFunction: abstract public double getValue(double x);
ShapeFunction:
ShapeFunction: /** Evaluates the shape on a discrete mesh point position.
ShapeFunction: @param mesh The mesh attributes
ShapeFunction: @param index The mesh index
ShapeFunction: @return The value of the function at this mesh point
ShapeFunction: */
ShapeFunction: abstract public double getValue(Mesh mesh, int index);
ShapeFunction:
ShapeFunction: } // class ShapeFunction
ShapeFunction:
ShapeGaussian: /* $Id: ShapeGaussian.java,v 1.10 2002/07/24 16:22:57 pde Exp $ */
ShapeGaussian:
ShapeGaussian: /******************************************************************************
ShapeGaussian: ShapeGaussian -- A Gaussian function
ShapeGaussian: @see Solution#discretize
ShapeGaussian: ******************************************************************************/
ShapeGaussian: public class ShapeGaussian extends ShapeFunction{
ShapeGaussian:
ShapeGaussian: /** Creates an instance of the class
ShapeGaussian: @param position The box center abscisa
ShapeGaussian: @param amplitude The box height
ShapeGaussian: @param width The box width
ShapeGaussian: */
ShapeGaussian: public ShapeGaussian(double position, double amplitude, double width){
ShapeGaussian: this.position = position;
ShapeGaussian: this.amplitude = amplitude;
ShapeGaussian: this.width = width;
ShapeGaussian: }
ShapeGaussian:
ShapeGaussian: /** Evaluates the shape for a real argument
ShapeGaussian: @param x The argument
ShapeGaussian: @return The value of the function for this argument
ShapeGaussian: */
ShapeGaussian: public double getValue(double x){
ShapeGaussian: double a = (x-position)/width;
ShapeGaussian: return amplitude * Math.exp(-a*a);
ShapeGaussian: }
ShapeGaussian:
ShapeGaussian: /** Evaluates the shape on a discrete mesh point position.
ShapeGaussian: @param mesh The mesh coordinates
ShapeGaussian: @param index The mesh index
ShapeGaussian: @return The value of the function at the specified mesh location
ShapeGaussian: */
ShapeGaussian: public double getValue(Mesh mesh, int index){
ShapeGaussian: return this.getValue(mesh.point(index));
ShapeGaussian: }
ShapeGaussian:
ShapeGaussian: } // class ShapeGaussian
ShapeCall: /* $Id: ShapeCall.java,v 1.10 2002/07/24 16:22:56 pde Exp $ */
ShapeCall:
ShapeCall: /******************************************************************************
ShapeCall: ShapeCall -- Payoff function for a call option at expiry
ShapeCall: @see Solution#discretize
ShapeCall: ******************************************************************************/
ShapeCall: public class ShapeCall extends ShapeFunction{
ShapeCall:
ShapeCall: /** Creates an instance of the class
ShapeCall: @param strike The strike price
ShapeCall: */
ShapeCall: public ShapeCall(double strike){
ShapeCall: position = strike;
ShapeCall: }
ShapeCall:
ShapeCall: /** Evaluates the shape for a real argument
ShapeCall: @param x The argument
ShapeCall: @return The value of the function for this argument
ShapeCall: */
ShapeCall: public double getValue(double x){
ShapeCall: return Math.max(x-position, 0.);
ShapeCall: }
ShapeCall:
ShapeCall: /** Evaluates the shape on a discrete mesh point position.
ShapeCall: @param mesh The mesh coordinates
ShapeCall: @param index The mesh index
ShapeCall: @return The value of the function at the specified mesh location
ShapeCall: */
ShapeCall: public double getValue(Mesh mesh, int index){
ShapeCall: return this.getValue(mesh.point(index));
ShapeCall: }
ShapeCall:
ShapeCall: } // class ShapeCall
ShapePut: /* $Id: ShapePut.java,v 1.10 2002/07/24 16:22:57 pde Exp $ */
ShapePut:
ShapePut: /******************************************************************************
ShapePut: ShapePut -- Payoff function for a put option at expiry
ShapePut: @see Solution#discretize
ShapePut: ******************************************************************************/
ShapePut: public class ShapePut extends ShapeFunction{
ShapePut:
ShapePut: /** Creates an instance of the class
ShapePut: @param strike The strike price
ShapePut: */
ShapePut: public ShapePut(double strike){
ShapePut: position = strike;
ShapePut: }
ShapePut:
ShapePut: /** Evaluates the shape for a real argument
ShapePut: @param x The argument
ShapePut: @return The value of the function for this argument
ShapePut: */
ShapePut: public double getValue(double x){
ShapePut: return Math.max(position - x, 0.);
ShapePut: }
ShapePut:
ShapePut: /** Evaluates the shape on a discrete mesh point position.
ShapePut: @param mesh The mesh coordinates
ShapePut: @param index The mesh index
ShapePut: @return The value of the function at the specified mesh location
ShapePut: */
ShapePut: public double getValue(Mesh mesh, int index){
ShapePut: return this.getValue(mesh.point(index));
ShapePut: }
ShapePut:
ShapePut: } // class ShapePut
ShapeSpread: /* $Id: ShapeSpread.java,v 1.9 2002/07/24 16:22:57 pde Exp $ */
ShapeSpread:
ShapeSpread: /******************************************************************************
ShapeSpread: ShapeSpread -- Payoff function for a spread option at expiry
ShapeSpread: @see Solution#discretize
ShapeSpread: ******************************************************************************/
ShapeSpread: public class ShapeSpread extends ShapeFunction{
ShapeSpread:
ShapeSpread: /** Creates an instance of the class
ShapeSpread: @param position The starting point
ShapeSpread: @param amplitude The offset
ShapeSpread: @param width The width
ShapeSpread: */
ShapeSpread: public ShapeSpread(double position, double amplitude, double width){
ShapeSpread: this.position = position;
ShapeSpread: this.amplitude = amplitude;
ShapeSpread: this.width = width;
ShapeSpread: }
ShapeSpread:
ShapeSpread: /** Evaluates the shape for a real argument
ShapeSpread: @param x The argument
ShapeSpread: @return The value of the function for this argument
ShapeSpread: */
ShapeSpread: public double getValue(double x){
ShapeSpread: return amplitude+Math.max(x-position,0.)-Math.max(x-width,0.);
ShapeSpread: }
ShapeSpread:
ShapeSpread: /** Evaluates the shape on a discrete mesh point position.
ShapeSpread: @param mesh The mesh coordinates
ShapeSpread: @param index The mesh index
ShapeSpread: @return The value of the function at the specified mesh location
ShapeSpread: */
ShapeSpread: public double getValue(Mesh mesh, int index){
ShapeSpread: return this.getValue(mesh.point(index));
ShapeSpread: }
ShapeSpread:
ShapeSpread: } // class ShapeSpread
ShapeYield: /* $Id: ShapeYield.java,v 1.10 2002/07/24 16:22:57 pde Exp $ */
ShapeYield:
ShapeYield: /******************************************************************************
ShapeYield: ShapeYield -- Yield curve / bond term structure
ShapeYield: @see Solution#discretize
ShapeYield: ******************************************************************************/
ShapeYield: public class ShapeYield extends ShapeFunction{
ShapeYield:
ShapeYield: /** Creates an instance of the class
ShapeYield: @param strike The strike price
ShapeYield: */
ShapeYield: public ShapeYield(double strike, double amp, double deriv, double curv){
ShapeYield: position = strike;
ShapeYield: amplitude = amp;
ShapeYield: slope = deriv;
ShapeYield: curvature = curv;
ShapeYield: }
ShapeYield:
ShapeYield: /** Evaluates the shape for a real argument
ShapeYield: @param x The argument
ShapeYield: @return The value of the function for this argument
ShapeYield: */
ShapeYield: public double getValue(double x){
ShapeYield: double z = x/position;
ShapeYield: double s = 3E-1 + z; //Singularity
ShapeYield: return amplitude*(1. + z/(z+s) + z*slope + z*z*curvature);
ShapeYield: }
ShapeYield:
ShapeYield: /** Evaluates the shape on a discrete mesh point position.
ShapeYield: @param mesh The mesh coordinates
ShapeYield: @param index The mesh index
ShapeYield: @return The value of the function at the specified mesh location
ShapeYield: */
ShapeYield: public double getValue(Mesh mesh, int index){
ShapeYield: return this.getValue(mesh.point(index));
ShapeYield: }
ShapeYield:
ShapeYield: } // class ShapeYield
Solution: /* $Id: Solution.java,v 1.13 2002/08/19 06:43:31 pde Exp $ */
Solution:
Solution: import java.awt.*;
Solution: import java.text.*;
Solution:
Solution: /******************************************************************************
Solution: * Solution -- Is an abstract class containing all the solutions and solvers.
Solution: * @see FluidSolution
Solution: * @see ParticleSolution
Solution: ******************************************************************************/
Solution: abstract public class Solution{
Solution:
Solution: /** The topic to be solved @see #setTopic */
Solution: protected String topic;
Solution: /** Numerical method name @see #setMethod */
Solution: protected String method;
Solution: /** Numerical scheme name @see #setScheme */
Solution: protected String scheme;
Solution: /** Initial condition name @see #setIC */
Solution: protected String ic;
Solution: /** Absolute time @see #setTime*/
Solution: protected double time;
Solution:
Solution: /** Function time level 0 (IC) @see #f */ protected double[] f0;
Solution:
Solution: /** Function time level n-1 */ protected double[] fm;
Solution: /** Function time level n */ protected double[] f;
Solution: /** Function time level n+1 */ protected double[] fp;
Solution: /** Derivative time level n-1 @see #fm */ protected double[] dfm;
Solution: /** Derivative time level n @see #f */ protected double[] df;
Solution: /** Derivative time level n+1 @see #fp */ protected double[] dfp;
Solution:
Solution: /** Extra Function time level n-1 */ protected double[] gm;
Solution: /** Extra Function time level n */ protected double[] g;
Solution: /** Extra Function time level n+1 */ protected double[] gp;
Solution: /** Extra Derivative time level n-1 @see #gm */protected double[] dgm;
Solution: /** Extra Derivative time level n @see #g */ protected double[] dg;
Solution: /** Extra Derivative time level n+1 @see #gp */protected double[] dgp;
Solution:
Solution: /** The underlying mesh for the solution */ protected Mesh mesh;
Solution: /** The mesh points @see #mesh */ protected double[] x;
Solution: /** The mesh intervals @see #mesh */ protected double[] dx;
Solution: /** Store initial moments */ protected double[]
Solution: initialMoments = {0.,0.,0.};
Solution:
Solution: /** Horizontal scale of plot area */ protected int xSize;
Solution: /** Vertical scale of plot area */ protected int ySize;
Solution: /** Horizontal offset of plot area */ protected int xOffset;
Solution: /** Vertical offset of plot area */ protected int yOffset;
Solution:
Solution: /** x of lower left corner of plot area */ protected double x_0;
Solution: /** x of upper right corner of plot area */ protected double x_1;
Solution: /** y of lower left corner of plot area */ protected double y_0;
Solution: /** y of upper right corner of plot area */ protected double y_1;
Solution:
Solution: /** Creates an instance of a Solution object with all the attributes.
Solution: @param runData The run time parameters
Solution: ****************************************************************************/
Solution: public Solution(RunData runData) {
Solution: Mesh mesh = runData.getMesh();
Solution: this.mesh = mesh;
Solution: int n = mesh.size();
Solution: x = mesh.points(); dx = mesh.intervals(); f0= new double[n];
Solution: fm = new double[n]; f = new double[n]; fp = new double[n];
Solution: dfm= new double[n]; df = new double[n]; dfp = new double[n];
Solution: gm = new double[n]; g = new double[n]; gp = new double[n];
Solution: dgm= new double[n]; dg = new double[n]; dgp = new double[n];
Solution: lastStep = 0;
Solution: } // Solution
Solution:
Solution:
Solution: /** Internal function to calculate the initial moments of f[] or their
Solution: deviation from the beginning of the evolution.
Solution: @param m The order of the moment
Solution: @return The value or deviation of the m:th moment of f[]
Solution: @see #momentsDeviation
Solution: ****************************************************************************/
Solution: protected double calculateMoments(int m){
Solution: int n=f.length-1;
Solution: double moment = 0.0;
Solution: if (m==0) {
Solution: for (int i=0; i<n; i++) {
Solution: moment= moment+0.5*dx[i]*(f[i+1]+f[i]);
Solution: }
Solution: moment = moment +0.5*dx[n]*(f[0]+f[n]);
Solution: } else { moment=0.0; }
Solution: return moment; //Initial value
Solution: } // calculateMoments
Solution:
Solution: /** Calculates the deviation from the m:th initial moment.
Solution: @param m The order of the moment
Solution: @return The deviation of the m:th moment from the beginning
Solution: ****************************************************************************/
Solution: public double momentsDeviation(int m){
Solution: return (calculateMoments(m) - initialMoments[m])
Solution: / initialMoments[m];
Solution: } // moments
Solution:
Solution: /** Calculates the solution boundaries.
Solution: @return A vector with {min(solution), max(solution)}
Solution: ****************************************************************************/
Solution: protected double[] limits(boolean headers) {
Solution: double[] lim = new double[2];
Solution: if (headers) {
Solution: lim[0]=f[0]; lim[1]=f[0];
Solution: for (int i=1;i<f.length;i++) {
Solution: if (f[i]<lim[0]) {lim[0]=f[i];};
Solution: if (f[i]>lim[1]) {lim[1]=f[i];};
Solution: if (g[i]<lim[0]) {lim[0]=g[i];};
Solution: if (g[i]>lim[1]) {lim[1]=g[i];};
Solution: }
Solution: } else {
Solution: lim[0]=f0[0]; lim[1]=f0[0];
Solution: for (int i=1;i<f.length;i++) {
Solution: if (f0[i]<lim[0]) {lim[0]=f0[i];};
Solution: if (f0[i]>lim[1]) {lim[1]=f0[i];};
Solution: if (g[i]<lim[0]) {lim[0]=g[i];};
Solution: if (g[i]>lim[1]) {lim[1]=g[i];};
Solution: }
Solution: }
Solution: return lim;
Solution: } // limits
Solution:
Solution:
Solution: /** Set the topic as a string.
Solution: @param topic The name of the equation
Solution: @see vmarket#RNDWALK
Solution: ****************************************************************************/
Solution: public void setTopic(String topic){
Solution: this.topic = new String(topic);
Solution: } // setTopic
Solution:
Solution: /** Set the numerical method as a string.
Solution: @param method The name of the numerical method
Solution: @return True
Solution: ****************************************************************************/
Solution: public void setMethod(String method){
Solution: this.method = new String(method);
Solution: } // setMethod
Solution:
Solution: /** Set the numerical scheme as a string.
Solution: @param scheme The name of the numerical scheme
Solution: @return True
Solution: ****************************************************************************/
Solution: public void setScheme(String scheme){
Solution: this.scheme = new String(scheme);
Solution: } // setScheme
Solution:
Solution: /** Set the initial condision as a string.
Solution: @param ic The name of the initial condition
Solution: @return True
Solution: ****************************************************************************/
Solution: public void setIC(String ic){
Solution: this.ic = new String(ic);
Solution: } // setIC
Solution:
Solution:
Solution: /** Set the current physical time
Solution: @param time Current time
Solution: @return True
Solution: ****************************************************************************/
Solution: public boolean setTime(double time){
Solution: this.time = time;
Solution: return true;
Solution: } // setTime
Solution:
Solution:
Solution: /** Increment the current physical time
Solution: @param time Current time to add
Solution: @return True
Solution: ****************************************************************************/
Solution: public boolean incTime(double time){
Solution: this.time += time;
Solution: return true;
Solution: } // incTime
Solution:
Solution:
Solution: /** Get the current physical time
Solution: @return current time
Solution: ****************************************************************************/
Solution: public double getTime(){
Solution: return this.time;
Solution: } // getTime
Solution:
Solution:
Solution: /** Discretize the initial shape and initialize the moments
Solution: @param function The initial shape to be approximated
Solution: ****************************************************************************/
Solution: abstract public void discretize(ShapeFunction function);
Solution:
Solution: /** The current step in the time discretization */
Solution: private int lastStep;
Solution:
Solution: /** Updates the information for the headers
Solution: @param runData List of run parameters
Solution: @param step The current step in the simulation
Solution: @see #plot
Solution: ****************************************************************************/
Solution: public void updateHeaders(RunData runData, int step){
Solution: lastStep = step;
Solution: } // updateHeaders
Solution:
Solution: /** Advance the solution forward one step in time.
Solution: The equation is set by the internal variable equation_ and
Solution: the numerical scheme by the internal variable scheme_
Solution: @param runData List of run parameters
Solution: @see RunData
Solution: @return True if a scheme is implemented for that equation
Solution: */
Solution: abstract public boolean next(RunData runData);
Solution:
Solution: /** Take the solution backward one step to initialize schemes
Solution: with 3 time levels.
Solution: The equation is set by the internal variable equation_ and
Solution: the numerical scheme by the internal variable scheme_
Solution: @param runData List of run parameters
Solution: @see RunData
Solution: @return True if an initialisation scheme is implemented for that equation
Solution: */
Solution: abstract public boolean previous(RunData runData);
Solution:
Solution: /** Gives the value of the function for an index
Solution: @param index The index for which to get the value
Solution: @return The value of the function at a given index
Solution: ****************************************************************************/
Solution: public double getValue(int index) {
Solution: return f[index];
Solution: } // getValue
Solution:
Solution: /** Linear interpolation of the solution. Assumes a uniform mesh.
Solution: @param arg Argument
Solution: @return A linear interpolation of the function for a given argument
Solution: ****************************************************************************/
Solution: public double getValue(double arg){
Solution: double[] xLim = mesh.limits();
Solution: int index=(int)Math.floor((arg-xLim[0])* // Lower mesh cell index
Solution: (mesh.size()-1)/(xLim[1]-xLim[0]));
Solution: if(index == mesh.size()-1) index--;
Solution: double x_low = mesh.point(index); //Linear interpolation
Solution: double x_high = mesh.point(index+1);
Solution: double a = (arg-x_low)/(x_high-x_low);
Solution: return f[index]*(1-a) + f[index+1]*a;
Solution: } // getValue
Solution:
Solution: /** Tells whether the solution implements a option
Solution: @param option The the option to implement
Solution: @return True if the option is implemented
Solution: @see vmarket#topicNames
Solution: @see vmarket#schemeNames
Solution: */
Solution: abstract public boolean hasOption(String option);
Solution:
Solution: /** Set the corners of the plot area
Solution: ****************************************************************************/
Solution: public void rescale(boolean headers){
Solution: double[] lim = limits(headers);
Solution: // Extra space needed for the periodic boundary condition line
Solution: x_0 = x[0] - dx[0] / 2.0;
Solution: x_1 = x[x.length - 1] + dx[x.length - 1] / 2.0;
Solution: y_0 = lim[0];
Solution: y_1 = lim[1];
Solution: if (y_0 == y_1) { y_0=- 1.; y_1=+ 1.; }
Solution: } // rescale
Solution:
Solution: /** Returns window size
Solution: @see #plot
Solution: ****************************************************************************/
Solution: public int[] getWinSize(){
Solution: int[] ret = {xSize,ySize,xOffset,yOffset};
Solution: return ret;
Solution: } //getWinSize
Solution:
Solution: /** Get physical coordinates from mouse coordinates
Solution: @param x horizontal mouse coordinate
Solution: @param y vertical mouse coordinate
Solution: @see #plot
Solution: ****************************************************************************/
Solution: public double[] measure(int x, int y){
Solution: double dx = (xSize-2*xOffset)/(x_1-x_0);
Solution: double dy = (ySize-2*yOffset)/(y_1-y_0);
Solution: double X = x_0+((double)( x-xOffset))/dx;
Solution: double Y = y_0+((double)(-y+ySize+2))/dy;
Solution: double[] coord = {X,Y};
Solution: return coord;
Solution: } // measure
Solution:
Solution: /** Print the solution in ASCII to java console
Solution: ****************************************************************************/
Solution: public void output(int step){
Solution: System.out.println(" ");
Solution: System.out.println("Step="+step);
Solution: for (int i=0; i<mesh.size(); i++) {
Solution: System.out.println("x["+i+"]="+mesh.point(i)+
Solution: " f0["+i+"]="+f0[i]+
Solution: " f["+i+"]="+f[i]);
Solution: }
Solution: } // print
Solution:
Solution: /** Plots the solution
Solution: @param plotArea The plot area
Solution: @param offScrImage The off screen image to draw on
Solution: @param headers Whether to draw headers
Solution: ****************************************************************************/
Solution: public void plot(Canvas plotArea, Image offScrImage, boolean headers){
Solution: } // plot
Solution:
Solution: } // class Solution