Skip to content

Instantly share code, notes, and snippets.

@verawatk
Created January 30, 2017 10:23
Show Gist options
  • Save verawatk/36f1f927b70f0f965d9261f0010ce63b to your computer and use it in GitHub Desktop.
Save verawatk/36f1f927b70f0f965d9261f0010ce63b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <math.h>
using namespace std;
int main() {
int compounding = 0;
cout << "Please enter the frequency of compounding? " << endl
<< "1 for Annual Compounding, 2 for Semi-Annual Compounding : " ; cin >> compounding;
cin.get(); // ignore return carriage
cout << "Please enter Swap Rates:";
vector<double> swapRates;
string buffer;
getline(cin, buffer);
istringstream ssin(buffer);
double input;
// We keep all swap rates in "swapRates".
while (ssin >> input) {
swapRates.push_back(input);
}
int terms = swapRates.size();
vector<double> df;
vector<double> spotRates;
vector<double> forwardRates;
// We use algorithms discussed above to find DF,Spot Rates,
// Forward Rates as follows.
// find discount factors
for (int i=0; i<terms; i++) {
double sum = 0;
double discount = 0;
for (int j=0; j<i; j++) {
sum += (swapRates[i] / compounding)*df[j];
}
discount = (1.0 - sum) / (1.0 + swapRates[i] / compounding);
df.push_back(discount);
}
// find Spot Rates
for (int i = 0; i < terms; i++) {
double spot = compounding * ( pow( 1.0/df[i] , 1.0/(i+1.0)) - 1.0);
spotRates.push_back(spot);
}
// find Forward Rates
for (int i = 0; i < terms; i++) {
double products = 1;
double forward;
for (int j = 0; j < i; j++) {
products *= 1 / (1 + forwardRates[j]/compounding);
}
products *= 1 / df[i];
forward = compounding * (products - 1);
forwardRates.push_back(forward);
}
// Display Results.
cout << endl;
cout << left << setw(15) << setfill(' ') << "Term (years)";
cout << left << setw(15) << setfill(' ') << "Swap Rates";
cout << left << setw(15) << setfill(' ') << "DF";
cout << left << setw(15) << setfill(' ') << "Spot Rates";
cout << left << setw(15) << setfill(' ') << "Forward Rates" << endl;
cout << "===========================================================" << endl;
for (int i = 0; i < terms; i++) {
cout << left << setw(15) << setfill(' ') << (1.0 / compounding)*(i+1);
cout << left << setw(15) << setfill(' ') << swapRates[i];
cout << left << setw(15) << setfill(' ') << df[i];
cout << left << setw(15) << setfill(' ') << spotRates[i];
cout << left << setw(15) << setfill(' ') << forwardRates[i] << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment