compute sharpe ratio in csharp

To calculate the Sharpe Ratio in C#, we need to first get the daily returns of the portfolio, then calculate the average return and standard deviation of the returns, and finally divide the result by the risk-free rate. Here's an example implementation:

main.cs
public static double CalculateSharpeRatio(double[] dailyReturns, double riskFreeRate)
{
    double averageReturn = dailyReturns.Average();
    double standardDeviation = Math.Sqrt(dailyReturns.Select(x => Math.Pow(x - averageReturn, 2)).Sum() / (dailyReturns.Length - 1));
    return (averageReturn - riskFreeRate) / standardDeviation;
}
338 chars
7 lines

This method takes in an array of daily returns and a risk-free rate as parameters, and returns the Sharpe Ratio.

Example usage:

main.cs
double[] dailyReturns = { 0.01, 0.02, -0.03, 0.04, -0.01 };
double riskFreeRate = 0.005;
double sharpeRatio = CalculateSharpeRatio(dailyReturns, riskFreeRate);

Console.WriteLine($"Sharpe Ratio: {sharpeRatio:N2}");
215 chars
6 lines

Output:

main.cs
Sharpe Ratio: 0.70
19 chars
2 lines

gistlibby LogSnag