Skip to content

Instantly share code, notes, and snippets.

@adejorosam
Created October 5, 2024 13:55
Show Gist options
  • Save adejorosam/2838123ba0c58c5fb3d8c5d830ed47b2 to your computer and use it in GitHub Desktop.
Save adejorosam/2838123ba0c58c5fb3d8c5d830ed47b2 to your computer and use it in GitHub Desktop.
rolling-avg
async computeRollingAverage(
accountId: string,
refDate: string,
): Promise<any> {
const totalPort = [];
const data = [];
let mom = 0;
let momC = 0;
// Loop through the past 7 months
for (let i = 6; i >= 0; i--) {
const rollDate = this.getPreviousMonth(refDate, i);
// Fetch portfolio data for the previous months
const previousMonthData = await this.fetchPortfolioPositionReport(accountId, rollDate);
if (previousMonthData && previousMonthData.totalValue) {
totalPort[i] = previousMonthData.totalValue;
// Calculate MoM changes for months other than the current one
if (i < 6) {
const totalPortNext = totalPort[i + 1] || 0;
mom = totalPort[i] - totalPortNext;
momC = totalPortNext !== 0 ? ((totalPort[i] - totalPortNext) / totalPortNext) * 100 : 0;
}
// Store the data for each month
data.push({
MONTH: rollDate,
'TOTAL VALUE': totalPort[i],
'MOM NGN CHANGE': mom.toFixed(2),
'MOM % CHANGE': momC.toFixed(2),
});
}
}
return data;
}
async fetchPortfolioPositionReport(accountId: string, valueDate: string): Promise<any> {
const url = `${this.ZANIBAL_BASE_URL}/position/api/v1/ledgers/report/account/${accountId}?valueDate=${valueDate}&currency=NGN`;
const token = await this.getAccessToken();
const response = await this.commonhttpService.get(url, {
'x-tenant-id': this.ZANIBAL_TENANT_ID,
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
});
return response;
}
// Helper function to get the previous month from a reference date
getPreviousMonth(refDate: string, monthsAgo: number): string {
const date = new Date(refDate);
date.setMonth(date.getMonth() - monthsAgo);
return date.toISOString().split('T')[0]; // Format as YYYY-MM-DD
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment