本文整理汇总了C#中InitializedList类的典型用法代码示例。如果您正苦于以下问题:C# InitializedList类的具体用法?C# InitializedList怎么用?C# InitializedList使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
InitializedList类属于命名空间,在下文中一共展示了InitializedList类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: expectedCashflows
//public List<CashFlow> interestCashflows()
//{
// List<CashFlow> icf = new List<CashFlow>();
// foreach (CashFlow cf in cashflows())
// {
// if (cf is QLNet.FixedRateCoupon)
// icf.Add(cf);
// }
// return icf;
//}
public List<CashFlow> expectedCashflows()
{
calcBondFactor();
List<CashFlow> expectedcashflows = new List<CashFlow>();
List<double> notionals = new InitializedList<double>(schedule_.Count);
notionals[0] = notionals_[0];
for (int i = 0; i < schedule_.Count - 1; ++i)
{
double currentNotional = notionals[i];
double smm = SMM(schedule_[i]);
double prepay = (notionals[i] * bondFactors_[i + 1]) / bondFactors_[i] * smm;
double actualamort = currentNotional * (1 - bondFactors_[i + 1] / bondFactors_[i]);
notionals[i + 1] = currentNotional - actualamort - prepay;
// ADD
CashFlow c1 = new VoluntaryPrepay(prepay, schedule_[i + 1]);
CashFlow c2 = new AmortizingPayment(actualamort, schedule_[i + 1]);
CashFlow c3 = new FixedRateCoupon(currentNotional, schedule_[i + 1], new InterestRate(PassThroughRate_, dCounter_, Compounding.Simple), schedule_[i], schedule_[i + 1]);
expectedcashflows.Add(c1);
expectedcashflows.Add(c2);
expectedcashflows.Add(c3);
}
notionals[notionals.Count - 1] = 0.0;
return expectedcashflows;
}
开发者ID:minikie,项目名称:OTCDerivativesCalculatorModule,代码行数:40,代码来源:MBSFixedRateBond.cs
示例2: Loan
public Loan(int legs)
{
legs_ = new InitializedList<List<CashFlow>>(legs);
payer_ = new InitializedList<double>(legs);
notionals_ = new List<double>();
legNPV_ = new InitializedList<double?>(legs);
}
开发者ID:ariesy,项目名称:QLNet,代码行数:7,代码来源:Loan.cs
示例3: AmericanExercise
public AmericanExercise(Date latest, bool payoffAtExpiry)
: base(Type.American, payoffAtExpiry)
{
dates_ = new InitializedList<Date>(2);
dates_[0] = Date.minDate();
dates_[1] = latest;
}
开发者ID:ammachado,项目名称:QLNet,代码行数:7,代码来源:Exercise.cs
示例4: initialize
private void initialize()
{
// firstSeed is chosen based on clock() and used for the first rng
ulong firstSeed = (ulong)DateTime.Now.Ticks; // (std::time(0));
MersenneTwisterUniformRng first = new MersenneTwisterUniformRng(firstSeed);
// secondSeed is as random as it could be
// feel free to suggest improvements
ulong secondSeed = first.nextInt32();
MersenneTwisterUniformRng second = new MersenneTwisterUniformRng(secondSeed);
// use the second rng to initialize the final one
ulong skip = second.nextInt32() % 1000;
List<ulong> init = new InitializedList<ulong>(4);
init[0]=second.nextInt32();
init[1]=second.nextInt32();
init[2]=second.nextInt32();
init[3]=second.nextInt32();
rng_ = new MersenneTwisterUniformRng(init);
for (ulong i=0; i<skip ; i++)
rng_.nextInt32();
}
开发者ID:ariesy,项目名称:QLNet,代码行数:25,代码来源:seedgenerator.cs
示例5: minimize
public override EndCriteria.Type minimize(Problem P, EndCriteria endCriteria) {
EndCriteria.Type ecType = EndCriteria.Type.None;
P.reset();
Vector x_ = P.currentValue();
currentProblem_ = P;
initCostValues_ = P.costFunction().values(x_);
int m = initCostValues_.size();
int n = x_.size();
Vector xx = new Vector(x_);
Vector fvec = new Vector(m), diag = new Vector(n);
int mode = 1;
double factor = 1;
int nprint = 0;
int info = 0;
int nfev =0;
Matrix fjac = new Matrix(m, n);
int ldfjac = m;
List<int> ipvt = new InitializedList<int>(n);
Vector qtf = new Vector(n), wa1 = new Vector(n), wa2 = new Vector(n), wa3 = new Vector(n), wa4 = new Vector(m);
// call lmdif to minimize the sum of the squares of m functions
// in n variables by the Levenberg-Marquardt algorithm.
MINPACK.lmdif(m, n, xx, ref fvec,
endCriteria.functionEpsilon(),
xtol_,
gtol_,
endCriteria.maxIterations(),
epsfcn_,
diag, mode, factor,
nprint, ref info, ref nfev, ref fjac,
ldfjac, ref ipvt, ref qtf,
wa1, wa2, wa3, wa4,
fcn);
info_ = info;
// check requirements & endCriteria evaluation
if(info == 0) throw new ApplicationException("MINPACK: improper input parameters");
//if(info == 6) throw new ApplicationException("MINPACK: ftol is too small. no further " +
// "reduction in the sum of squares is possible.");
if (info != 6) ecType = EndCriteria.Type.StationaryFunctionValue;
//QL_REQUIRE(info != 5, "MINPACK: number of calls to fcn has reached or exceeded maxfev.");
endCriteria.checkMaxIterations(nfev, ref ecType);
if(info == 7) throw new ApplicationException("MINPACK: xtol is too small. no further " +
"improvement in the approximate " +
"solution x is possible.");
if(info == 8) throw new ApplicationException("MINPACK: gtol is too small. fvec is " +
"orthogonal to the columns of the " +
"jacobian to machine precision.");
// set problem
x_ = new Vector(xx.GetRange(0, n));
P.setCurrentValue(x_);
P.setFunctionValue(P.costFunction().value(x_));
return ecType;
}
开发者ID:akasolace,项目名称:qlnet,代码行数:60,代码来源:levenbergmarquardt.cs
示例6: multiPathBasisSystem
public static List<Func<Vector, double>> multiPathBasisSystem(int dim, int order, PolynomType polynomType)
{
List<Func<double, double>> b = pathBasisSystem(order, polynomType);
List<Func<Vector, double>> ret = new List<Func<Vector,double>>();
ret.Add((xx) => 1.0);
for (int i=1; i<=order; ++i) {
List<Func<Vector, double>> a = w(dim, i, polynomType, b);
foreach (var iter in a) {
ret.Add(iter);
}
}
// remove-o-zap: now remove redundant functions.
// usually we do have a lot of them due to the construction schema.
// We use a more "hands on" method here.
List<bool> rm = new InitializedList<bool>(ret.Count, true);
Vector x = new Vector(dim), v = new Vector(ret.Count);
MersenneTwisterUniformRng rng = new MersenneTwisterUniformRng(1234UL);
for (int i=0; i<10; ++i) {
int k;
// calculate random x vector
for (k=0; k<dim; ++k) {
x[k] = rng.next().value;
}
// get return values for all basis functions
for (k = 0; k < ret.Count; ++k) {
v[k] = ret[k](x);
}
// find duplicates
for (k = 0; k < ret.Count; ++k) {
if (v.First(xx => (Math.Abs(v[k] - xx) <= 10*v[k]*Const.QL_Epsilon)) == v.First() + k) {
// don't remove this item, it's unique!
rm[k] = false;
}
}
}
int iter2 = 0;
for (int i = 0; i < rm.Count; ++i) {
if (rm[i]) {
ret.RemoveAt(iter2);
}
else {
++iter2;
}
}
return ret;
}
开发者ID:tickzoom,项目名称:QLNet,代码行数:57,代码来源:lsmbasissystem.cs
示例7: value
public override double value(double x, double y)
{
List<double> section = new InitializedList<double>( splines_.Count );
for (int i=0; i<splines_.Count; i++)
section[i]=splines_[i].value(x,true);
CubicInterpolation spline = new CubicInterpolation(this.yBegin_, this.ySize_, section,
CubicInterpolation.DerivativeApprox.Spline, false,
CubicInterpolation.BoundaryCondition.SecondDerivative, 0.0,
CubicInterpolation.BoundaryCondition.SecondDerivative, 0.0);
return spline.value(y,true);
}
开发者ID:akasolace,项目名称:qlnet,代码行数:12,代码来源:BicubicSplineInterpolation.cs
示例8: BrownianBridge
//! generic times
/*! \note the starting time of the path is assumed to be 0 and must not be included */
public BrownianBridge(List<double> times) {
size_ = times.Count;
t_ = new InitializedList<double>(size_);
sqrtdt_ = new InitializedList<double>(size_);
bridgeIndex_ = new InitializedList<int>(size_);
leftIndex_ = new InitializedList<int>(size_);
rightIndex_ = new InitializedList<int>(size_);
leftWeight_ = new InitializedList<double>(size_);
rightWeight_ = new InitializedList<double>(size_);
stdDev_ = new InitializedList<double>(size_);
initialize();
}
开发者ID:akasolace,项目名称:qlnet,代码行数:14,代码来源:brownianbridge.cs
示例9: secondDerivativeX
public double secondDerivativeX(double x, double y)
{
List<double> section = new InitializedList<double>( this.zData_.columns() );
for (int i=0; i < section.Count; ++i)
{
section[i] = value(this.xBegin_[i], y);
}
return new CubicInterpolation( this.xBegin_, this.xSize_, section,
CubicInterpolation.DerivativeApprox.Spline, false,
CubicInterpolation.BoundaryCondition.SecondDerivative, 0.0,
CubicInterpolation.BoundaryCondition.SecondDerivative, 0.0).secondDerivative(x);
}
开发者ID:akasolace,项目名称:qlnet,代码行数:13,代码来源:BicubicSplineInterpolation.cs
示例10: computeSimplexSize
// Computes the size of the simplex
public static double computeSimplexSize(InitializedList<Vector> vertices)
{
Vector center = new Vector(vertices[0].Count, 0);
for (int i = 0; i < vertices.Count; ++i)
center += vertices[i];
center *= 1 / (double)(vertices.Count);
double result = 0;
for (int i = 0; i < vertices.Count; ++i)
{
Vector temp = vertices[i] - center;
result += Math.Sqrt(Vector.DotProduct(temp, temp));
}
return result / (double)(vertices.Count);
}
开发者ID:akasolace,项目名称:qlnet,代码行数:15,代码来源:Simplex.cs
示例11: DiscretizedSwaption
public DiscretizedSwaption(Swaption.Arguments args,
Date referenceDate,
DayCounter dayCounter)
: base(new DiscretizedSwap(args, referenceDate, dayCounter), args.exercise.type(), new List<double>())
{
arguments_=args;
exerciseTimes_ = new InitializedList<double>(arguments_.exercise.dates().Count);
for (int i = 0; i < exerciseTimes_.Count; ++i)
exerciseTimes_[i] =
dayCounter.yearFraction(referenceDate,
arguments_.exercise.date(i));
// Date adjustments can get time vectors out of synch.
// Here, we try and collapse similar dates which could cause
// a mispricing.
for (int i=0; i<arguments_.exercise.dates().Count; i++) {
Date exerciseDate = arguments_.exercise.date(i);
for (int j = 0; j < arguments_.fixedPayDates.Count; j++) {
if (withinNextWeek(exerciseDate,
arguments_.fixedPayDates[j])
// coupons in the future are dealt with below
&& arguments_.fixedResetDates[j] < referenceDate)
arguments_.fixedPayDates[j] = exerciseDate;
}
for (int j = 0; j < arguments_.fixedResetDates.Count; j++) {
if (withinPreviousWeek(exerciseDate,
arguments_.fixedResetDates[j]))
arguments_.fixedResetDates[j] = exerciseDate;
}
for (int j = 0; j < arguments_.floatingResetDates.Count; j++) {
if (withinPreviousWeek(exerciseDate,
arguments_.floatingResetDates[j]))
arguments_.floatingResetDates[j] = exerciseDate;
}
}
double lastFixedPayment =
dayCounter.yearFraction(referenceDate,
arguments_.fixedPayDates.Last() );
double lastFloatingPayment =
dayCounter.yearFraction(referenceDate,
arguments_.floatingPayDates.Last());
lastPayment_ = Math.Max(lastFixedPayment,lastFloatingPayment);
underlying_ = new DiscretizedSwap(arguments_,
referenceDate,
dayCounter);
}
开发者ID:akasolace,项目名称:qlnet,代码行数:49,代码来源:discretizedswaption.cs
示例12: test1dLinearRegression
public void test1dLinearRegression()
{
//BOOST_MESSAGE("Testing 1d simple linear least-squares regression...");
/* Example taken from the QuantLib-User list, see posting
* Multiple linear regression/weighted regression, Boris Skorodumov */
//SavedSettings backup;
List<double> x = new InitializedList<double>(9),
y = new InitializedList<double>(9);
x[0] = 2.4; x[1] = 1.8; x[2] = 2.5; x[3] = 3.0;
x[4] = 2.1; x[5] = 1.2; x[6] = 2.0; x[7] = 2.7; x[8] = 3.6;
y[0] = 7.8; y[1] = 5.5; y[2] = 8.0; y[3] = 9.0;
y[4] = 6.5; y[5] = 4.0; y[6] = 6.3; y[7] = 8.4; y[8] = 10.2;
List<Func<double, double>> v = new List<Func<double, double>>();
v.Add(a => 1.0);
v.Add(a => a);
LinearRegression m = new LinearRegression(x, y);
const double tol = 0.0002;
double[] coeffExpected = new double[] { 0.9448, 2.6853 };
double[] errorsExpected = new double[] { 0.3654, 0.1487 };
for (int i = 0; i < 2; ++i) {
if (Math.Abs(m.standardErrors()[i] - errorsExpected[i]) > tol) {
Assert.Fail("Failed to reproduce linear regression standard errors"
+ "\n calculated: " + m.standardErrors()[i]
+ "\n expected: " + errorsExpected[i]
+ "\n tolerance: " + tol);
}
if (Math.Abs(m.coefficients()[i] - coeffExpected[i]) > tol) {
Assert.Fail("Failed to reproduce linear regression coef."
+ "\n calculated: " + m.coefficients()[i]
+ "\n expected: " + coeffExpected[i]
+ "\n tolerance: " + tol);
}
}
}
开发者ID:ariesy,项目名称:QLNet,代码行数:43,代码来源:T_LinearLeastSquaresRegression.cs
示例13: fetchResults
public override void fetchResults(IPricingEngineResults r)
{
base.fetchResults(r);
LoanPricingEngineResults results = r as LoanPricingEngineResults;
if (results == null) throw new ArgumentException("wrong result type");
if (results.legNPV.Count != 0)
{
if (results.legNPV.Count != legNPV_.Count)
{
throw new ArgumentException("wrong number of leg NPV returned");
}
legNPV_ = results.legNPV;
}
else
{
legNPV_ = new InitializedList<double?>(legNPV_.Count);
}
}
开发者ID:ariesy,项目名称:QLNet,代码行数:21,代码来源:Loan.cs
示例14: MersenneTwisterUniformRng
public MersenneTwisterUniformRng(List<ulong> seeds) {
mt = new InitializedList<ulong>(N);
seedInitialization(19650218UL);
int i = 1, j = 0, k = (N > seeds.Count ? N : seeds.Count);
for (; k!=0; k--) {
mt[i] = (mt[i] ^ ((mt[i - 1] ^ (mt[i - 1] >> 30)) * 1664525UL)) + seeds[j] + (ulong)j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=seeds.Count) j=0;
}
for (k=N-1; k!=0; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - (ulong)i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /*MSB is 1; assuring non-zero initial array*/
}
开发者ID:akasolace,项目名称:qlnet,代码行数:21,代码来源:mt19937uniformrng.cs
示例15: calculate
// Instrument interface
public override void calculate() {
if (discountCurve_.empty()) throw new ArgumentException("no discounting term structure set");
results_.value = results_.cash = 0;
results_.errorEstimate = null;
results_.legNPV = new InitializedList<double?>(arguments_.legs.Count);
results_.legBPS = new InitializedList<double?>(arguments_.legs.Count);
List<double?> startDiscounts = new InitializedList<double?>(arguments_.legs.Count);
for (int i=0; i<arguments_.legs.Count; ++i) {
results_.legNPV[i] = arguments_.payer[i] * CashFlows.npv(arguments_.legs[i], discountCurve_);
results_.legBPS[i] = arguments_.payer[i] * CashFlows.bps(arguments_.legs[i], discountCurve_);
results_.value += results_.legNPV[i];
results_.cash += arguments_.payer[i] * CashFlows.cash(arguments_.legs[i]);
try {
Date d = CashFlows.startDate(arguments_.legs[i]);
startDiscounts[i] = discountCurve_.link.discount(d);
} catch {
startDiscounts[i] = null;
}
}
results_.additionalResults.Add("startDiscounts", startDiscounts);
}
开发者ID:minikie,项目名称:OTCDerivativesCalculatorModule,代码行数:23,代码来源:Discountingswapengine.cs
示例16: update
public override void update()
{
Vector tmp = new Vector(size_);
List<double> dx = new InitializedList<double>(size_ - 1),
S = new InitializedList<double>(size_ - 1);
for (int i = 0; i < size_ - 1; ++i) {
dx[i] = xBegin_[i+1] - xBegin_[i];
S[i] = (yBegin_[i+1] - yBegin_[i])/dx[i];
}
// first derivative approximation
if (da_==CubicInterpolation.DerivativeApprox.Spline) {
TridiagonalOperator L = new TridiagonalOperator(size_);
for (int i = 1; i < size_ - 1; ++i) {
L.setMidRow(i, dx[i], 2.0*(dx[i]+dx[i-1]), dx[i-1]);
tmp[i] = 3.0*(dx[i]*S[i-1] + dx[i-1]*S[i]);
}
// left boundary condition
switch (leftType_) {
case CubicInterpolation.BoundaryCondition.NotAKnot:
// ignoring end condition value
L.setFirstRow(dx[1]*(dx[1]+dx[0]), (dx[0]+dx[1])*(dx[0]+dx[1]));
tmp[0] = S[0]*dx[1]*(2.0*dx[1]+3.0*dx[0]) + S[1]*dx[0]*dx[0];
break;
case CubicInterpolation.BoundaryCondition.FirstDerivative:
L.setFirstRow(1.0, 0.0);
tmp[0] = leftValue_;
break;
case CubicInterpolation.BoundaryCondition.SecondDerivative:
L.setFirstRow(2.0, 1.0);
tmp[0] = 3.0*S[0] - leftValue_*dx[0]/2.0;
break;
case CubicInterpolation.BoundaryCondition.Periodic:
case CubicInterpolation.BoundaryCondition.Lagrange:
// ignoring end condition value
throw new NotImplementedException("this end condition is not implemented yet");
default:
throw new ArgumentException("unknown end condition");
}
// right boundary condition
switch (rightType_) {
case CubicInterpolation.BoundaryCondition.NotAKnot:
// ignoring end condition value
L.setLastRow(-(dx[size_ - 2] + dx[size_ - 3]) * (dx[size_ - 2] + dx[size_ - 3]),
-dx[size_ - 3] * (dx[size_ - 3] + dx[size_ - 2]));
tmp[size_ - 1] = -S[size_ - 3] * dx[size_ - 2] * dx[size_ - 2] -
S[size_ - 2] * dx[size_ - 3] * (3.0 * dx[size_ - 2] + 2.0 * dx[size_ - 3]);
break;
case CubicInterpolation.BoundaryCondition.FirstDerivative:
L.setLastRow(0.0, 1.0);
tmp[size_ - 1] = rightValue_;
break;
case CubicInterpolation.BoundaryCondition.SecondDerivative:
L.setLastRow(1.0, 2.0);
tmp[size_ - 1] = 3.0 * S[size_ - 2] + rightValue_ * dx[size_ - 2] / 2.0;
break;
case CubicInterpolation.BoundaryCondition.Periodic:
case CubicInterpolation.BoundaryCondition.Lagrange:
// ignoring end condition value
throw new NotImplementedException("this end condition is not implemented yet");
default:
throw new ArgumentException("unknown end condition");
}
// solve the system
tmp = L.solveFor(tmp);
} else { // local schemes
if (size_ == 2)
tmp[0] = tmp[1] = S[0];
else {
switch (da_) {
case CubicInterpolation.DerivativeApprox.FourthOrder:
throw new NotImplementedException("FourthOrder not implemented yet");
break;
case CubicInterpolation.DerivativeApprox.Parabolic:
// intermediate points
for (int i = 1; i < size_ - 1; ++i) {
tmp[i] = (dx[i - 1] * S[i] + dx[i] * S[i - 1]) / (dx[i] + dx[i - 1]);
}
// end points
tmp[0] = ((2.0 * dx[0] + dx[1]) * S[0] - dx[0] * S[1]) / (dx[0] + dx[1]);
tmp[size_ - 1] = ((2.0 * dx[size_ - 2] + dx[size_ - 3]) * S[size_ - 2] - dx[size_ - 2] * S[size_ - 3]) / (dx[size_ - 2] + dx[size_ - 3]);
break;
break;
case CubicInterpolation.DerivativeApprox.FritschButland:
// intermediate points
for (int i=1; i<size_-1; ++i) {
double Smin = Math.Min(S[i-1], S[i]);
double Smax = Math.Max(S[i-1], S[i]);
tmp[i] = 3.0*Smin*Smax/(Smax+2.0*Smin);
}
// end points
tmp[0] = ((2.0*dx[ 0]+dx[ 1])*S[ 0] - dx[ 0]*S[ 1]) / (dx[ 0]+dx[ 1]);
tmp[size_-1] = ((2.0*dx[size_-2]+dx[size_-3])*S[size_-2] - dx[size_-2]*S[size_-3]) / (dx[size_-2]+dx[size_-3]);
break;
case CubicInterpolation.DerivativeApprox.Akima:
throw new NotImplementedException("Akima not implemented yet");
//.........这里部分代码省略.........
开发者ID:StreetConnect,项目名称:QLNet,代码行数:101,代码来源:CubicInterpolation.cs
示例17: CubicInterpolationImpl
public CubicInterpolationImpl(List<double> xBegin, int size, List<double> yBegin,
CubicInterpolation.DerivativeApprox da,
bool monotonic,
CubicInterpolation.BoundaryCondition leftCondition,
double leftConditionValue,
CubicInterpolation.BoundaryCondition rightCondition,
double rightConditionValue)
: base(xBegin, size, yBegin)
{
da_ = da;
monotonic_ = monotonic;
leftType_ = leftCondition;
rightType_ = rightCondition;
leftValue_ = leftConditionValue;
rightValue_ = rightConditionValue;
// coefficients
primitiveConst_ = new InitializedList<double>(size - 1);
a_ = new InitializedList<double>(size - 1);
b_ = new InitializedList<double>(size - 1);
c_ = new InitializedList<double>(size - 1);
monotonicityAdjustments_ = new InitializedList<bool>(size);
}
开发者ID:StreetConnect,项目名称:QLNet,代码行数:23,代码来源:CubicInterpolation.cs
示例18: sinkingNotionals
protected List<double> sinkingNotionals(Period maturityTenor,
Frequency sinkingFrequency,
double couponRate,
double initialNotional)
{
Period freqPeriod = new Period(sinkingFrequency);
int nPeriods = 0;
Utils.QL_REQUIRE(isSubPeriod(freqPeriod, maturityTenor, out nPeriods),() =>
"Bond frequency is incompatible with the maturity tenor");
List<double> notionals = new InitializedList<double>(nPeriods+1);
notionals[0] = initialNotional;
double coupon = couponRate / (double)sinkingFrequency;
double compoundedInterest = 1.0;
double totalValue = Math.Pow(1.0+coupon, nPeriods);
for(int i = 0; i < (int)nPeriods-1; ++i)
{
compoundedInterest *= (1.0 + coupon);
double currentNotional = 0.0;
if(coupon < 1.0e-12) {
currentNotional =
initialNotional*(1.0 - (i+1.0)/nPeriods);
}
else {
currentNotional =
initialNotional*(compoundedInterest - (compoundedInterest-1.0)/(1.0 - 1.0/totalValue));
}
notionals[i+1] = currentNotional;
}
notionals[notionals.Count-1] = 0.0;
return notionals;
}
开发者ID:akasolace,项目名称:qlnet,代码行数:32,代码来源:AmortizingFixedRateBond.cs
示例19: testMonteCarloCapletPricing
public void testMonteCarloCapletPricing()
{
//"Testing caplet LMM Monte-Carlo caplet pricing..."
//SavedSettings backup;
/* factor loadings are taken from Hull & White article
plus extra normalisation to get orthogonal eigenvectors
http://www.rotman.utoronto.ca/~amackay/fin/libormktmodel2.pdf */
double[] compValues = {0.85549771, 0.46707264, 0.22353259,
0.91915359, 0.37716089, 0.11360610,
0.96438280, 0.26413316,-0.01412414,
0.97939148, 0.13492952,-0.15028753,
0.95970595,-0.00000000,-0.28100621,
0.97939148,-0.13492952,-0.15028753,
0.96438280,-0.26413316,-0.01412414,
0.91915359,-0.37716089, 0.11360610,
0.85549771,-0.46707264, 0.22353259};
Matrix volaComp=new Matrix(9,3);
List<double> lcompValues=new InitializedList<double>(27,0);
List<double> ltemp = new InitializedList<double>(3, 0);
lcompValues=compValues.ToList();
//std::copy(compValues, compValues+9*3, volaComp.begin());
for (int i = 0; i < 9; i++)
{
ltemp = lcompValues.GetRange(3*i, 3);
for (int j = 0; j < 3; j++)
volaComp[i, j] = ltemp[j];
}
LiborForwardModelProcess process1 = makeProcess();
LiborForwardModelProcess process2 = makeProcess(volaComp);
List<double> tmp = process1.fixingTimes();
TimeGrid grid=new TimeGrid(tmp ,12);
List<int> location=new List<int>();
for (int i=0; i < tmp.Count; ++i) {
location.Add(grid.index(tmp[i])) ;
}
// set-up a small Monte-Carlo simulation to price caplets
// and ratchet caps using a one- and a three factor libor market model
ulong seed = 42;
LowDiscrepancy.icInstance = new InverseCumulativeNormal();
IRNG rsg1 = (IRNG)new LowDiscrepancy().make_sequence_generator(
process1.factors()*(grid.size()-1), seed);
IRNG rsg2 = (IRNG)new LowDiscrepancy().make_sequence_generator(
process2.factors()*(grid.size()-1), seed);
MultiPathGenerator<IRNG> generator1=new MultiPathGenerator<IRNG> (process1, grid, rsg1, false);
MultiPathGenerator<IRNG> generator2=new MultiPathGenerator<IRNG> (process2, grid, rsg2, false);
const int nrTrails = 250000;
List<GeneralStatistics> stat1 = new InitializedList<GeneralStatistics>(process1.size());
List<GeneralStatistics> stat2 = new InitializedList<GeneralStatistics>(process2.size());
List<GeneralStatistics> stat3 = new InitializedList<GeneralStatistics>(process2.size() - 1);
for (int i=0; i<nrTrails; ++i) {
Sample<MultiPath> path1 = generator1.next();
Sample<MultiPath> path2 = generator2.next();
List<double> rates1=new InitializedList<double>(len);
List<double> rates2 = new InitializedList<double>(len);
for (int j=0; j<process1.size(); ++j) {
rates1[j] = path1.value[j][location[j]];
rates2[j] = path2.value[j][location[j]];
}
List<double> dis1 = process1.discountBond(rates1);
List<double> dis2 = process2.discountBond(rates2);
for (int k=0; k<process1.size(); ++k) {
double accrualPeriod = process1.accrualEndTimes()[k]
- process1.accrualStartTimes()[k];
// caplet payoff function, cap rate at 4%
double payoff1 = Math.Max(rates1[k] - 0.04, 0.0) * accrualPeriod;
double payoff2 = Math.Max(rates2[k] - 0.04, 0.0) * accrualPeriod;
stat1[k].add(dis1[k] * payoff1);
stat2[k].add(dis2[k] * payoff2);
if (k != 0) {
// ratchet cap payoff function
double payoff3 = Math.Max(rates2[k] - (rates2[k-1]+0.0025), 0.0)
* accrualPeriod;
stat3[k-1].add(dis2[k] * payoff3);
}
}
}
double[] capletNpv = {0.000000000000, 0.000002841629, 0.002533279333,
0.009577143571, 0.017746502618, 0.025216116835,
0.031608230268, 0.036645683881, 0.039792254012,
0.041829864365};
double[] ratchetNpv = {0.0082644895, 0.0082754754, 0.0082159966,
0.0082982822, 0.0083803357, 0.0084366961,
0.0084173270, 0.0081803406, 0.0079533814};
//.........这里部分代码省略.........
开发者ID:Yenyenx,项目名称:qlnet,代码行数:101,代码来源:T_LiborMarketModelProcess.cs
示例20: testCachedFloating
public void testCachedFloating()
{
// "Testing floating-rate bond prices against cached values...");
CommonVars vars = new CommonVars();
Date today = new Date(22, Month.November, 2004);
Settings.setEvaluationDate(today);
int settlementDays = 1;
var riskFreeRate = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.025, new Actual360()));
var discountCurve = new Handle<YieldTermStructure>(Utilities.flatRate(today, 0.03, new Actual360()));
IborIndex index = new USDLibor(new Period(6, TimeUnit.Months), riskFreeRate);
int fixingDays = 1;
double tolerance = 1.0e-6;
IborCouponPricer pricer = new BlackIborCouponPricer(new Handle<OptionletVolatilityStructure>());
// plain
Schedule sch = new Schedule(new Date(30, Month.November, 2004), new Date(30, Month.November, 2008),
new Period(Frequency.Semiannual), new UnitedStates(UnitedStates.Market.GovernmentBond),
BusinessDayConvention.ModifiedFollowing, BusinessDayConvention.ModifiedFollowing,
DateGeneration.Rule.Backward, false);
FloatingRateBond bond1 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List<double>(), new List<double>(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine = new DiscountingBondEngine(riskFreeRate);
bond1.setPricingEngine(bondEngine);
Utils.setCouponPricer(bond1.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice1 = 99.874645;
#else
double cachedPrice1 = 99.874646;
#endif
double price = bond1.cleanPrice();
if (Math.Abs(price - cachedPrice1) > tolerance)
{
Assert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice1 + "\n"
+ " error: " + (price - cachedPrice1));
}
// different risk-free and discount curve
FloatingRateBond bond2 = new FloatingRateBond(settlementDays, vars.faceAmount, sch,
index, new ActualActual(ActualActual.Convention.ISMA),
BusinessDayConvention.ModifiedFollowing, fixingDays,
new List<double>(), new List<double>(),
new List<double>(), new List<double>(),
false,
100.0, new Date(30, Month.November, 2004));
IPricingEngine bondEngine2 = new DiscountingBondEngine(discountCurve);
bond2.setPricingEngine(bondEngine2);
Utils.setCouponPricer(bond2.cashflows(), pricer);
#if QL_USE_INDEXED_COUPON
double cachedPrice2 = 97.955904;
#else
double cachedPrice2 = 97.955904;
#endif
price = bond2.cleanPrice();
if (Math.Abs(price - cachedPrice2) > tolerance)
{
Assert.Fail("failed to reproduce cached price:\n"
+ " calculated: " + price + "\n"
+ " expected: " + cachedPrice2 + "\n"
+ " error: " + (price - cachedPrice2));
}
// varying spread
InitializedList<double> spreads = new InitializedList<
|
请发表评论