Hi, I've been using quantlib through swig in java for several months and, once past the initial difficulties, it has been working very well. Up until now, I've only been using the option pricing functionality but would like to use the monte carlo functionality as well. To get rolling, I've been looking at the DiscreteHedging example with an eye towards implementing in java to get used to what's involved. I've been able to expose and use the relevant bits of BlackCalculator but am now stuck on the implementation of a PathPricer. My hope is to implement the logic of the path pricer within java, but this doesn't seem terribly easy as the path pricer is essentially a callback which, if exposed through SWIG, would need quantlib to call into java (or whatever other language). To do this, I believe I'd have to implement a custom c++ PathPricer which somehow gets a hold of a reference to a java object which implements the path pricer. I don't see any examples in QuantLib-SWIG which seem to do a similar trick which leads me to believe that it is not particularly easy and that people are thus not using the MC model in any very interesting way in other languages. My questions: - Am I missing something obvious here? Are people really not using MC from swig? - Does anyone have an example of a pathpricer or similar functionality which is called through swig from quantlib? - Any ideas on how one might design an amendment to quantlib's existing MC functionality such that it could be more readily accessed/extended from external languages? Thanks in advance for any insights or suggestions and best wishes to all for happy holidays and new year. Tito. ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/ _______________________________________________ QuantLib-dev mailing list [hidden email] https://lists.sourceforge.net/lists/listinfo/quantlib-dev |
Hi, I managed to answer my own questions. Instead of calling back into java from c++, I instead pulled the MonteCarloModel into java which ennabled me to implement a pathPricer in java. The cost is a bit high - this impl is something like 3 times slower than the pure c++ version - but it's not so bad that it becomes unusable for my purposes. Below you'll find a complete working version of the DiscreteHedging implementation in Java. I've also enclosed the modifications I made to the montecarlo.i and options.i SWIG interfaces. Luigi & team could you add to the repository if you find appropriate as others might find them useful? Thanks and regards, Tito. Tito Ingargiola <[hidden email]> wrote:
--- DiscreteHedging.java --- package examples; import org.quantlib.Actual365Fixed; import org.quantlib.BlackCalculator; import org.quantlib.BlackConstantVol; import org.quantlib.BlackScholesMertonProcess; import org.quantlib.BlackVolTermStructureHandle; import org.quantlib.Calendar; import org.quantlib.Date; import org.quantlib.DayCounter; import org.quantlib.FlatForward; import org.quantlib.GaussianLowDiscrepancySequenceGenerator; import org.quantlib.GaussianPathGenerator; import org.quantlib.GaussianRandomSequenceGenerator; import org.quantlib.GaussianSobolPathGenerator; import org.quantlib.Option; import org.quantlib.Path; import org.quantlib.PlainVanillaPayoff; import org.quantlib.QuoteHandle; import org.quantlib.SamplePath; import org.quantlib.SimpleQuote; import org.quantlib.Statistics; import org.quantlib.TARGET; import org.quantlib.UniformLowDiscrepancySequenceGenerator; import org.quantlib.UniformRandomGenerator; import org.quantlib.UniformRandomSequenceGenerator; import org.quantlib.YieldTermStructureHandle; /** * DiscreteHedging Test app - java version of QuantLib/Examples/DiscreteHedging * to illustrate use of Quantlib's MonteCarlo functionality through supplied * SWIG interfaces. * * You need to run this with a correctly set library path and something like: * * -Djava.library.path=/usr/local/lib * * @author Tito Ingargiola **/ public class DiscreteHedging { static { // Load QuantLib try { System.loadLibrary("QuantLibJNI"); } catch (RuntimeException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { long begin = System.currentTimeMillis(); double maturity = 1.0/12.0; // 1 month double strike = 100; double underlying = 100; double volatility = 0.20; // 20% double riskFreeRate = 0.05; // 5% ReplicationError rp = new ReplicationError(Option.Type.Call, maturity, strike, underlying, volatility, riskFreeRate); long scenarios = 50000; long hedgesNum = 21; rp.compute(hedgesNum, scenarios); hedgesNum = 84; rp.compute(hedgesNum, scenarios); long msecs = (System.currentTimeMillis()-begin); System.out.println("\nRun completed in "+msecs+" ms."); } /** * The ReplicationError class carries out Monte Carlo simulations to * evaluate the outcome (the replication error) of the discrete hedging * strategy over different, randomly generated scenarios of future stock * price evolution. **/ public static class ReplicationError { public ReplicationError(Option.Type type, double maturity, double strike, double s0, double sigma, double r ) { type_ = type; maturity_ = maturity; strike_ = strike; s0_ = s0; sigma_ = sigma; r_ = r; // value of the option double rDiscount = Math.exp(-r_ * maturity_); double qDiscount = 1.0; double forward = s0_ * qDiscount/rDiscount; double stdDev = Math.sqrt(sigma_*sigma_*maturity); BlackCalculator black = new BlackCalculator (new PlainVanillaPayoff(type,strike),forward,stdDev,rDiscount); System.out.printf("Option value: %2.5f \n\n",black.value()); // store option's vega, since Derman and Kamal's formula needs it vega_ = black.vega(maturity_); String fmt ="%-8s | %-8s | %-8s | %-8s | %-12s | %-8s | %-8s \n"; System.out.printf (fmt, " ", " ", "P&L", "P&L", "Derman&Kamal", "P&L","P&L" ); System.out.printf(fmt, " samples", "trades", "mean", "std.dev", "formula", "skewness","kurtosis" ); for (int i = 0; i < 78; i++) System.out.print("-"); System.out.println("-"); } void compute(long nTimeSteps, long nSamples) { assert nTimeSteps>0 : "the number of steps must be > 0"; /* Black-Scholes framework: the underlying stock price evolves lognormally with a fixed known volatility that stays constant throughout time. */ Calendar calendar = new TARGET(); Date today = Date.todaysDate(); DayCounter dayCounter = new Actual365Fixed(); QuoteHandle stateVariable = new QuoteHandle(new SimpleQuote(s0_)); YieldTermStructureHandle riskFreeRate = new YieldTermStructureHandle (new FlatForward(today, r_, dayCounter)); YieldTermStructureHandle dividendYield = new YieldTermStructureHandle (new FlatForward(today, 0.0, dayCounter)); BlackVolTermStructureHandle volatility = new BlackVolTermStructureHandle( new BlackConstantVol(today, calendar, sigma_, dayCounter)); BlackScholesMertonProcess diffusion = new BlackScholesMertonProcess (stateVariable,dividendYield, riskFreeRate, volatility); // Black Scholes equation rules the path generator: // at each step the log of the stock // will have drift and sigma^2 variance boolean brownianBridge = false; GaussianRandomSequenceGenerator rsg = new GaussianRandomSequenceGenerator (new UniformRandomSequenceGenerator (nTimeSteps,new UniformRandomGenerator(0))); GaussianPathGenerator myPathGenerator = new GaussianPathGenerator (diffusion,maturity_,nTimeSteps,rsg, brownianBridge); /* Alternately you can modify the MonteCarloModel to take a * GaussianSobolPathGenerator and uncomment these lines and * comment those just above * GaussianLowDiscrepancySequenceGenerator rsg = new GaussianLowDiscrepancySequenceGenerator (new UniformLowDiscrepancySequenceGenerator (nTimeSteps)); GaussianSobolPathGenerator myPathGenerator = new GaussianSobolPathGenerator (diffusion,maturity_,nTimeSteps,rsg, brownianBridge);*/ ReplicationPathPricer myPathPricer = new ReplicationPathPricer (type_,strike_, r_, maturity_, sigma_); MonteCarloModel mcSimulation = new MonteCarloModel (myPathGenerator, myPathPricer); mcSimulation.addSamples(nSamples); // the sampleAccumulator method // gives access to all the methods of statisticsAccumulator double PLMean = mcSimulation.sampleAccumulator().mean(); double PLStDev = mcSimulation.sampleAccumulator().standardDeviation(); double PLSkew = mcSimulation.sampleAccumulator().skewness(); double PLKurt = mcSimulation.sampleAccumulator().kurtosis(); // Derman and Kamal's formula double theorStD = Math.sqrt(Math.PI/4/nTimeSteps)*vega_*sigma_; String fmt = "%-8d | %-8d | %-8.3f | %-8.2f | %-12.2f | %-8.2f | %-8.2f \n"; System.out.printf(fmt, nSamples, nTimeSteps, PLMean, PLStDev, theorStD, PLSkew, PLKurt ); } double maturity_; Option.Type type_; double strike_; double s0_; double sigma_; double r_; double vega_; } /** * We pull the interface for a PathPricer into Java so we can * support its implementation in Java while still relying upon QuantLib's * powerful RNGs. */ public static interface JPathPricer { public double price(Path path); } // The key for the MonteCarlo simulation is to have a PathPricer that // implements a value(const Path& path) method. // This method prices the portfolio for each Path of the random variable public static class ReplicationPathPricer implements JPathPricer { public ReplicationPathPricer(Option.Type type, double strike, double r, double maturity, double sigma) { assert strike > 0 : "Strike must be positive!"; assert maturity > 0 : "Risk free rate must be positive!"; assert r >= 0 : "Risk free rate must be positive or Zero!"; assert sigma >= 0 : "Volatility must be positive or Zero!"; type_ = type; strike_ = strike; r_ = r; maturity_ = maturity; sigma_ = sigma; } public double price(Path path) { long n = path.length() - 1; assert n > 0 : "The path can't be empty!"; // discrete hedging interval double dt = maturity_ / ((double)n); // For simplicity, we assume the stock pays no dividends. double stockDividendYield = 0.0; // let's start double t = 0; // stock value at t=0 double stock = path.front(); // money account at t=0 double money_account = 0.0; /************************/ /*** the initial deal ***/ /************************/ // option fair price (Black-Scholes) at t=0 double rDiscount = Math.exp(-r_*maturity_); double qDiscount = Math.exp(-stockDividendYield*maturity_); double forward = stock*qDiscount/rDiscount; double stdDev = Math.sqrt(sigma_*sigma_*maturity_); PlainVanillaPayoff payoff = new PlainVanillaPayoff(type_,strike_); BlackCalculator black = new BlackCalculator (payoff,forward,stdDev,rDiscount); // sell the option, cash in its premium money_account += black.value(); // compute delta double delta = black.delta(stock); // delta-hedge the option buying stock double stockAmount = delta; money_account -= stockAmount*stock; /**********************************/ /*** hedging during option life ***/ /**********************************/ for (long step = 0; step < n-1; step++){ // time flows t += dt; // accruing on the money account money_account *= Math.exp( r_*dt ); // stock growth: stock = path.value(step+1); // recalculate option value at the current stock value, // and the current time to maturity rDiscount = Math.exp(-r_*(maturity_-t)); qDiscount = Math.exp(-stockDividendYield*(maturity_-t)); forward = stock*(qDiscount/rDiscount); stdDev = Math.sqrt(sigma_*sigma_*(maturity_-t)); black = new BlackCalculator (new PlainVanillaPayoff(type_,strike_),forward,stdDev,rDiscount); // recalculate delta delta = black.delta(stock); // re-hedging money_account -= (delta - stockAmount)*stock; stockAmount = delta; } /*************************/ /*** option expiration ***/ /*************************/ // last accrual on my money account money_account *= Math.exp( r_*dt ); // last stock growth stock = path.value(n); // the hedger delivers the option payoff to the option holder double optionPayoff = (new PlainVanillaPayoff(type_, strike_)).getValue(stock); money_account -= optionPayoff; // and unwinds the hedge selling his stock position money_account += stockAmount*stock; // final Profit&Loss return money_account; } double maturity_; Option.Type type_; double strike_; double sigma_; double r_; } /** * We pull the MonteCarloModel into Java so that we can enable the * implementation in java of our PathPricer */ public static class MonteCarloModel { /** convenience ctor **/ public MonteCarloModel (GaussianPathGenerator gpg, JPathPricer pathpricer) { this(gpg,pathpricer,false, null); } /** complete ctor **/ public MonteCarloModel(GaussianPathGenerator gpg, JPathPricer pathpricer, boolean antitheticVariate, Statistics stats ) { assert gpg != null : "PathGenerator must not be null!"; assert pathpricer != null : "PathPricer must not be null!"; gpg_ = gpg; ppricer_ = pathpricer; stats_ = (stats==null) ? new Statistics() : stats; av_ = antitheticVariate; } public Statistics sampleAccumulator () { return stats_; } public void addSamples( long samples ) { for(long j = 0; j < samples; j++) { SamplePath path = gpg_.next(); double price = ppricer_.price(path.value()); if ( av_ ) { path = gpg_.antithetic(); double price2 = ppricer_.price(path.value()); stats_.add((price+price2)/2.0, path.weight()); } else { stats_.add(price, path.weight()); } } } final boolean av_; final GaussianPathGenerator gpg_; final JPathPricer ppricer_; final Statistics stats_; } } ----- options.i ---- /* Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl Copyright (C) 2005 Dominic Thuillier This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[hidden email]>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef quantlib_options_i #define quantlib_options_i %include common.i %include exercise.i %include stochasticprocess.i %include instruments.i %include stl.i %include linearalgebra.i // option and barrier types %{ using QuantLib::Option; using QuantLib::Barrier; %} // declared out of its hierarchy just to export the inner enumeration class Option { public: enum Type { Put = -1, Call = 1}; private: Option(); }; struct Barrier { enum Type { DownIn, UpIn, DownOut, UpOut }; }; // payoff %{ using QuantLib::Payoff; using QuantLib::StrikedTypePayoff; %} %ignore Payoff; class Payoff { #if defined(SWIGMZSCHEME) || defined(SWIGGUILE) \ || defined(SWIGCSHARP) || defined(SWIGPERL) %rename(call) operator(); #endif public: Real operator()(Real price) const; }; %template(Payoff) boost::shared_ptr<Payoff>; #if defined(SWIGR) %Rruntime %{ setMethod("summary", "_p_VanillaOptionPtr", function(object) {object$freeze() ans <- c(value=object$NPV(), delta=object$delta(), gamma=object$gamma(), vega=object$vega(), theta=object$theta(), rho=object$rho(), divRho=object$dividendRho()) object$unfreeze() ans }) setMethod("summary", "_p_DividendVanillaOptionPtr", function(object) {object$freeze() ans <- c(value=object$NPV(), delta=object$delta(), gamma=object$gamma(), vega=object$vega(), theta=object$theta(), rho=object$rho(), divRho=object$dividendRho()) object$unfreeze() ans }) %} #endif // plain option and engines %{ using QuantLib::VanillaOption; using QuantLib::ForwardVanillaOption; using QuantLib::BlackCalculator; typedef boost::shared_ptr<Instrument> VanillaOptionPtr; typedef boost::shared_ptr<Instrument> MultiAssetOptionPtr; %} %rename(VanillaOption) VanillaOptionPtr; class VanillaOptionPtr : public boost::shared_ptr<Instrument> { #if defined(SWIGMZSCHEME) || defined(SWIGGUILE) %rename("dividend-rho") dividendRho; %rename("implied-volatility") impliedVolatility; #endif public: %extend { VanillaOptionPtr( const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new VanillaOptionPtr(new VanillaOption(stPayoff,exercise)); } Real delta() { return boost::dynamic_pointer_cast<VanillaOption>(*self)->delta(); } Real gamma() { return boost::dynamic_pointer_cast<VanillaOption>(*self)->gamma(); } Real theta() { return boost::dynamic_pointer_cast<VanillaOption>(*self)->theta(); } Real thetaPerDay() { return boost::dynamic_pointer_cast<VanillaOption>(*self) ->thetaPerDay(); } Real vega() { return boost::dynamic_pointer_cast<VanillaOption>(*self)->vega(); } Real rho() { return boost::dynamic_pointer_cast<VanillaOption>(*self)->rho(); } Real dividendRho() { return boost::dynamic_pointer_cast<VanillaOption>(*self) ->dividendRho(); } Real strikeSensitivity() { return boost::dynamic_pointer_cast<VanillaOption>(*self) ->strikeSensitivity(); } SampledCurve priceCurve() { return boost::dynamic_pointer_cast<VanillaOption>(*self) ->result<SampledCurve>("priceCurve"); } Volatility impliedVolatility( Real targetValue, const GeneralizedBlackScholesProcessPtr& process, Real accuracy = 1.0e-4, Size maxEvaluations = 100, Volatility minVol = 1.0e-4, Volatility maxVol = 4.0) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return boost::dynamic_pointer_cast<VanillaOption>(*self) ->impliedVolatility(targetValue, bsProcess, accuracy, maxEvaluations, minVol, maxVol); } } }; %{ using QuantLib::EuropeanOption; typedef boost::shared_ptr<Instrument> EuropeanOptionPtr; %} %rename(EuropeanOption) EuropeanOptionPtr; class EuropeanOptionPtr : public VanillaOptionPtr { public: %extend { EuropeanOptionPtr( const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new EuropeanOptionPtr(new EuropeanOption(stPayoff,exercise)); } } }; // ForwardVanillaOption %{ using QuantLib::ForwardVanillaOption; typedef boost::shared_ptr<Instrument> ForwardVanillaOptionPtr; %} %rename(ForwardVanillaOption) ForwardVanillaOptionPtr; class ForwardVanillaOptionPtr : public VanillaOptionPtr { public: %extend { ForwardVanillaOptionPtr( Real moneyness, Date resetDate, const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new ForwardVanillaOptionPtr( new ForwardVanillaOption(moneyness, resetDate, stPayoff, exercise)); } } }; // QuantoVanillaOption %{ using QuantLib::QuantoVanillaOption; typedef boost::shared_ptr<Instrument> QuantoVanillaOptionPtr; %} %rename(QuantoVanillaOption) QuantoVanillaOptionPtr; class QuantoVanillaOptionPtr : public VanillaOptionPtr { public: %extend { QuantoVanillaOptionPtr( const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new QuantoVanillaOptionPtr( new QuantoVanillaOption(stPayoff, exercise)); } Real qvega() { return boost::dynamic_pointer_cast<QuantoVanillaOption>(*self) ->qvega(); } Real qrho() { return boost::dynamic_pointer_cast<QuantoVanillaOption>(*self) ->qrho(); } Real qlambda() { return boost::dynamic_pointer_cast<QuantoVanillaOption>(*self) ->qlambda(); } } }; %{ using QuantLib::QuantoForwardVanillaOption; typedef boost::shared_ptr<Instrument> QuantoForwardVanillaOptionPtr; %} %rename(QuantoForwardVanillaOption) QuantoForwardVanillaOptionPtr; class QuantoForwardVanillaOptionPtr : public QuantoVanillaOptionPtr { public: %extend { QuantoForwardVanillaOptionPtr( Real moneyness, Date resetDate, const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new QuantoForwardVanillaOptionPtr( new QuantoForwardVanillaOption(moneyness, resetDate, stPayoff, exercise)); } } }; %{ using QuantLib::MultiAssetOption; %} %rename(MultiAssetOption) MultiAssetOptionPtr; class MultiAssetOptionPtr : public boost::shared_ptr<Instrument> { public: %extend { Real delta() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self) ->delta(); } Real gamma() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self) ->gamma(); } Real theta() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self) ->theta(); } Real vega() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self)->vega(); } Real rho() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self)->rho(); } Real dividendRho() { return boost::dynamic_pointer_cast<MultiAssetOption>(*self) ->dividendRho(); } } }; // European engines %{ using QuantLib::AnalyticEuropeanEngine; typedef boost::shared_ptr<PricingEngine> AnalyticEuropeanEnginePtr; %} %rename(AnalyticEuropeanEngine) AnalyticEuropeanEnginePtr; class AnalyticEuropeanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { AnalyticEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new AnalyticEuropeanEnginePtr( new AnalyticEuropeanEngine(bsProcess)); } } }; %{ using QuantLib::IntegralEngine; typedef boost::shared_ptr<PricingEngine> IntegralEnginePtr; %} %rename(IntegralEngine) IntegralEnginePtr; class IntegralEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { IntegralEnginePtr(const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new IntegralEnginePtr(new IntegralEngine(bsProcess)); } } }; %{ using QuantLib::FDBermudanEngine; typedef boost::shared_ptr<PricingEngine> FDBermudanEnginePtr; %} %rename(FDBermudanEngine) FDBermudanEnginePtr; class FDBermudanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDBermudanEnginePtr(const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDBermudanEnginePtr( new FDBermudanEngine(bsProcess,timeSteps, gridPoints,timeDependent)); } } }; %{ using QuantLib::FDEuropeanEngine; typedef boost::shared_ptr<PricingEngine> FDEuropeanEnginePtr; %} %rename(FDEuropeanEngine) FDEuropeanEnginePtr; class FDEuropeanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDEuropeanEnginePtr(const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDEuropeanEnginePtr( new FDEuropeanEngine(bsProcess,timeSteps, gridPoints,timeDependent)); } } }; %{ using QuantLib::BinomialVanillaEngine; using QuantLib::CoxRossRubinstein; using QuantLib::JarrowRudd; using QuantLib::AdditiveEQPBinomialTree; using QuantLib::Trigeorgis; using QuantLib::Tian; using QuantLib::LeisenReimer; using QuantLib::Joshi4; typedef boost::shared_ptr<PricingEngine> BinomialVanillaEnginePtr; %} %rename(BinomialVanillaEngine) BinomialVanillaEnginePtr; class BinomialVanillaEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { BinomialVanillaEnginePtr( const GeneralizedBlackScholesProcessPtr& process, const std::string& type, Size steps) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); std::string s = boost::algorithm::to_lower_copy(type); if (s == "crr" || s == "coxrossrubinstein") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<CoxRossRubinstein>( bsProcess,steps)); else if (s == "jr" || s == "jarrowrudd") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<JarrowRudd>(bsProcess,steps)); else if (s == "eqp" || s == "additiveeqpbinomialtree") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<AdditiveEQPBinomialTree>( bsProcess,steps)); else if (s == "trigeorgis") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<Trigeorgis>(bsProcess,steps)); else if (s == "tian") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<Tian>(bsProcess,steps)); else if (s == "lr" || s == "leisenreimer") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<LeisenReimer>(bsProcess,steps)); else if (s == "j4" || s == "joshi4") return new BinomialVanillaEnginePtr( new BinomialVanillaEngine<Joshi4>(bsProcess,steps)); else QL_FAIL("unknown binomial engine type: "+s); } } }; %{ using QuantLib::MCEuropeanEngine; using QuantLib::PseudoRandom; using QuantLib::LowDiscrepancy; typedef boost::shared_ptr<PricingEngine> MCEuropeanEnginePtr; %} %rename(MCEuropeanEngine) MCEuropeanEnginePtr; class MCEuropeanEnginePtr : public boost::shared_ptr<PricingEngine> { %feature("kwargs") MCEuropeanEnginePtr; public: %extend { MCEuropeanEnginePtr(const GeneralizedBlackScholesProcessPtr& process, const std::string& traits, intOrNull timeSteps = Null<Size>(), intOrNull timeStepsPerYear = Null<Size>(), bool brownianBridge = false, bool antitheticVariate = false, bool controlVariate = false, intOrNull requiredSamples = Null<Size>(), doubleOrNull requiredTolerance = Null<Real>(), intOrNull maxSamples = Null<Size>(), BigInteger seed = 0) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); std::string s = boost::algorithm::to_lower_copy(traits); QL_REQUIRE(Size(timeSteps) != Null<Size>() || Size(timeStepsPerYear) != Null<Size>(), "number of steps not specified"); if (s == "pseudorandom" || s == "pr") return new MCEuropeanEnginePtr( new MCEuropeanEngine<PseudoRandom>(bsProcess, timeSteps, timeStepsPerYear, brownianBridge, antitheticVariate, controlVariate, requiredSamples, requiredTolerance, maxSamples, seed)); else if (s == "lowdiscrepancy" || s == "ld") return new MCEuropeanEnginePtr( new MCEuropeanEngine<LowDiscrepancy>(bsProcess, timeSteps, timeStepsPerYear, brownianBridge, antitheticVariate, controlVariate, requiredSamples, requiredTolerance, maxSamples, seed)); else QL_FAIL("unknown Monte Carlo engine type: "+s); } } }; // American engines %{ using QuantLib::FDAmericanEngine; using QuantLib::FDShoutEngine; typedef boost::shared_ptr<PricingEngine> FDAmericanEnginePtr; typedef boost::shared_ptr<PricingEngine> FDShoutEnginePtr; %} %rename(FDAmericanEngine) FDAmericanEnginePtr; class FDAmericanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDAmericanEnginePtr(const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDAmericanEnginePtr( new FDAmericanEngine(bsProcess,timeSteps, gridPoints,timeDependent)); } } }; %rename(FDShoutEngine) FDShoutEnginePtr; class FDShoutEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDShoutEnginePtr(const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDShoutEnginePtr( new FDShoutEngine(bsProcess,timeSteps, gridPoints,timeDependent)); } } }; %{ using QuantLib::BaroneAdesiWhaleyApproximationEngine; typedef boost::shared_ptr<PricingEngine> BaroneAdesiWhaleyApproximationEnginePtr; %} %rename(BaroneAdesiWhaleyEngine) BaroneAdesiWhaleyApproximationEnginePtr; class BaroneAdesiWhaleyApproximationEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { BaroneAdesiWhaleyApproximationEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new BaroneAdesiWhaleyApproximationEnginePtr( new BaroneAdesiWhaleyApproximationEngine(bsProcess)); } } }; %{ using QuantLib::BjerksundStenslandApproximationEngine; typedef boost::shared_ptr<PricingEngine> BjerksundStenslandApproximationEnginePtr; %} %rename(BjerksundStenslandEngine) BjerksundStenslandApproximationEnginePtr; class BjerksundStenslandApproximationEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { BjerksundStenslandApproximationEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new BjerksundStenslandApproximationEnginePtr( new BjerksundStenslandApproximationEngine(bsProcess)); } } }; %{ using QuantLib::AnalyticDigitalAmericanEngine; typedef boost::shared_ptr<PricingEngine> AnalyticDigitalAmericanEnginePtr; %} %rename(AnalyticDigitalAmericanEngine) AnalyticDigitalAmericanEnginePtr; class AnalyticDigitalAmericanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { AnalyticDigitalAmericanEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new AnalyticDigitalAmericanEnginePtr( new AnalyticDigitalAmericanEngine(bsProcess)); } } }; // Dividend option %{ using QuantLib::DividendVanillaOption; typedef boost::shared_ptr<Instrument> DividendVanillaOptionPtr; %} %rename(DividendVanillaOption) DividendVanillaOptionPtr; class DividendVanillaOptionPtr : public boost::shared_ptr<Instrument> { #if defined(SWIGMZSCHEME) || defined(SWIGGUILE) %rename("dividend-rho") dividendRho; %rename("implied-volatility") impliedVolatility; #endif public: %extend { DividendVanillaOptionPtr( const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise, const std::vector<Date>& dividendDates, const std::vector<Real>& dividends) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new DividendVanillaOptionPtr( new DividendVanillaOption(stPayoff,exercise, dividendDates,dividends)); } Real delta() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->delta(); } Real gamma() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->gamma(); } Real theta() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->theta(); } Real vega() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->vega(); } Real rho() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->rho(); } Real dividendRho() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->dividendRho(); } Real strikeSensitivity() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->strikeSensitivity(); } SampledCurve priceCurve() { return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->result<SampledCurve>("priceCurve"); } Volatility impliedVolatility( Real targetValue, const GeneralizedBlackScholesProcessPtr& process, Real accuracy = 1.0e-4, Size maxEvaluations = 100, Volatility minVol = 1.0e-4, Volatility maxVol = 4.0) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return boost::dynamic_pointer_cast<DividendVanillaOption>(*self) ->impliedVolatility(targetValue, bsProcess, accuracy, maxEvaluations, minVol, maxVol); } } }; %{ using QuantLib::AnalyticDividendEuropeanEngine; typedef boost::shared_ptr<PricingEngine> AnalyticDividendEuropeanEnginePtr; %} %rename(AnalyticDividendEuropeanEngine) AnalyticDividendEuropeanEnginePtr; class AnalyticDividendEuropeanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { AnalyticDividendEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new AnalyticDividendEuropeanEnginePtr( new AnalyticDividendEuropeanEngine(bsProcess)); } } }; %{ using QuantLib::FDDividendEuropeanEngine; using QuantLib::FDDividendAmericanEngine; typedef boost::shared_ptr<PricingEngine> FDDividendEuropeanEnginePtr; typedef boost::shared_ptr<PricingEngine> FDDividendAmericanEnginePtr; %} %rename(FDDividendEuropeanEngine) FDDividendEuropeanEnginePtr; class FDDividendEuropeanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDDividendEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDDividendEuropeanEnginePtr( new FDDividendEuropeanEngine(bsProcess,timeSteps, gridPoints, timeDependent)); } } }; %rename(FDDividendAmericanEngine) FDDividendAmericanEnginePtr; class FDDividendAmericanEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { FDDividendAmericanEnginePtr( const GeneralizedBlackScholesProcessPtr& process, Size timeSteps = 100, Size gridPoints = 100, bool timeDependent = false) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new FDDividendAmericanEnginePtr( new FDDividendAmericanEngine(bsProcess,timeSteps, gridPoints, timeDependent)); } } }; // Barrier option %{ using QuantLib::BarrierOption; typedef boost::shared_ptr<Instrument> BarrierOptionPtr; %} %rename(BarrierOption) BarrierOptionPtr; class BarrierOptionPtr : public boost::shared_ptr<Instrument> { #if defined(SWIGMZSCHEME) || defined(SWIGGUILE) %rename("dividend-rho") dividendRho; %rename("implied-volatility") impliedVolatility; #endif public: %extend { BarrierOptionPtr( Barrier::Type barrierType, Real barrier, Real rebate, const boost::shared_ptr<Payoff>& payoff, const boost::shared_ptr<Exercise>& exercise) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new BarrierOptionPtr( new BarrierOption(barrierType, barrier, rebate, stPayoff,exercise)); } Real delta() { return boost::dynamic_pointer_cast<BarrierOption>(*self)->delta(); } Real gamma() { return boost::dynamic_pointer_cast<BarrierOption>(*self)->gamma(); } Real theta() { return boost::dynamic_pointer_cast<BarrierOption>(*self)->theta(); } Real vega() { return boost::dynamic_pointer_cast<BarrierOption>(*self)->vega(); } Real rho() { return boost::dynamic_pointer_cast<BarrierOption>(*self)->rho(); } Real dividendRho() { return boost::dynamic_pointer_cast<BarrierOption>(*self) ->dividendRho(); } Real strikeSensitivity() { return boost::dynamic_pointer_cast<BarrierOption>(*self) ->strikeSensitivity(); } SampledCurve priceCurve() { return boost::dynamic_pointer_cast<BarrierOption>(*self) ->result<SampledCurve>("priceCurve"); } Volatility impliedVolatility( Real targetValue, const GeneralizedBlackScholesProcessPtr& process, Real accuracy = 1.0e-4, Size maxEvaluations = 100, Volatility minVol = 1.0e-4, Volatility maxVol = 4.0) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return boost::dynamic_pointer_cast<BarrierOption>(*self) ->impliedVolatility(targetValue, bsProcess, accuracy, maxEvaluations, minVol, maxVol); } } }; // Barrier engines %{ using QuantLib::AnalyticBarrierEngine; typedef boost::shared_ptr<PricingEngine> AnalyticBarrierEnginePtr; %} %rename(AnalyticBarrierEngine) AnalyticBarrierEnginePtr; class AnalyticBarrierEnginePtr : public boost::shared_ptr<PricingEngine> { public: %extend { AnalyticBarrierEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new AnalyticBarrierEnginePtr( new AnalyticBarrierEngine(bsProcess)); } } }; %{ using QuantLib::MCBarrierEngine; typedef boost::shared_ptr<PricingEngine> MCBarrierEnginePtr; %} %rename(MCBarrierEngine) MCBarrierEnginePtr; class MCBarrierEnginePtr : public boost::shared_ptr<PricingEngine> { %feature("kwargs") MCBarrierEnginePtr; public: %extend { MCBarrierEnginePtr(const GeneralizedBlackScholesProcessPtr& process, const std::string& traits, Size timeStepsPerYear = Null<Size>(), bool brownianBridge = false, bool antitheticVariate = false, bool controlVariate = false, intOrNull requiredSamples = Null<Size>(), doubleOrNull requiredTolerance = Null<Real>(), intOrNull maxSamples = Null<Size>(), bool isBiased = false, BigInteger seed = 0) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); std::string s = boost::algorithm::to_lower_copy(traits); if (s == "pseudorandom" || s == "pr") return new MCBarrierEnginePtr( new MCBarrierEngine<PseudoRandom>(bsProcess, timeStepsPerYear, brownianBridge, antitheticVariate, controlVariate, requiredSamples, requiredTolerance, maxSamples, isBiased, seed)); else if (s == "lowdiscrepancy" || s == "ld") return new MCBarrierEnginePtr( new MCBarrierEngine<LowDiscrepancy>(bsProcess, timeStepsPerYear, brownianBridge, antitheticVariate, controlVariate, requiredSamples, requiredTolerance, maxSamples, isBiased, seed)); else QL_FAIL("unknown Monte Carlo engine type: "+s); } } }; %{ using QuantLib::QuantoEngine; using QuantLib::ForwardVanillaEngine; typedef boost::shared_ptr<PricingEngine> ForwardEuropeanEnginePtr; typedef boost::shared_ptr<PricingEngine> QuantoEuropeanEnginePtr; typedef boost::shared_ptr<PricingEngine> QuantoForwardEuropeanEnginePtr; %} %rename(ForwardEuropeanEngine) ForwardEuropeanEnginePtr; class ForwardEuropeanEnginePtr: public boost::shared_ptr<PricingEngine> { public: %extend { ForwardEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new ForwardEuropeanEnginePtr( new ForwardVanillaEngine<AnalyticEuropeanEngine>(bsProcess)); } } }; %rename(QuantoEuropeanEngine) QuantoEuropeanEnginePtr; class QuantoEuropeanEnginePtr: public boost::shared_ptr<PricingEngine> { public: %extend { QuantoEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process, const Handle<YieldTermStructure>& foreignRiskFreeRate, const Handle<BlackVolTermStructure>& exchangeRateVolatility, const Handle<Quote>& correlation) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new QuantoEuropeanEnginePtr( new QuantoEngine<VanillaOption,AnalyticEuropeanEngine>( bsProcess, foreignRiskFreeRate, exchangeRateVolatility, correlation)); } } }; %rename(QuantoForwardEuropeanEngine) QuantoForwardEuropeanEnginePtr; class QuantoForwardEuropeanEnginePtr: public boost::shared_ptr<PricingEngine> { public: %extend { QuantoForwardEuropeanEnginePtr( const GeneralizedBlackScholesProcessPtr& process, const Handle<YieldTermStructure>& foreignRiskFreeRate, const Handle<BlackVolTermStructure>& exchangeRateVolatility, const Handle<Quote>& correlation) { boost::shared_ptr<GeneralizedBlackScholesProcess> bsProcess = boost::dynamic_pointer_cast<GeneralizedBlackScholesProcess>( process); QL_REQUIRE(bsProcess, "Black-Scholes process required"); return new QuantoForwardEuropeanEnginePtr( new QuantoEngine<ForwardVanillaOption,AnalyticEuropeanEngine>( bsProcess, foreignRiskFreeRate, exchangeRateVolatility, correlation)); } } }; %{ using QuantLib::BlackCalculator; %} class BlackCalculator { public: Real value() const; Real deltaForward() const; virtual Real delta(Real spot) const; Real elasticityForward() const; virtual Real elasticity(Real spot) const; Real gammaForward() const; virtual Real gamma(Real spot) const; virtual Real theta(Real spot, Time maturity) const; virtual Real thetaPerDay(Real spot, Time maturity) const; Real vega(Time maturity) const; Real rho(Time maturity) const; Real dividendRho(Time maturity) const; Real itmCashProbability() const; Real itmAssetProbability() const; Real strikeSensitivity() const; Real alpha() const; Real beta() const; %extend { BlackCalculator ( const boost::shared_ptr<Payoff>& payoff, Real forward, Real stdDev, Real discount = 1.0) { boost::shared_ptr<StrikedTypePayoff> stPayoff = boost::dynamic_pointer_cast<StrikedTypePayoff>(payoff); QL_REQUIRE(stPayoff, "wrong payoff given"); return new BlackCalculator(stPayoff,forward,stdDev,discount); } } }; #endif ---- montecarlo.i ---- /* Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2003, 2004, 2005 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[hidden email]>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef quantlib_montecarlo_tools_i #define quantlib_montecarlo_tools_i %include stochasticprocess.i %include linearalgebra.i %include randomnumbers.i %include types.i #if defined(SWIGMZSCHEME) || defined(SWIGGUILE) %rename("get-covariance") getCovariance; #endif %inline %{ Matrix getCovariance(const Array& volatilities, const Matrix& correlations) { return QuantLib::getCovariance(volatilities.begin(), volatilities.end(), correlations); } %} %{ using QuantLib::Path; %} #if defined(SWIGRUBY) %mixin Path "Enumerable"; #endif class Path { #if defined(SWIGPYTHON) || defined(SWIGRUBY) %rename(__len__) length; #endif private: Path(); public: Size length() const; Real value(Size i) const; Real front() const; Time time(Size i) const; %extend { #if defined(SWIGPYTHON) || defined(SWIGRUBY) Real __getitem__(Integer i) { Integer size_ = Integer(self->length()); if (i>=0 && i<size_) { return (*self)[i]; } else if (i<0 && -i<=size_) { return (*self)[size_+i]; } else { throw std::out_of_range("path index out of range"); } } #elif defined(SWIGMZSCHEME) || defined(SWIGGUILE) Real ref(Size i) { if (i<self->length()) { return (*self)[i]; } else { throw std::out_of_range("path index out of range"); } } #endif #if defined(SWIGRUBY) void each() { for (Size i=0; i<self->length(); i++) rb_yield(rb_float_new((*self)[i])); } #elif defined(SWIGMZSCHEME) void for_each(Scheme_Object* proc) { for (Size i=0; i<self->length(); ++i) { Scheme_Object* x = scheme_make_double((*self)[i]); scheme_apply(proc,1,&x); } } #elif defined(SWIGGUILE) void for_each(SCM proc) { for (Size i=0; i<self->length(); ++i) { SCM x = gh_double2scm((*self)[i]); gh_call1(proc,x); } } #endif } }; %{ typedef QuantLib::PathGenerator<GaussianRandomSequenceGenerator> GaussianPathGenerator; %} %template(SamplePath) Sample<Path>; class GaussianPathGenerator { public: %extend { GaussianPathGenerator(const StochasticProcess1DPtr& process, Time length, Size steps, const GaussianRandomSequenceGenerator& rsg, bool brownianBridge) { boost::shared_ptr<StochasticProcess1D> process1d = boost::dynamic_pointer_cast<StochasticProcess1D>(process); return new GaussianPathGenerator(process1d,length,steps, rsg,brownianBridge); } } Sample<Path> next() const; Sample<Path> antithetic() const; }; %{ typedef QuantLib::PathGenerator<GaussianLowDiscrepancySequenceGenerator> GaussianSobolPathGenerator; %} class GaussianSobolPathGenerator { public: %extend { GaussianSobolPathGenerator(const StochasticProcess1DPtr& process, Time length, Size steps, const GaussianLowDiscrepancySequenceGenerator& rsg, bool brownianBridge) { boost::shared_ptr<StochasticProcess1D> process1d = boost::dynamic_pointer_cast<StochasticProcess1D>(process); return new GaussianSobolPathGenerator(process1d,length,steps, rsg,brownianBridge); } } Sample<Path> next() const; Sample<Path> antithetic() const; }; %{ using QuantLib::MultiPath; %} class MultiPath { #if defined(SWIGPYTHON) || defined(SWIGRUBY) %rename(__len__) pathSize; #elif defined(SWIGMZSCHEME) || defined(SWIGGUILE) %rename("length") pathSize; %rename("asset-number") assetNumber; #endif private: MultiPath(); public: Size pathSize() const; Size assetNumber() const; %extend { #if defined(SWIGPYTHON) || defined(SWIGRUBY) const Path& __getitem__(Integer i) { Integer assets_ = Integer(self->assetNumber()); if (i>=0 && i<assets_) { return (*self)[i]; } else if (i<0 && -i<=assets_) { return (*self)[assets_+i]; } else { throw std::out_of_range("multi-path index out of range"); } } #elif defined(SWIGMZSCHEME) || defined(SWIGGUILE) Real ref(Size i, Size j) { if (i<self->assetNumber() && j<self->pathSize()) { return (*self)[i][j]; } else { throw std::out_of_range("multi-path index out of range"); } } #endif #if defined(SWIGRUBY) void each_path() { for (Size i=0; i<self->assetNumber(); i++) rb_yield(SWIG_NewPointerObj(&((*self)[i]), $descriptor(Path *), 0)); } void each_step() { for (Size j=0; j<self->pathSize(); j++) { VALUE v = rb_ary_new2(self->assetNumber()); for (Size i=0; i<self->assetNumber(); i++) rb_ary_store(v,i,rb_float_new((*self)[i][j])); rb_yield(v); } } #elif defined(SWIGMZSCHEME) void for_each_path(Scheme_Object* proc) { for (Size i=0; i<self->assetNumber(); i++) { Scheme_Object* x = SWIG_NewPointerObj(&((*self)[i]), $descriptor(Path *), 0); scheme_apply(proc,1,&x); } } void for_each_step(Scheme_Object* proc) { for (Size j=0; j<self->pathSize(); j++) { Scheme_Object* v = scheme_make_vector(self->assetNumber(), scheme_undefined); Scheme_Object** els = SCHEME_VEC_ELS(v); for (Size i=0; i<self->assetNumber(); i++) els[i] = scheme_make_double((*self)[i][j]); scheme_apply(proc,1,&v); } } #elif defined(SWIGGUILE) void for_each_path(SCM proc) { for (Size i=0; i<self->assetNumber(); ++i) { SCM x = SWIG_NewPointerObj(&((*self)[i]), $descriptor(Path *), 0); gh_call1(proc,x); } } void for_each_step(SCM proc) { for (Size j=0; j<self->pathSize(); ++j) { SCM v = gh_make_vector(gh_long2scm(self->assetNumber()), SCM_UNSPECIFIED); for (Size i=0; i<self->assetNumber(); i++) { gh_vector_set_x(v,gh_long2scm(i), gh_double2scm((*self)[i][j])); } gh_call1(proc,v); } } #endif } }; %{ typedef QuantLib::MultiPathGenerator<GaussianRandomSequenceGenerator> GaussianMultiPathGenerator; %} %template(SampleMultiPath) Sample<MultiPath>; class GaussianMultiPathGenerator { public: %extend { GaussianMultiPathGenerator( const boost::shared_ptr<StochasticProcess>& process, const std::vector<Time>& times, const GaussianRandomSequenceGenerator& generator, bool brownianBridge = false) { return new GaussianMultiPathGenerator(process, QuantLib::TimeGrid( times.begin(), times.end()), generator, brownianBridge); } } Sample<MultiPath> next() const; }; #endif ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/ _______________________________________________ QuantLib-dev mailing list [hidden email] https://lists.sourceforge.net/lists/listinfo/quantlib-dev |
Free forum by Nabble | Edit this page |