Member-only story

Sharpe Ratio in C++ and Python

Sukhvinder Singh
2 min readMar 10, 2023

--

The first example is in C++

In this code, we define three functions: calculateMean, calculateStdDev, and calculateSharpeRatio.

calculateMean takes a vector of returns as input, and calculates the mean return.

calculateStdDev takes a vector of returns and the mean return as input, and calculates the standard deviation of returns.

calculateSharpeRatio takes a vector of returns and the risk-free rate as input, and calculates the Sharpe Ratio by first calculating the mean and standard deviation of returns, then computing the excess returns over the risk-free rate, and finally dividing the excess returns by the standard deviation.

#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

double calculateMean(vector<double> returns)
{
double sum = 0;
int n = returns.size();
for (int i = 0; i < n; i++)
{
sum += returns[i];
}
return sum / n;
}

double calculateStdDev(vector<double> returns, double mean)
{
double sum = 0;
int n = returns.size();
for (int i = 0; i < n; i++)
{
sum += pow(returns[i] - mean, 2);
}
return sqrt(sum / (n - 1));
}

double calculateSharpeRatio(vector<double> returns, double riskFreeRate)
{
double mean = calculateMean(returns);
double stdDev = calculateStdDev(returns, mean);
double excessReturns = mean - riskFreeRate;
return excessReturns / stdDev;
}

int main()
{
vector<double> returns = {0.05, 0.02, -0.01, 0.03, 0.01};
double…

--

--

Sukhvinder Singh
Sukhvinder Singh

Written by Sukhvinder Singh

Software Developer, Software Architect, Inventor, Quant

No responses yet