Skip to content

Instantly share code, notes, and snippets.

@PopovMP
Created July 31, 2019 15:51
Show Gist options
  • Save PopovMP/9131e3a853a43a8a87bdaf3a0d1fa994 to your computer and use it in GitHub Desktop.
Save PopovMP/9131e3a853a43a8a87bdaf3a0d1fa994 to your computer and use it in GitHub Desktop.
getRSquared
public static getRSquared(transactions: Transaction[], fromBar: number, toBar: number): number {
if (transactions.length === 0 ||
transactions[0].bar >= toBar ||
transactions[transactions.length - 1].bar < fromBar) {
return 0;
}
let startIndex: number = 0;
if (fromBar > 0) {
for (let i: number = 0; i < transactions.length; i++) {
const transaction: Transaction = transactions[i];
if (transaction.bar >= fromBar) {
startIndex = i;
break;
}
}
}
let endIndex: number = transactions.length - 1;
if (transactions[endIndex].bar >= toBar) {
for (let i: number = endIndex; i >= startIndex; i--) {
if (transactions[i].bar < toBar) {
endIndex = i;
break;
}
}
}
let minBalance: number = transactions[0].balance;
for (let i: number = startIndex; i <= endIndex; i++) {
if (transactions[i].balance < minBalance) {
minBalance = transactions[i].balance;
}
}
let sumX: number = 0;
let sumY: number = 0;
let sumXX: number = 0;
let sumYY: number = 0;
let sumXY: number = 0;
let count: number = 0;
for (let i: number = startIndex; i <= endIndex; i++) {
const transaction: Transaction = transactions[i];
if (transaction.type === TransactionType.Close ||
transaction.type === TransactionType.StopLoss ||
transaction.type === TransactionType.TakeProfit) {
const x: number = transaction.bar - fromBar + 1;
const y: number = transaction.balance - minBalance + 1;
sumX += x;
sumY += y;
sumXX += x * x;
sumYY += y * y;
sumXY += x * y;
count++;
}
}
if (count < 2) {
return 0;
}
const r: number = (count * sumXY - sumX * sumY) / Math.sqrt(count * sumXX - sumX * sumX) / Math.sqrt(count * sumYY - sumY * sumY);
const r5: number = Math.pow(r, 5);
return 100 * r5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment