152 lines
5.6 KiB
C#
152 lines
5.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
using bts;
|
|
|
|
namespace bts.SilverPine {
|
|
public static class IndicatorCalc {
|
|
public static double calculate_pearson_correlation(List<double> prices1, List<double> prices2) {
|
|
if (prices1 == null)
|
|
throw new ArgumentNullException(nameof(prices1), "First price list cannot be null.");
|
|
if (prices2 == null)
|
|
throw new ArgumentNullException(nameof(prices2), "Second price list cannot be null.");
|
|
if (prices1.Count != prices2.Count)
|
|
throw new ArgumentException("Price lists must have the same number of elements.");
|
|
if (prices1.Count < 2)
|
|
throw new ArgumentException("At least two data points are required to calculate correlation.");
|
|
|
|
int n = prices1.Count;
|
|
double sumX = 0;
|
|
double sumY = 0;
|
|
double sumX2 = 0;
|
|
double sumY2 = 0;
|
|
double sumXY = 0;
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
double x = prices1[i];
|
|
double y = prices2[i];
|
|
|
|
sumX += x;
|
|
sumY += y;
|
|
sumX2 += x * x;
|
|
sumY2 += y * y;
|
|
sumXY += x * y;
|
|
}
|
|
|
|
double numerator = (n * sumXY) - (sumX * sumY);
|
|
double denominatorPart1 = (n * sumX2) - (sumX * sumX);
|
|
double denominatorPart2 = (n * sumY2) - (sumY * sumY);
|
|
double denominator = Math.Sqrt(denominatorPart1 * denominatorPart2);
|
|
|
|
if (denominator == 0)
|
|
throw new InvalidOperationException("Denominator is zero, correlation is undefined.");
|
|
|
|
return numerator / denominator;
|
|
}
|
|
public static double calculate_VWAP(List<Tuple<int, double>> volumePriceData) {
|
|
Log.Gen.info($"ChartingHelper.calculate_VWAP n_vals: {volumePriceData.Count}");
|
|
double totalVolume = 0;
|
|
double totalPriceVolume = 0;
|
|
|
|
foreach (var data in volumePriceData) {
|
|
int volume = data.Item1; // Volume
|
|
double price = data.Item2; // Closing price
|
|
|
|
// Accumulate total price-volume (price * volume) and total volume
|
|
totalPriceVolume += price * volume;
|
|
totalVolume += volume;
|
|
}
|
|
|
|
// VWAP is totalPriceVolume divided by totalVolume
|
|
return totalVolume > 0 ? totalPriceVolume / totalVolume : 0;
|
|
}
|
|
|
|
// Calculate Volatility (Standard Deviation of returns) over a given period
|
|
public static double calculate_volatility(IList<double> prices, int period = 252) {
|
|
if (prices == null || prices.Count < period + 1) {
|
|
throw new ArgumentException("Insufficient data to calculate volatility.");
|
|
}
|
|
|
|
// Calculate daily returns
|
|
var returns = new List<double>();
|
|
for (int i = 1; i < prices.Count; i++) {
|
|
double dailyReturn = (prices[i] - prices[i - 1]) / prices[i - 1];
|
|
returns.Add(dailyReturn);
|
|
}
|
|
|
|
// Get the returns over the desired period
|
|
var recentReturns = returns.Skip(returns.Count - period).Take(period).ToList();
|
|
|
|
// Calculate the mean of returns
|
|
double meanReturn = recentReturns.Average();
|
|
|
|
// Calculate the variance (sum of squared differences from the mean)
|
|
double variance = recentReturns.Sum(r => Math.Pow(r - meanReturn, 2)) / period;
|
|
|
|
// Volatility is the square root of variance (standard deviation)
|
|
double volatility = Math.Sqrt(variance);
|
|
|
|
// Annualize volatility by multiplying by the square root of 252 (number of trading days in a year)
|
|
return volatility * Math.Sqrt(252);
|
|
}
|
|
|
|
// Calculate SMA (Simple Moving Average) for a given period (e.g., 50, 100, or 200)
|
|
public static double calculate_SMA(IList<double> prices, int period = 50) {
|
|
if (prices == null || prices.Count < period) {
|
|
throw new ArgumentException("Insufficient data to calculate SMA.");
|
|
}
|
|
|
|
// Sum up the prices over the given period
|
|
double sum = prices.Skip(prices.Count - period).Take(period).Sum();
|
|
|
|
// Return the average
|
|
return sum / period;
|
|
}
|
|
|
|
public static double calculate_RSI(IList<double> prices, int period = 14) {
|
|
if (prices == null || prices.Count < period + 1) {
|
|
return Double.NaN;
|
|
//throw new ArgumentException("Insufficient data to calculate RSI.");
|
|
}
|
|
|
|
double gainSum = 0;
|
|
double lossSum = 0;
|
|
|
|
// Calculate the initial average gain and loss over the first 'period' days
|
|
for (int i = 1; i <= period; i++) {
|
|
double change = prices[i] - prices[i - 1];
|
|
if (change > 0) {
|
|
gainSum += change;
|
|
} else {
|
|
lossSum -= change; // Subtract since loss is negative
|
|
}
|
|
}
|
|
|
|
double avgGain = gainSum / period;
|
|
double avgLoss = lossSum / period;
|
|
|
|
// Calculate RSI using smoothed values
|
|
for (int i = period + 1; i < prices.Count; i++) {
|
|
double change = prices[i] - prices[i - 1];
|
|
if (change > 0) {
|
|
avgGain = (avgGain * (period - 1) + change) / period;
|
|
avgLoss = (avgLoss * (period - 1)) / period;
|
|
} else {
|
|
avgGain = (avgGain * (period - 1)) / period;
|
|
avgLoss = (avgLoss * (period - 1) - change) / period;
|
|
}
|
|
}
|
|
|
|
// Prevent division by zero in case of no losses
|
|
if (avgLoss == 0) {
|
|
return 100;
|
|
}
|
|
|
|
double rs = avgGain / avgLoss;
|
|
double rsi = 100 - (100 / (1 + rs));
|
|
|
|
return rsi;
|
|
}
|
|
}
|
|
} |