RcppExport SEXP cfamounts(SEXP params){ SEXP rl=R_NilValue; char* exceptionMesg=NULL; try{ RcppParams rparam(params); QuantLib::Date maturity(dateFromR(rparam.getDateValue("Maturity"))); QuantLib::Date settle(dateFromR(rparam.getDateValue("Settle"))); QuantLib::Date issue(dateFromR(rparam.getDateValue("IssueDate"))); double rate = rparam.getDoubleValue("CouponRate"); std::vector<double> rateVec(1, rate); double faceAmount = rparam.getDoubleValue("Face"); double period = rparam.getDoubleValue("Period"); double basis = rparam.getDoubleValue("Basis"); DayCounter dayCounter = getDayCounter(basis); Frequency freq = getFrequency(period); Period p(freq); double EMR = rparam.getDoubleValue("EMR"); Calendar calendar=UnitedStates(UnitedStates::GovernmentBond); Schedule sch(settle, maturity, p, calendar, Unadjusted, Unadjusted, DateGeneration::Backward, (EMR == 1)? true : false); FixedRateBond bond(1, faceAmount, sch, rateVec, dayCounter, Following, 100, issue); //cashflow int numCol = 2; std::vector<std::string> colNames(numCol); colNames[0] = "Date"; colNames[1] = "Amount"; RcppFrame frame(colNames); Leg bondCashFlow = bond.cashflows(); for (unsigned int i = 0; i< bondCashFlow.size(); i++){ std::vector<ColDatum> row(numCol); Date d = bondCashFlow[i]->date(); row[0].setDateValue(RcppDate(d.month(), d.dayOfMonth(), d.year())); row[1].setDoubleValue(bondCashFlow[i]->amount()); frame.addRow(row); } RcppResultSet rs; rs.add("cashFlow", frame); rl = rs.getReturnList(); } catch(std::exception& ex) { exceptionMesg = copyMessageToR(ex.what()); } catch(...) { exceptionMesg = copyMessageToR("unknown reason"); } if(exceptionMesg != NULL) Rf_error(exceptionMesg); return rl; }
int main() { Robot *hexapode = new Robot(); hexapode->addLeg(100); std::cout << hexapode->nbLegs() << std::endl; Leg *leg = new Leg(); leg->generateOrders(100); hexapode->addLeg(leg); std::cout << hexapode->nbLegs() << std::endl; hexapode->addLeg(100); hexapode->addLeg(100); hexapode->addLeg(100); hexapode->addLeg(100); std::cout << hexapode->nbLegs() << std::endl; return 0; }
void setCouponPricer( const Leg& leg, const boost::shared_ptr<FloatingRateCouponPricer>& pricer) { PricerSetter setter(pricer); for (Size i=0; i<leg.size(); ++i) { leg[i]->accept(setter); } }
MakeCapFloor::operator shared_ptr<CapFloor>() const { VanillaSwap swap = makeVanillaSwap_; Leg leg = swap.floatingLeg(); if (firstCapletExcluded_) leg.erase(leg.begin()); // only leaves the last coupon if (asOptionlet_ && leg.size() > 1) { Leg::iterator end = leg.end(); // Sun Studio needs an lvalue leg.erase(leg.begin(), --end); } std::vector<Rate> strikeVector(1, strike_); if (strike_ == Null<Rate>()) { // temporary patch... // should be fixed for every CapFloor::Engine shared_ptr<BlackCapFloorEngine> temp = dynamic_pointer_cast<BlackCapFloorEngine>(engine_); QL_REQUIRE(temp, "cannot calculate ATM without a BlackCapFloorEngine"); Handle<YieldTermStructure> discountCurve = temp->termStructure(); strikeVector[0] = CashFlows::atmRate(leg, **discountCurve, false, discountCurve->referenceDate()); } shared_ptr<CapFloor> capFloor(new CapFloor(capFloorType_, leg, strikeVector)); capFloor->setPricingEngine(engine_); return capFloor; }
void Draw() { BeginDraw(); model.Draw(); leg.Draw(); EndDraw(); }
Leg FixedRateLeg::load_fixedRateLeg(const std::string& legID) { // load ÂÞ¿í. Leg leg = Leg(); clsMAST_CF_FIXED_TB clstb = clsMAST_CF_FIXED_TB(); clstb.LEG_ID = legID; clstb._LEG_IDSelectFlag = true; std::vector<boost::shared_ptr<clsMAST_CF_FIXED_TB>> cfList = clstb.create(clstb.selectQuery_raw()); QL_REQUIRE(cfList.size() > 0, "fixedRate cash-flow does not exist : " + legID); Size cashflow_num = cfList.size(); for (Size i = 0; i < cashflow_num ; i++) { const Date& paymentDate = DateParser::parseDB(cfList[i]->PAYMENT_DT); Real nominal = cfList[i]->NOTIONAL; Real rate = cfList[i]->FIXED_RATE; const DayCounter& dayCounter = DayCounterFactory::load_dayCounter("act/365f"); const Date& startDate = DateParser::parseDB(cfList[i]->CALC_START_DT); const Date& endDate = DateParser::parseDB(cfList[i]->CALC_END_DT); boost::shared_ptr<FixedRateCoupon> frc = boost::shared_ptr<FixedRateCoupon>( new FixedRateCoupon(paymentDate, nominal, rate, dayCounter, startDate, endDate)); leg.push_back(frc); } // sort ? return leg; }
AverageBMALeg::operator Leg() const { QL_REQUIRE(!notionals_.empty(), "no notional given"); Leg cashflows; // the following is not always correct Calendar calendar = schedule_.calendar(); Date refStart, start, refEnd, end; Date paymentDate; Size n = schedule_.size()-1; for (Size i=0; i<n; ++i) { refStart = start = schedule_.date(i); refEnd = end = schedule_.date(i+1); paymentDate = calendar.adjust(end, paymentAdjustment_); if (i == 0 && schedule_.hasIsRegular() && !schedule_.isRegular(i+1) && schedule_.hasTenor()) refStart = calendar.adjust(end - schedule_.tenor(), paymentAdjustment_); if (i == n-1 && schedule_.hasIsRegular() && !schedule_.isRegular(i+1) && schedule_.hasTenor()) refEnd = calendar.adjust(start + schedule_.tenor(), paymentAdjustment_); cashflows.push_back(ext::shared_ptr<CashFlow>(new AverageBMACoupon(paymentDate, detail::get(notionals_, i, notionals_.back()), start, end, index_, detail::get(gearings_, i, 1.0), detail::get(spreads_, i, 0.0), refStart, refEnd, paymentDayCounter_))); } return cashflows; }
MakeYoYInflationCapFloor::operator ext::shared_ptr<YoYInflationCapFloor>() const { Date startDate; if (effectiveDate_ != Date()) { startDate = effectiveDate_; } else { Date referenceDate = Settings::instance().evaluationDate(); Date spotDate = calendar_.advance(referenceDate, fixingDays_*Days); startDate = spotDate+forwardStart_; } Date endDate = calendar_.advance(startDate,length_*Years,Unadjusted); Schedule schedule(startDate, endDate, Period(Annual), calendar_, Unadjusted, Unadjusted, // ref periods & acc periods DateGeneration::Forward, false); Leg leg = yoyInflationLeg(schedule, calendar_, index_, observationLag_) .withPaymentAdjustment(roll_) .withPaymentDayCounter(dayCounter_) .withNotionals(nominal_) ; if (firstCapletExcluded_) leg.erase(leg.begin()); // only leaves the last coupon if (asOptionlet_ && leg.size() > 1) { Leg::iterator end = leg.end(); // Sun Studio needs an lvalue leg.erase(leg.begin(), --end); } std::vector<Rate> strikeVector(1, strike_); if (strike_ == Null<Rate>()) { // ATM on the forecasting curve Handle<YieldTermStructure> fc; if (!nominalTermStructure_.empty()) { fc = nominalTermStructure_; } else { QL_REQUIRE(!index_->yoyInflationTermStructure().empty(), "no forecasting yoy term structure set for " << index_->name()); fc = index_->yoyInflationTermStructure()->nominalTermStructure(); } strikeVector[0] = CashFlows::atmRate(leg,**fc, false, fc->referenceDate()); } ext::shared_ptr<YoYInflationCapFloor> capFloor(new YoYInflationCapFloor(capFloorType_, leg, strikeVector)); capFloor->setPricingEngine(engine_); return capFloor; }
void setCouponPricers( const Leg& leg, const std::vector<boost::shared_ptr<FloatingRateCouponPricer> >& pricers) { Size nCashFlows = leg.size(); QL_REQUIRE(nCashFlows>0, "no cashflows"); Size nPricers = pricers.size(); QL_REQUIRE(nCashFlows >= nPricers, "mismatch between leg size (" << nCashFlows << ") and number of pricers (" << nPricers << ")"); for (Size i=0; i<nCashFlows; ++i) { PricerSetter setter(i<nPricers ? pricers[i] : pricers[nPricers-1]); leg[i]->accept(setter); } }
FixedRateLeg::operator Leg() const { QL_REQUIRE(!couponRates_.empty(), "no coupon rates given"); QL_REQUIRE(!notionals_.empty(), "no notional given"); Leg leg; leg.reserve(schedule_.size()-1); Calendar schCalendar = schedule_.calendar(); // first period might be short or long Date start = schedule_.date(0), end = schedule_.date(1); Date paymentDate = calendar_.adjust(end, paymentAdjustment_); Date exCouponDate; InterestRate rate = couponRates_[0]; Real nominal = notionals_[0]; if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } if (schedule_.isRegular(1)) { QL_REQUIRE(firstPeriodDC_.empty() || firstPeriodDC_ == rate.dayCounter(), "regular first coupon " "does not allow a first-period day count"); shared_ptr<CashFlow> temp(new FixedRateCoupon(paymentDate, nominal, rate, start, end, start, end, exCouponDate)); leg.push_back(temp); } else { Date ref = end - schedule_.tenor(); ref = schCalendar.adjust(ref, schedule_.businessDayConvention()); InterestRate r(rate.rate(), firstPeriodDC_.empty() ? rate.dayCounter() : firstPeriodDC_, rate.compounding(), rate.frequency()); leg.push_back(shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, r, start, end, ref, end, exCouponDate))); } // regular periods for (Size i=2; i<schedule_.size()-1; ++i) { start = end; end = schedule_.date(i); paymentDate = calendar_.adjust(end, paymentAdjustment_); if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } if ((i-1) < couponRates_.size()) rate = couponRates_[i-1]; else rate = couponRates_.back(); if ((i-1) < notionals_.size()) nominal = notionals_[i-1]; else nominal = notionals_.back(); leg.push_back(shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, rate, start, end, start, end, exCouponDate))); } if (schedule_.size() > 2) { // last period might be short or long Size N = schedule_.size(); start = end; end = schedule_.date(N-1); paymentDate = calendar_.adjust(end, paymentAdjustment_); if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } if ((N-2) < couponRates_.size()) rate = couponRates_[N-2]; else rate = couponRates_.back(); if ((N-2) < notionals_.size()) nominal = notionals_[N-2]; else nominal = notionals_.back(); if (schedule_.isRegular(N-1)) { leg.push_back(shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, rate, start, end, start, end, exCouponDate))); } else { Date ref = start + schedule_.tenor(); ref = schCalendar.adjust(ref, schedule_.businessDayConvention()); leg.push_back(shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, rate, start, end, start, ref, exCouponDate))); } } return leg; }
/* TODO: Instrument interface - swaps: euro swaps, usd - bonds: UST, corp, tax-exempt munis */ int main () { cout << "QuantLib Version #: " << QL_VERSION << endl ; Calendar calendar = TARGET(); // Date todaysDate = TARGET().adjust( Date(20, September, 2004) ); Date todaysDate = TARGET().adjust( Date(28, May, 2012) ); Settings::instance().evaluationDate() = todaysDate; cout << "settings: " << &Settings::instance() << endl; cout << "\n\nToday: " << todaysDate << endl; string futtenors[] = {"ED1", "ED2", "ED3", "ED4", "ED5", "ED6", "ED7", "ED8"}; double futspots[] = {96.2875, 96.7875, 96.9875, 96.6875, 96.4875, 96.3875, 96.2875, 96.0875}; string depotenors[] = {"1W", "1M", "3M", "6M", "9M", "1y"}; double depospots[] = {.0382, 0.0372, 0.0363, 0.0353, 0.0348, 0.0345}; string swaptenors[] = {"2y", "3y", "5y", "10Y", "15Y"}; double swapspots[] = {0.037125, 0.0398, 0.0443, 0.05165, 0.055175}; cout << "test sc1" << endl; RateHelperCurve acurve = RateHelperCurve(EURiborCurve("6M")); acurve.update(depotenors, depospots, 6, swaptenors, swapspots, 5, todaysDate); cout << "quote: " << acurve.tenorquote("10Y") << endl; cout << "test tenors\n" << Period(6, Months) << " | " << Tenor("6M") << endl; cout << "fixing calendar: " << acurve.calendar() << endl; /********************* * SWAPS TO BE PRICED * **********************/ RelinkableHandle<YieldTermStructure>forecastingTermStructure = acurve.forecastingTermStructure(); // constant nominal 1,000,000 Euro Real nominal = 1000000.0; // fixed leg Frequency fixedLegFrequency = Annual; BusinessDayConvention fixedLegConvention = Unadjusted; BusinessDayConvention floatingLegConvention = ModifiedFollowing; DayCounter fixedLegDayCounter = Thirty360(Thirty360::European); Rate fixedRate = 0.04; DayCounter floatingLegDayCounter = Actual360(); // floating leg Frequency floatingLegFrequency = Semiannual; boost::shared_ptr<IborIndex> euriborIndex(new Euribor6M(forecastingTermStructure)); Spread spread = 0.0; Integer lenghtInYears = 5; VanillaSwap::Type swapType = VanillaSwap::Payer; Date settlementDate = acurve.referenceDate(); Date maturity = acurve.referenceDate() + lenghtInYears*Years; Schedule fixedSchedule(settlementDate, maturity, Period(fixedLegFrequency), calendar, fixedLegConvention, fixedLegConvention, DateGeneration::Forward, false); Schedule floatSchedule(settlementDate, maturity, Period(floatingLegFrequency), calendar, floatingLegConvention, floatingLegConvention, DateGeneration::Forward, false); VanillaSwap spot5YearSwap(swapType, nominal, fixedSchedule, fixedRate, fixedLegDayCounter, floatSchedule, euriborIndex, spread, floatingLegDayCounter); Date fwdStart = calendar.advance(settlementDate, 1, Years); Date fwdMaturity = fwdStart + lenghtInYears*Years; Schedule fwdFixedSchedule(fwdStart, fwdMaturity, Period(fixedLegFrequency), calendar, fixedLegConvention, fixedLegConvention, DateGeneration::Forward, false); Schedule fwdFloatSchedule(fwdStart, fwdMaturity, Period(floatingLegFrequency), calendar, floatingLegConvention, floatingLegConvention, DateGeneration::Forward, false); VanillaSwap oneYearForward5YearSwap(swapType, nominal, fwdFixedSchedule, fixedRate, fixedLegDayCounter, fwdFloatSchedule, euriborIndex, spread, floatingLegDayCounter); cout << "swap." << endl; boost::shared_ptr<PricingEngine> swapEngine = createPriceEngine<DiscountingSwapEngine>( acurve.discountingTermStructure() ); spot5YearSwap.setPricingEngine(swapEngine); oneYearForward5YearSwap.setPricingEngine(swapEngine); Real NPV; Rate fairRate; Spread fairSpread; cout << "spot " << endl; NPV = spot5YearSwap.NPV(); fairSpread = spot5YearSwap.fairSpread(); fairRate = spot5YearSwap.fairRate(); cout << std::setprecision(2) << std::setw(12) << std::fixed << "NPV : " << NPV << " | Fair Spread: " << io::rate(fairSpread) << " | Fair Rate: " << io::rate(fairRate) << endl; cout << std::setprecision(2) << std::setw(12) << std::fixed << "fx NPV : " << spot5YearSwap.fixedLegNPV() << " | fx NPV : " << spot5YearSwap.floatingLegNPV() << endl; cout << "forward " << endl; NPV = oneYearForward5YearSwap.NPV(); fairSpread = oneYearForward5YearSwap.fairSpread(); fairRate = oneYearForward5YearSwap.fairRate(); cout << std::setprecision(2) << std::setw(12) << std::fixed << "NPV : " << NPV << " | Fair Spread: " << io::rate(fairSpread) << " | Fair Rate: " << io::rate(fairRate) << endl; cout << std::setprecision(2) << std::setw(12) << std::fixed << "fx NPV : " << oneYearForward5YearSwap.fixedLegNPV() << " | fx NPV : " << oneYearForward5YearSwap.floatingLegNPV() << endl; cout << "test libor clone" << endl; RelinkableHandle<YieldTermStructure> indexTermStructure; boost::shared_ptr<IborIndex> libor3m(new USDLibor(Period(3, Months), indexTermStructure)); Handle<YieldTermStructure>testTS = acurve.forecastingTermStructure(); boost::shared_ptr<IborIndex> newlib = libor3m->clone(testTS); // If one wanted a USD Libor index.... USDLiborBase testIndex; cout << "\n\nSwap to compare to first swap " << endl; cout << "Qswap" << endl; cout << "mty: " << maturity << " | cpn: " << io::rate(fixedRate) << endl; EuriborBase euribor(6, Months); FixedFloatSwap qswp(settlementDate, maturity, fixedRate, euribor(acurve.yieldTermStructurePtr()), FixedPayer, 0.0, 1000000.0, Annual, Thirty360(Thirty360::European), Unadjusted, Semiannual, Actual360(), ModifiedFollowing, TARGET() ); qswp.setPricingEngine(swapEngine); cout << std::setprecision(2) << std::setw(12) << std::fixed << "NPV : " << qswp.NPV() << " | Fair Spread: " << io::rate(qswp.fairSpread()) << " | Fair Rate: " << io::rate(qswp.fairRate()) << endl; cout << std::setprecision(2) << std::setw(12) << std::fixed << "fx NPV : " << qswp.fixedLegNPV() << " | fl NPV : " << qswp.floatingLegNPV() << endl; cout << "Inspect Legs" << endl << endl; Leg fixedLeg = qswp.fixedLeg(); Leg floatingLeg = qswp.floatingLeg(); cout << "Fixed: " << endl; Leg::iterator fxIt; int cfCount =0; Date cfDate; double cfAmt; double cfDF; double cfNPV = 0.0; for (fxIt=fixedLeg.begin(); fxIt < fixedLeg.end(); fxIt++) { cfDate = (*fxIt)->date(); cfAmt = (*fxIt)->amount(); cfDF = acurve.discount((*fxIt)->date()); cfNPV += cfAmt*cfDF; cout << cfCount++ << ") " << std::setw(24) << cfDate << " | " << std::setw(12) << cfAmt << " | " << std::setprecision(6) << cfDF << " | " << std::setprecision(2) << cfNPV << endl; } cout << "Floating: " << endl; Leg::iterator flIt; cfCount =0; cfNPV = 0.0; for (flIt=floatingLeg.begin(); flIt < floatingLeg.end(); flIt++) { cfDate = (*flIt)->date(); cfAmt = (*flIt)->amount(); cfDF = acurve.discount((*flIt)->date()); cfNPV += cfAmt*cfDF; cout << cfCount++ << ") " << std::setw(24) << cfDate << " | " << std::setw(12) << cfAmt << " | " << std::setprecision(6) << cfDF << " | " << std::setprecision(2) << cfNPV << endl; } cout << "swp2 " << endl; SwapType<Euribor> euriborswaps(Annual, Thirty360(Thirty360::European), Unadjusted, Semiannual, Actual360(), ModifiedFollowing, TARGET() ); cout << "create" << endl; boost::shared_ptr<FixedFloatSwap> qswp2 = euriborswaps.create(settlementDate, maturity, fixedRate); cout << "pricing" << endl; qswp2->setEngine(acurve); cout << "link" << endl; euriborswaps.linkIndex(acurve); cout << std::setprecision(2) << std::setw(12) << std::fixed << "NPV : " << qswp2->NPV() << " | Fair Spread: " << io::rate(qswp2->fairSpread()) << " | Fair Rate: " << io::rate(qswp2->fairRate()) << endl; cout << std::setprecision(2) << std::setw(12) << std::fixed << "fx NPV : " << qswp2->fixedLegNPV() << " | fx NPV : " << qswp2->floatingLegNPV() << endl; cout << "\nSwap 3: forward" << endl; boost::shared_ptr<FixedFloatSwap> qswp3 = euriborswaps.create(fwdStart, fwdMaturity, fixedRate); cout << "fixed rate: " << qswp3->fixedRate() << endl; qswp3->setPricingEngine(swapEngine); euriborswaps.linkIndexTo(acurve.yieldTermStructurePtr()); cout << std::setprecision(2) << std::setw(12) << std::fixed << "NPV : " << qswp3->NPV() << " | Fair Spread: " << io::rate(qswp3->fairSpread()) << " | Fair Rate: " << io::rate(qswp3->fairRate()) << endl; cout << std::setprecision(2) << std::setw(12) << std::fixed << "fx NPV : " << qswp3->fixedLegNPV() << " | fx NPV : " << qswp3->floatingLegNPV() << endl; cout << "\n\nBonds" << endl; boost::shared_ptr<BulletBond> bond1(new BulletBond(.045, Date(15, May, 2017), Date(15, May, 2003)) ); cout << "mty: " << bond1->maturityDate() << endl; cout << "stl: " << bond1->settlementDate() << endl; cout << "test" << endl; bond1->setEngine(acurve); cout << "bondprice: " ; double prc = bond1->cleanPrice(); cout << std::setprecision(3) << prc << endl; cout << "Yield: " ; double yld = bond1->yield(prc, bond1->dayCounter(), Compounded, bond1->frequency()); cout << io::rate(yld) << endl; cout << "\n\nIMM Stuff\n"; cout << "settle: " << settlementDate << endl; Date imm = IMM::nextDate(settlementDate); string immcode = IMM::code(imm); Date imm2 = imm_nextDate(imm); string immcode2 = imm_nextCode(immcode); cout << "date: " << imm << " | code: " << immcode << endl; cout << "date: " << imm2 << " | code: " << immcode2 << endl; cout << "ED3: " << FuturesTenor("ED3") << endl; CurveMap depocurve; CurveMap futscurve; CurveMap swapcurve; RateHelperCurve rhcurve( EURiborCurve("6M", Annual) ); if (futscurve.empty()) { cout << "futscurve empty " << endl; } else { cout << "futscurve not empty: " << endl; } for (int i=0; i<2; i++) depocurve[depotenors[i]] = depospots[i]; for (int i=0; i<6; i++) futscurve[futtenors[i]] = futspots[i]; for (int i=0; i<5; i++) swapcurve[swaptenors[i]] = swapspots[i]; rhcurve.update(depocurve, futscurve, swapcurve); cout << "\n10Y: " << io::rate(rhcurve.tenorquote("10Y")) << endl; cout << "discount: " << rhcurve.discount(10.0) << endl; return 0; }
yoyInflationLeg::operator Leg() const { Size n = schedule_.size()-1; QL_REQUIRE(!notionals_.empty(), "no notional given"); QL_REQUIRE(notionals_.size() <= n, "too many nominals (" << notionals_.size() << "), only " << n << " required"); QL_REQUIRE(gearings_.size()<=n, "too many gearings (" << gearings_.size() << "), only " << n << " required"); QL_REQUIRE(spreads_.size()<=n, "too many spreads (" << spreads_.size() << "), only " << n << " required"); QL_REQUIRE(caps_.size()<=n, "too many caps (" << caps_.size() << "), only " << n << " required"); QL_REQUIRE(floors_.size()<=n, "too many floors (" << floors_.size() << "), only " << n << " required"); Leg leg; leg.reserve(n); Calendar calendar = paymentCalendar_; Date refStart, start, refEnd, end; for (Size i=0; i<n; ++i) { refStart = start = schedule_.date(i); refEnd = end = schedule_.date(i+1); Date paymentDate = calendar.adjust(end, paymentAdjustment_); if (i==0 && schedule_.hasIsRegular() && !schedule_.isRegular(i+1)) { BusinessDayConvention bdc = schedule_.businessDayConvention(); refStart = schedule_.calendar().adjust(end - schedule_.tenor(), bdc); } if (i==n-1 && schedule_.hasIsRegular() && !schedule_.isRegular(i+1)) { BusinessDayConvention bdc = schedule_.businessDayConvention(); refEnd = schedule_.calendar().adjust(start + schedule_.tenor(), bdc); } if (detail::get(gearings_, i, 1.0) == 0.0) { // fixed coupon leg.push_back(ext::shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, detail::get(notionals_, i, 1.0), detail::effectiveFixedRate(spreads_,caps_, floors_,i), paymentDayCounter_, start, end, refStart, refEnd))); } else { // yoy inflation coupon if (detail::noOption(caps_, floors_, i)) { // just swaplet ext::shared_ptr<YoYInflationCoupon> coup(new YoYInflationCoupon( paymentDate, detail::get(notionals_, i, 1.0), start, end, detail::get(fixingDays_, i, 0), index_, observationLag_, paymentDayCounter_, detail::get(gearings_, i, 1.0), detail::get(spreads_, i, 0.0), refStart, refEnd)); // in this case you can set a pricer // straight away because it only provides computation - not data ext::shared_ptr<YoYInflationCouponPricer> pricer( new YoYInflationCouponPricer); coup->setPricer(pricer); leg.push_back(ext::dynamic_pointer_cast<CashFlow>(coup)); } else { // cap/floorlet leg.push_back(ext::shared_ptr<CashFlow>(new CappedFlooredYoYInflationCoupon( paymentDate, detail::get(notionals_, i, 1.0), start, end, detail::get(fixingDays_, i, 0), index_, observationLag_, paymentDayCounter_, detail::get(gearings_, i, 1.0), detail::get(spreads_, i, 0.0), detail::get(caps_, i, Null<Rate>()), detail::get(floors_, i, Null<Rate>()), refStart, refEnd))); } } } return leg; }
void SL::parsereply(QNetworkReply *reply) { if (reply->error() != QNetworkReply::NoError) { qDebug() << "An error occured"; emit replyready("No connection"); sender()->deleteLater(); return; } trips->clear(); QTextCodec *cod = QTextCodec::codecForName("iso-8859-1"); QString bytes = cod->toUnicode(reply->readAll()); //qDebug() << bytes; QJsonParseError err; QJsonDocument jsondoc; jsondoc = QJsonDocument::fromJson(bytes.toUtf8(),&err); //qDebug() << jsondoc.isObject() << jsondoc.isArray(); QJsonObject root = jsondoc.object(); //qDebug() << root.keys(); QJsonObject hafas = root.value("HafasResponse").toObject(); //qDebug() << hafas.keys(); QJsonArray triplist; int lentrips; if (hafas.value("Trip").isObject()) { lentrips = 1; } else { triplist = hafas.value("Trip").toArray(); lentrips = triplist.size(); } for (int i = 0; i < triplist.size(); i++) { //qDebug() << "######################### NEW TRIP" << i << "/" << triplist.size(); Trip *strip = new Trip(); strip->setParent(this); strip->valid = true; strip->passed = false; strip->errmsg = ""; //Check if there is only one trip QJsonObject trip; if (lentrips == 1) { trip = hafas.value("Trip").toObject(); } else { trip = triplist.at(i).toObject(); } QJsonObject summary = trip.value("Summary").toObject(); strip->depdate = toappdate(summary.value("DepartureDate").toString()); strip->deprtdate = strip->depdate; strip->deptime = summary.value("DepartureTime").toObject().value("#text").toString(); strip->deprttime = strip->deptime; strip->arivdate = toappdate(summary.value("ArrivalDate").toString()); strip->arivrtdate = strip->arivdate; strip->arivtime = summary.value("ArrivalTime").toObject().value("#text").toString(); strip->arivrttime = strip->arivtime; //qDebug() << strip->depdate << strip->deptime << strip->arivdate << strip->arivrttime; //See if the subtrips are in a list int len; QJsonArray subtriplist; if(trip.value("SubTrip").isObject()) { len = 1; } else { subtriplist = trip.value("SubTrip").toArray(); len = subtriplist.size(); } Leg *leg = NULL; for (int j = 0; j < len; j++) { //qDebug() << "######################### NEW SUBTRIP" << j << "/" << subtriplist.size(); leg = new Leg(); leg->setParent(strip); //Check if the Subtrips are in a list QJsonObject subtrip; if (len == 1) { subtrip = trip.value("SubTrip").toObject(); } else { subtrip = subtriplist.at(j).toObject(); } QJsonObject transport = subtrip.value("Transport").toObject(); //Add leg info leg->mline = transport.value("Line").toString(); leg->mdir = transport.value("Towards").toString(); //qDebug() << leg->mline << leg->mdir; QString type = transport.value("Type").toString(); //qDebug() << "Type" << type; if (type == "MET") { if (leg->mline == "10" || leg->mline == "11") { leg->mfgcolour = blue; } else if (leg->mline == "13" || leg->mline == "14") { leg->mfgcolour = red; } else if (leg->mline == "17" || leg->mline == "18" || leg->mline == "19") { leg->mfgcolour = green; } leg->mbgcolour = "#ffffff"; leg->mline = "T" + leg->mline; } else if (type == "BUS") { leg->mfgcolour = "#ffffff"; leg->mbgcolour = "#00abe5"; } else if (type == "SHP") { leg->mfgcolour = "#00abe5"; leg->mbgcolour = "#ffffff"; } else if (type == "TRN") { leg->mfgcolour = "#000000"; leg->mbgcolour = "#ffffff"; } else if (type == "TRM") { leg->mfgcolour = "#ffe600"; leg->mbgcolour = "#00abe5"; } else { leg->mfgcolour = "#ffffff"; leg->mbgcolour = "#00abe5"; } QJsonObject origin = subtrip.value("Origin").toObject(); //Add origin info leg->mfrom = origin.value("#text").toString(); leg->mfromid = "null"; leg->mfromtrack = ""; leg->mdepdate = toappdate(subtrip.value("DepartureDate").toString()); leg->mdeprtdate = leg->mdepdate; leg->mdeptime = subtrip.value("DepartureTime").toObject().value("#text").toString(); leg->mdeprttime = leg->mdeptime; //qDebug() << leg->mfrom << leg->mdepdate << leg->mdeptime; QJsonObject destination = subtrip.value("Destination").toObject(); //Add destination info leg->mto = destination.value("#text").toString(); leg->mtoid = "null"; leg->mtotrack = ""; leg->marivdate = toappdate(subtrip.value("ArrivalDate").toString()); leg->marivrtdate = leg->marivdate; leg->marivtime = subtrip.value("ArrivalTime").toObject().value("#text").toString(); leg->marivrttime = leg->marivtime; //qDebug() << leg->mto << leg->marivdate << leg->marivtime; //Add it leg->calculatetimes(); strip->addleg(leg); } //Check if the departure time has passed, if so notify by setting errmsg. if (Timehelper::beforenow(strip->deprtdate, strip->deprttime)) { strip->passed = true; strip->errmsg = tr("Departed"); } //Add it strip->calculatetimes(); trips->append(strip); } qDebug() << "Parsing done, no errors!"; emit replyready(""); sender()->deleteLater(); }
bool AngularMotor::moveLeg(side s, Leg leg){ if( s == right_side ){ effect << " (" << "rle1 " << leg.getlj1() << ") "; effect << " (" << "rle2 " << leg.getlj2() << ") "; effect << " (" << "rle3 " << leg.getlj3() << ") "; effect << " (" << "rle4 " << leg.getlj4() << ") "; effect << " (" << "rle5 " << leg.getlj5() << ") "; effect << " (" << "rle6 " << leg.getlj6() << ") "; }else if ( s == left_side ){ effect << " (" << "lle1 " << leg.getlj1() << ") "; effect << " (" << "lle2 " << leg.getlj2() << ") "; effect << " (" << "lle3 " << leg.getlj3() << ") "; effect << " (" << "lle4 " << leg.getlj4() << ") "; effect << " (" << "lle5 " << leg.getlj5() << ") "; effect << " (" << "lle6 " << leg.getlj6() << ") "; } return true; }
void BendLeg(float amount) { leg.Rotate(Quaternion::FromAxisAngleDegrees(Vector3(1, 0, 0), 90 * amount)); }
int main( int argc, const char** argv ) { try { cout << "DEMO STEROWNIKA NOGI" << endl; Leg* legModel; vector<float_type> config; legModel = createInsectLeg("../resources/legModel.xml"); cout << "Leg type: " << legModel->getName() << endl << endl; Mat34 linkPose, linkPose_l; linkPose(0, 0) = 0; linkPose(0, 1) = 0; linkPose(0, 2) = 1; linkPose(0, 3) = 0.164; linkPose(1, 0) = 0; linkPose(1, 1) = 1; linkPose(1, 2) = 0; linkPose(1, 3) = 0.0; linkPose(2, 0) = -1; linkPose(2, 1) = 0; linkPose(2, 2) = 0; linkPose(2, 3) = -0.119; int linksNo = legModel->getLinksNo(); cout << "Destination Position" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { cout << linkPose(i, j) << " "; } cout << endl; } cout << endl << "Configuration" << endl;\ config = legModel->inverseKinematic(linkPose, linksNo, false); cout << config[0] << ", " << config[1] << ", " << config[2] << endl; linkPose = legModel->forwardKinematic(config, linksNo, false); cout << endl << "Forward Kinematic" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { cout << linkPose(i, j) << " "; } cout << endl; } Vec3 sila(0,3,1); vector<float_type> qload; qload = legModel->computLoad(sila, config, true); cout << endl << "Computed loads: " << qload[0] << ", " << qload[1] << ", " << qload[2] << endl; cout << endl << "If Leg is left: " << endl; cout << endl << "Configuration" << endl; config = legModel->inverseKinematic(linkPose, linksNo, true); cout << config[0] << ", " << config[1] << ", " << config[2] << endl; linkPose = legModel->forwardKinematic(config, linksNo, true); cout << endl << "Forward Kinematic" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) { cout << linkPose(i, j) << " "; } cout << endl; } config.clear(); config.push_back(10 * M_PI / 180);//10*M_PI/180; config.push_back(24 * M_PI / 180);//24*M_PI/180; config.push_back(-114 * M_PI / 180);//-114*M_PI/180; linkPose = legModel->forwardKinematic(config, linksNo, false); cout << endl << "Test Inverse Kinematic" << endl; cout << "testowa konfiguracja: " << config[0] << ", " << config[1] << ", " << config[2] << endl; cout << " Pozycja prawa noga:" << endl; for (int i = 0; i < 3; ++i) { cout << " "; for (int j = 0; j < 4; ++j) { cout << linkPose(i, j) << " "; } cout << endl; } linkPose_l = legModel->forwardKinematic(config, linksNo, true); cout << " Pozycja lewa noga:" << endl; for (int i = 0; i < 3; ++i) { cout << " "; for (int j = 0; j < 4; ++j) { cout << linkPose_l(i, j) << " "; } cout << endl; } config = legModel->inverseKinematic(linkPose, linksNo, false); cout << "otrzymana konfiguracja prawa: " << config[0] << ", " << config[1] << ", " << config[2] << endl; config = legModel->inverseKinematic(linkPose_l, linksNo, true); cout << "otrzymana konfiguracja lewa: " << config[0] << ", " << config[1] << ", " << config[2] << endl; getchar(); } catch (const std::exception& ex) { std::cerr << ex.what() << std::endl; return 1; } return 0; }
// GLUT callback. Called to draw the scene. void My_Display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //GLfloat angleX = ((GLfloat)windowRotateX / ((GLfloat)window_width / 2)) * 180; //GLfloat angleY = ((GLfloat)windowRotateY / ((GLfloat)window_height / 2)) * 180; //Arm left_up_arm(1, -1, 1); //Arm right_up_arm(-1,-1,1); //initial matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLightfv(GL_LIGHT0, GL_POSITION, lightPos); gluLookAt(0.0, 0.0, nRange, 0.0, 0.0, 0.0, 0.0, 0.1, 0.0); { glutSolidCube(0.08f*nRange/10.0f); } glMultMatrixf(World_Matrix); SpotlightPos[0] = 0.0f; SpotlightPos[1] = -13.5f; SpotlightPos[2] = 8.0f; SpotlightPos[3] = 1.0f; glLightfv(GL_LIGHT1, GL_AMBIENT, ambientLight); glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuseLight); glLightfv(GL_LIGHT1, GL_SPECULAR, specular); glLightfv(GL_LIGHT1, GL_POSITION, SpotlightPos); glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, Vector3<GLfloat>(0.0f, 13.5f, -0.8f).toArray()); glLighti(GL_LIGHT1, GL_SPOT_CUTOFF, 30); glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 1000.0f); SpotlightPos[0] = 0.0f; SpotlightPos[1] = -9.5f; SpotlightPos[2] = 0.0f; SpotlightPos[3] = 1.0f; glLightfv(GL_LIGHT2, GL_AMBIENT, ambientLight); glLightfv(GL_LIGHT2, GL_DIFFUSE, diffuseLight); glLightfv(GL_LIGHT2, GL_SPECULAR, specular); glLightfv(GL_LIGHT2, GL_POSITION, SpotlightPos); glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, Vector3<GLfloat>(0.0f, -1.0f, 0.0f).toArray()); glLighti(GL_LIGHT2, GL_SPOT_CUTOFF, 60); glLightf(GL_LIGHT2, GL_SPOT_EXPONENT, 1000.0f); glPushMatrix(); { //glRotatef(angleX, 0.0, 1.0, 0.0); //glRotatef(angleY, 1.0, 0.0, 0.0); //glRotatef(angle,0.0f,1.0f,0.0f); glPushMatrix(); { glPushMatrix(); { glTranslatef(0.0f,-13.5f,0.0f); magiccircle.draw(); } glPopMatrix(); glTranslatef(0.0f, body.torso_pos, 0.0f); glPushMatrix(); { glRotateXYZ(body.torso_tilt); body.draw(); //body glPushMatrix(); //left wing { glTranslatef(1.3f, 3.0f, -1.1f); glRotatef(25.0f, 0.0f, 1.0f, 0.0f); glRotatef(-5.0f, 0.0f, 0.0f, 1.0f); left_wing.draw(); } glPopMatrix(); glPushMatrix(); //right wing { glTranslatef(-1.3f, 3.0f, -1.1f); glRotatef(-25.0f, 0.0f, 1.0f, 0.0f); glRotatef(5.0f, 0.0f, 0.0f, 1.0f); right_wing.draw(); } glPopMatrix(); glPushMatrix(); //head { glTranslatef(0.0f, 4.0f, 0.0f); head.draw(); } glPopMatrix(); glPushMatrix(); //left arm { glTranslatef(3.0f, 2.6f, 0.0f); left_arm.draw(); } glPopMatrix(); glPushMatrix(); //right arm { glTranslatef(-3.0f, 2.6f, 0.0f); right_arm.draw(); } glPopMatrix(); glPushMatrix(); //left leg { glTranslatef(1.7f, -4.0f, 0.0f); glRotateXYZ(-body.torso_tilt[0], 0.0f, 0.0f); left_leg.draw(); } glPopMatrix(); glPushMatrix(); //right leg { glTranslatef(-1.7f, -4.0f, 0.0f); glRotateXYZ(-body.torso_tilt[0], 0.0f, 0.0f); right_leg.draw(); } glPopMatrix(); } glPopMatrix(); } glPopMatrix(); /* glPushMatrix(); { glTranslatef(2.2f, 0.7f, 0.0f); left_up_arm.draw(); } glPopMatrix(); glPushMatrix(); { glTranslatef(-2.2f, 0.7f, 0.0f); right_up_arm.draw(); } glPopMatrix();*/ } glPopMatrix(); glutSwapBuffers(); }
void Robot::addLeg(int nbOrders) { Leg *leg = new Leg(); leg->generateOrders(nbOrders); legs->push_back(leg); }
CPILeg::operator Leg() const { QL_REQUIRE(!notionals_.empty(), "no notional given"); Size n = schedule_.size()-1; Calendar calendar = schedule_.calendar(); Leg leg; leg.reserve(n+1); // +1 for notional, we always have some sort ... if (n>0) { QL_REQUIRE(!fixedRates_.empty() || !spreads_.empty(), "no fixedRates or spreads given"); Date refStart, start, refEnd, end; for (Size i=0; i<n; ++i) { refStart = start = schedule_.date(i); refEnd = end = schedule_.date(i+1); Date paymentDate = calendar.adjust(end, paymentAdjustment_); if (i==0 && !schedule_.isRegular(i+1)) { BusinessDayConvention bdc = schedule_.businessDayConvention(); refStart = schedule_.calendar().adjust(end - schedule_.tenor(), bdc); } if (i==n-1 && !schedule_.isRegular(i+1)) { BusinessDayConvention bdc = schedule_.businessDayConvention(); refEnd = schedule_.calendar().adjust(start + schedule_.tenor(), bdc); } if (detail::get(fixedRates_, i, 1.0) == 0.0) { // fixed coupon leg.push_back(boost::shared_ptr<CashFlow> (new FixedRateCoupon (paymentDate, detail::get(notionals_, i, 0.0), detail::effectiveFixedRate(spreads_,caps_,floors_,i), paymentDayCounter_, start, end, refStart, refEnd))); } else { // zero inflation coupon if (detail::noOption(caps_, floors_, i)) { // just swaplet boost::shared_ptr<CPICoupon> coup; coup = boost::shared_ptr<CPICoupon> (new CPICoupon(baseCPI_, // all have same base for ratio paymentDate, detail::get(notionals_, i, 0.0), start, end, detail::get(fixingDays_, i, 0.0), index_, observationLag_, observationInterpolation_, paymentDayCounter_, detail::get(fixedRates_, i, 0.0), detail::get(spreads_, i, 0.0), refStart, refEnd)); // in this case you can set a pricer // straight away because it only provides computation - not data boost::shared_ptr<CPICouponPricer> pricer (new CPICouponPricer); coup->setPricer(pricer); leg.push_back(boost::dynamic_pointer_cast<CashFlow>(coup)); } else { // cap/floorlet QL_FAIL("caps/floors on CPI coupons not implemented."); } } } } // in CPI legs you always have a notional flow of some sort Date paymentDate = calendar.adjust(schedule_.date(n), paymentAdjustment_); Date fixingDate = paymentDate - observationLag_; boost::shared_ptr<CashFlow> xnl(new CPICashFlow (detail::get(notionals_, n, 0.0), index_, Date(), // is fake, i.e. you do not have one baseCPI_, fixingDate, paymentDate, subtractInflationNominal_, observationInterpolation_, index_->frequency()) ); leg.push_back(xnl); return leg; }
FixedRateLeg::operator Leg() const { QL_REQUIRE(!couponRates_.empty(), "no coupon rates given"); QL_REQUIRE(!notionals_.empty(), "no notional given"); Leg leg; leg.reserve(schedule_.size()-1); // first period might be short or long Date start = schedule_.date(0), end = schedule_.date(1); Date paymentDate = paymentCalendar_.advance(end, paymentLag_, Days, paymentAdjustment_); Date exCouponDate; InterestRate rate = couponRates_[0]; Real nominal = notionals_[0]; if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } Date ref = schedule_.hasTenor() && schedule_.hasIsRegular() && !schedule_.isRegular(1) ? schedule_.calendar().advance(end, -schedule_.tenor(), schedule_.businessDayConvention(), schedule_.endOfMonth()) : start; InterestRate r(rate.rate(), firstPeriodDC_.empty() ? rate.dayCounter() : firstPeriodDC_, rate.compounding(), rate.frequency()); leg.push_back(ext::shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, r, start, end, ref, end, exCouponDate))); // regular periods for (Size i=2; i<schedule_.size()-1; ++i) { start = end; end = schedule_.date(i); Date paymentDate = paymentCalendar_.advance(end, paymentLag_, Days, paymentAdjustment_); if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } if ((i-1) < couponRates_.size()) rate = couponRates_[i-1]; else rate = couponRates_.back(); if ((i-1) < notionals_.size()) nominal = notionals_[i-1]; else nominal = notionals_.back(); leg.push_back(ext::shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, rate, start, end, start, end, exCouponDate))); } if (schedule_.size() > 2) { // last period might be short or long Size N = schedule_.size(); start = end; end = schedule_.date(N-1); Date paymentDate = paymentCalendar_.advance(end, paymentLag_, Days, paymentAdjustment_); if (exCouponPeriod_ != Period()) { exCouponDate = exCouponCalendar_.advance(paymentDate, -exCouponPeriod_, exCouponAdjustment_, exCouponEndOfMonth_); } if ((N-2) < couponRates_.size()) rate = couponRates_[N-2]; else rate = couponRates_.back(); if ((N-2) < notionals_.size()) nominal = notionals_[N-2]; else nominal = notionals_.back(); InterestRate r( rate.rate(), lastPeriodDC_.empty() ? rate.dayCounter() : lastPeriodDC_ , rate.compounding(), rate.frequency() ); if ((schedule_.hasIsRegular() && schedule_.isRegular(N - 1)) || !schedule_.hasTenor()) { leg.push_back(ext::shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, r, start, end, start, end, exCouponDate))); } else { Date ref = schedule_.calendar().advance( start, schedule_.tenor(), schedule_.businessDayConvention(), schedule_.endOfMonth()); leg.push_back(ext::shared_ptr<CashFlow>(new FixedRateCoupon(paymentDate, nominal, r, start, end, start, ref, exCouponDate))); } } return leg; }