aiden-shared-calculations-unified 1.0.78 → 1.0.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @fileoverview Calculation (Pass 1 - Meta) for 1-day price change.
3
+ *
4
+ * This metric answers: "What is the 1-day percentage price change for
5
+ * every instrument, handling for market holidays/weekends?"
6
+ *
7
+ * It is a 'meta' calculation that runs once, loads all price data,
8
+ * and provides a reusable 1-day change signal for downstream passes
9
+ * like cohort-capital-flow.
10
+ */
11
+
12
+ class InstrumentPriceChange1D {
13
+
14
+ /**
15
+ * Defines the output schema for this calculation.
16
+ */
17
+ static getSchema() {
18
+ const tickerSchema = {
19
+ "type": "object",
20
+ "properties": {
21
+ "price_change_1d_pct": {
22
+ "type": ["number", "null"],
23
+ "description": "The 1-day (business day adjusted) price change percentage."
24
+ }
25
+ },
26
+ "required": ["price_change_1d_pct"]
27
+ };
28
+
29
+ return {
30
+ "type": "object",
31
+ "description": "Calculates the 1-day price change for all instruments.",
32
+ "patternProperties": {
33
+ "^.*$": tickerSchema // Ticker
34
+ },
35
+ "additionalProperties": tickerSchema
36
+ };
37
+ }
38
+
39
+ /**
40
+ * Statically defines all metadata for the manifest builder.
41
+ */
42
+ static getMetadata() {
43
+ return {
44
+ type: 'meta',
45
+ rootDataDependencies: [], // Relies on price data, not root data
46
+ isHistorical: false, // It needs to look back 1 day, but is not 'historical' in the runner's sense
47
+ userType: 'n/a',
48
+ category: 'core_metrics' // Fits with other price/metric calcs
49
+ };
50
+ }
51
+
52
+ /**
53
+ * This is a Pass 1 calculation and has no dependencies.
54
+ */
55
+ static getDependencies() {
56
+ return [];
57
+ }
58
+
59
+ // Helper to get date string N days ago
60
+ _getDateStr(baseDateStr, daysOffset) {
61
+ const date = new Date(baseDateStr + 'T00:00:00Z');
62
+ date.setUTCDate(date.getUTCDate() + daysOffset);
63
+ return date.toISOString().slice(0, 10);
64
+ }
65
+
66
+ /**
67
+ * This is a 'meta' calculation. It runs once.
68
+ * @param {string} dateStr - The date string 'YYYY-MM-DD'.
69
+ * @param {object} dependencies - The shared dependencies (e.g., logger, calculationUtils).
70
+ * @param {object} config - The computation system configuration.
71
+ * @param {object} fetchedDependencies - (Unused)
72
+ * @returns {Promise<object>} The calculation result.
73
+ */
74
+ async process(dateStr, dependencies, config, fetchedDependencies) {
75
+ const { logger, calculationUtils } = dependencies;
76
+
77
+ // calculationUtils contains all exported functions from the /utils folder
78
+ const priceMap = await calculationUtils.loadAllPriceData();
79
+ const tickerMap = await calculationUtils.loadInstrumentMappings();
80
+
81
+ if (!priceMap || !tickerMap || !tickerMap.instrumentToTicker) {
82
+ logger.log('ERROR', '[instrument-price-change-1d] Failed to load priceMap or mappings.');
83
+ return {};
84
+ }
85
+
86
+ const yesterdayStr = this._getDateStr(dateStr, -1);
87
+ const result = {};
88
+
89
+ for (const instrumentId in priceMap) {
90
+ const ticker = tickerMap.instrumentToTicker[instrumentId];
91
+ if (!ticker) continue;
92
+
93
+ // Use the utility function from price_data_provider.js
94
+ const priceChangeDecimal = calculationUtils.getDailyPriceChange(
95
+ instrumentId,
96
+ yesterdayStr,
97
+ dateStr,
98
+ priceMap
99
+ );
100
+
101
+ result[ticker] = {
102
+ // Convert decimal (0.05) to percentage (5.0) for consistency
103
+ price_change_1d_pct: priceChangeDecimal !== null ? priceChangeDecimal * 100 : null
104
+ };
105
+ }
106
+
107
+ return result;
108
+ }
109
+ }
110
+
111
+ module.exports = InstrumentPriceChange1D;
@@ -6,25 +6,36 @@
6
6
  * the price-adjusted capital flow for each cohort, per asset.
7
7
  *
8
8
  * This is the primary input for the final Pass 4 signal.
9
+ *
10
+ * --- REVISED 11/12/2025 ---
11
+ * - Removed dependency on 'insights' data.
12
+ * - Added dependency on 'instrument-price-change-1d' (Pass 1 meta calc).
13
+ * - Price adjustment logic now uses the reliable 1-day price change
14
+ * from the new dependency.
15
+ * --------------------------
9
16
  */
10
17
  const { loadInstrumentMappings } = require('../../utils/sector_mapping_provider');
11
18
 
12
19
 
13
20
  class CohortCapitalFlow {
14
21
  constructor() {
15
- // We will store: { [cohortName]: Map<instrumentId, { flow_data... }> }
22
+ // { [cohortName]: Map<instrumentId, { flow_data... }> }
16
23
  this.cohortFlows = new Map();
17
- // This will be a lookup map: { [userId]: "cohortName" }
24
+ // { [userId]: "cohortName" }
18
25
  this.cohortMap = new Map();
19
26
  this.mappings = null;
20
27
  this.dependenciesLoaded = false;
28
+
29
+ // --- NEW ---
30
+ // This will store the { [ticker]: { price_change_1d_pct: 5.5 } } map
31
+ this.priceChangeMap = null;
21
32
  }
22
33
 
23
34
  /**
24
35
  * Defines the output schema for this calculation.
25
- * @returns {object} JSON Schema object
26
36
  */
27
37
  static getSchema() {
38
+ // ... (Schema remains unchanged) ...
28
39
  const flowSchema = {
29
40
  "type": "object",
30
41
  "properties": {
@@ -57,7 +68,9 @@ class CohortCapitalFlow {
57
68
  static getMetadata() {
58
69
  return {
59
70
  type: 'standard',
60
- rootDataDependencies: ['portfolio'],
71
+ // --- REVISED ---
72
+ // Removed 'insights' as it's no longer needed for price.
73
+ rootDataDependencies: ['portfolio', 'history'],
61
74
  isHistorical: true, // Needs T-1 portfolio for flow
62
75
  userType: 'all',
63
76
  category: 'gauss'
@@ -69,12 +82,13 @@ class CohortCapitalFlow {
69
82
  */
70
83
  static getDependencies() {
71
84
  return [
72
- 'cohort-definer' // from gauss (Pass 2)
85
+ 'cohort-definer', // from gauss (Pass 2)
86
+ // --- REVISED ---
87
+ 'instrument-price-change-1d' // from core (Pass 1)
73
88
  ];
74
89
  }
75
90
 
76
91
  _getPortfolioPositions(portfolio) {
77
- // We MUST use AggregatedPositions for this to get 'Invested' (portfolio percentage)
78
92
  return portfolio?.AggregatedPositions;
79
93
  }
80
94
 
@@ -86,7 +100,7 @@ class CohortCapitalFlow {
86
100
  this.cohortFlows.get(cohortName).set(instrumentId, {
87
101
  total_invested_yesterday: 0,
88
102
  total_invested_today: 0,
89
- price_change_yesterday: 0, // This is a weighted sum
103
+ price_change_yesterday: 0, // Weighted sum
90
104
  });
91
105
  }
92
106
  }
@@ -97,14 +111,22 @@ class CohortCapitalFlow {
97
111
  _loadDependencies(fetchedDependencies) {
98
112
  if (this.dependenciesLoaded) return;
99
113
 
114
+ // 1. Load Cohort Definitions
100
115
  const cohortData = fetchedDependencies['cohort-definer'];
101
116
  if (cohortData) {
102
117
  for (const [cohortName, userIds] of Object.entries(cohortData)) {
103
- for (const userId of userIds) {
104
- this.cohortMap.set(userId, cohortName);
118
+ if (Array.isArray(userIds)) {
119
+ for (const userId of userIds) {
120
+ this.cohortMap.set(userId, cohortName);
121
+ }
105
122
  }
106
123
  }
107
124
  }
125
+
126
+ // 2. Load Price Change Data
127
+ // --- REVISED ---
128
+ this.priceChangeMap = fetchedDependencies['instrument-price-change-1d'] || {};
129
+
108
130
  this.dependenciesLoaded = true;
109
131
  }
110
132
 
@@ -117,7 +139,7 @@ class CohortCapitalFlow {
117
139
 
118
140
  const cohortName = this.cohortMap.get(userId);
119
141
  if (!cohortName) {
120
- return; // This user is not in one of our defined cohorts, skip.
142
+ return; // Not in a defined cohort, skip.
121
143
  }
122
144
 
123
145
  if (!todayPortfolio || !yesterdayPortfolio) {
@@ -127,9 +149,14 @@ class CohortCapitalFlow {
127
149
  const yPos = this._getPortfolioPositions(yesterdayPortfolio);
128
150
  const tPos = this._getPortfolioPositions(todayPortfolio);
129
151
 
130
- // We must have AggregatedPositions for both days to do this calculation
131
152
  if (!yPos || !tPos) {
132
- return;
153
+ return; // Must have AggregatedPositions for both days
154
+ }
155
+
156
+ // --- REVISED ---
157
+ // We no longer need insightsMap
158
+ if (!this.priceChangeMap) {
159
+ return; // Cannot calculate price-adjusted flow
133
160
  }
134
161
 
135
162
  const yPosMap = new Map(yPos.map(p => [p.InstrumentID, p]));
@@ -145,15 +172,23 @@ class CohortCapitalFlow {
145
172
  const yP = yPosMap.get(instrumentId);
146
173
  const tP = tPosMap.get(instrumentId);
147
174
 
148
- // 'Invested' is the portfolio percentage (e.g., 5.0 = 5%)
149
175
  const yInvested = yP?.Invested || 0;
150
176
  const tInvested = tP?.Invested || 0;
151
177
 
152
178
  if (yInvested > 0) {
153
179
  asset.total_invested_yesterday += yInvested;
154
- // 'NetProfit' here is actually the 1-day P&L *as a percentage* (e.g., 0.1 for +10%)
155
- const yPriceChange = (yP?.NetProfit || 0);
156
- asset.price_change_yesterday += yPriceChange * yInvested; // Weighted sum
180
+
181
+ // --- REVISED ---
182
+ // Get the 1-day price change from our new dependency
183
+ const ticker = this.mappings.instrumentToTicker[instrumentId];
184
+ const yPriceChange_pct = (ticker && this.priceChangeMap[ticker])
185
+ ? this.priceChangeMap[ticker].price_change_1d_pct
186
+ : 0;
187
+
188
+ // Convert from percentage (5.5) to decimal (0.055)
189
+ const yPriceChange_decimal = (yPriceChange_pct || 0) / 100.0;
190
+
191
+ asset.price_change_yesterday += yPriceChange_decimal * yInvested; // Weighted sum
157
192
  }
158
193
  if (tInvested > 0) {
159
194
  asset.total_invested_today += tInvested;
@@ -169,6 +204,7 @@ class CohortCapitalFlow {
169
204
  const finalResult = {};
170
205
 
171
206
  for (const [cohortName, assetMap] of this.cohortFlows.entries()) {
207
+ // --- REVISED: Initialize cohortAssets as an object ---
172
208
  const cohortAssets = {};
173
209
  for (const [instrumentId, data] of assetMap.entries()) {
174
210
  const ticker = this.mappings.instrumentToTicker[instrumentId];
@@ -177,32 +213,32 @@ class CohortCapitalFlow {
177
213
  const { total_invested_yesterday, total_invested_today, price_change_yesterday } = data;
178
214
 
179
215
  if (total_invested_yesterday > 0) {
180
- // 1. Find the weighted average price change for this cohort/asset
181
- // e.g., (0.1 * 5.0 + 0.05 * 2.0) / (5.0 + 2.0)
182
- const avg_price_change_pct = price_change_yesterday / total_invested_yesterday;
183
-
184
- // 2. Estimate yesterday's value *after* price change
185
- // (This is what the value *would be* if no one bought or sold)
186
- const price_adjusted_yesterday_value = total_invested_yesterday * (1 + avg_price_change_pct);
187
-
188
- // 3. The difference between today's value and the price-adjusted
189
- // value is the *net capital flow*.
216
+ const avg_price_change_decimal = price_change_yesterday / total_invested_yesterday;
217
+ const price_adjusted_yesterday_value = total_invested_yesterday * (1 + avg_price_change_decimal);
190
218
  const flow_contribution = total_invested_today - price_adjusted_yesterday_value;
191
-
192
- // 4. Normalize the flow as a percentage of yesterday's capital
193
219
  const net_flow_percentage = (flow_contribution / total_invested_yesterday) * 100;
194
220
 
195
221
  if (isFinite(net_flow_percentage) && isFinite(flow_contribution)) {
196
222
  cohortAssets[ticker] = {
197
223
  net_flow_percentage: net_flow_percentage,
198
- net_flow_contribution: flow_contribution // This is the %-point flow
224
+ net_flow_contribution: flow_contribution
199
225
  };
200
226
  }
227
+ } else if (total_invested_today > 0) {
228
+ cohortAssets[ticker] = {
229
+ net_flow_percentage: Infinity, // Represents pure inflow
230
+ net_flow_contribution: total_invested_today
231
+ };
201
232
  }
202
233
  }
234
+ // --- REVISED: Match schema { "cohortName": { "assets": { ... } } } ---
235
+ // This was a bug in your original file. The schema expected an object
236
+ // with an 'assets' key, but the code was returning the map directly.
203
237
  finalResult[cohortName] = { assets: cohortAssets };
204
238
  }
205
- // Output is compact and not sharded
239
+
240
+ // --- REVISED: The schema for this calc shows the output is NOT sharded. ---
241
+ // The return should be the final object.
206
242
  return finalResult;
207
243
  }
208
244
 
@@ -211,6 +247,8 @@ class CohortCapitalFlow {
211
247
  this.cohortMap.clear();
212
248
  this.mappings = null;
213
249
  this.dependenciesLoaded = false;
250
+ // --- NEW ---
251
+ this.priceChangeMap = null;
214
252
  }
215
253
  }
216
254
 
@@ -10,6 +10,7 @@
10
10
  */
11
11
  const { loadInstrumentMappings } = require('../../utils/sector_mapping_provider');
12
12
 
13
+
13
14
  class CohortDefiner {
14
15
  constructor() {
15
16
  // We will store the full DNA for our filtered cohorts
@@ -58,7 +59,10 @@ class CohortDefiner {
58
59
  "smart_scalpers": cohortSchema,
59
60
  "fomo_chasers": cohortSchema,
60
61
  "patient_losers": cohortSchema,
61
- "fomo_bagholders": cohortSchema
62
+ "fomo_bagholders": cohortSchema,
63
+ // --- FIX [PROBLEM 9]: Add uncategorized bucket ---
64
+ "uncategorized_smart": cohortSchema,
65
+ "uncategorized_dumb": cohortSchema
62
66
  },
63
67
  "additionalProperties": cohortSchema
64
68
  };
@@ -73,14 +77,29 @@ class CohortDefiner {
73
77
  const dnaFilterData = fetchedDependencies['daily-dna-filter'];
74
78
  this.momentumData = fetchedDependencies['instrument-price-momentum-20d'];
75
79
 
76
- this.cohortIdSets = {
77
- smart: new Set(dnaFilterData?.smart_cohort_ids || []),
78
- dumb: new Set(dnaFilterData?.dumb_cohort_ids || [])
79
- };
80
+ // --- FIX [PROBLEM 6]: Validate dependency content, not just existence ---
81
+ if (dnaFilterData && dnaFilterData.smart_cohort_ids && dnaFilterData.dumb_cohort_ids) {
82
+ this.cohortIdSets = {
83
+ smart: new Set(dnaFilterData.smart_cohort_ids),
84
+ dumb: new Set(dnaFilterData.dumb_cohort_ids)
85
+ };
86
+ } else {
87
+ // Initialize with empty sets if dependency is missing or malformed
88
+ this.cohortIdSets = {
89
+ smart: new Set(),
90
+ dumb: new Set()
91
+ };
92
+ }
80
93
  }
81
94
 
82
95
  _getFomoScore(todayPortfolio, yesterdayPortfolio) {
83
96
  if (!this.mappings) return 0;
97
+
98
+ // --- FIX [PROBLEM 4 related]: Ensure momentum data is loaded ---
99
+ if (!this.momentumData) {
100
+ return 0; // Cannot calculate FOMO without momentum data
101
+ }
102
+
84
103
  const yIds = new Set((yesterdayPortfolio?.AggregatedPositions || []).map(p => p.InstrumentID));
85
104
  const newPositions = (todayPortfolio?.AggregatedPositions || []).filter(p => p.InstrumentID && !yIds.has(p.InstrumentID));
86
105
  if (newPositions.length === 0) return 0;
@@ -89,6 +108,7 @@ class CohortDefiner {
89
108
  let count = 0;
90
109
  for (const pos of newPositions) {
91
110
  const ticker = this.mappings.instrumentToTicker[pos.InstrumentID];
111
+ // --- FIX [PROBLEM 4 related]: Check momentumData[ticker] exists ---
92
112
  if (ticker && this.momentumData[ticker]) {
93
113
  fomoSum += this.momentumData[ticker].momentum_20d_pct || 0;
94
114
  count++;
@@ -165,19 +185,32 @@ class CohortDefiner {
165
185
  if (vectors.length === 0) return 0;
166
186
  const sorted = vectors.map(v => v[key]).sort((a, b) => a - b);
167
187
  const mid = Math.floor(sorted.length / 2);
188
+ // Handle even-length array by taking average of middle two
189
+ if (sorted.length % 2 === 0 && sorted.length > 0) {
190
+ return (sorted[mid - 1] + sorted[mid]) / 2;
191
+ }
168
192
  return sorted[mid];
169
193
  }
170
194
 
171
195
  getResult() {
172
196
  const cohorts = {};
197
+ const assignedSmart = new Set();
198
+ const assignedDumb = new Set();
173
199
 
174
200
  // 1. Process Smart Cohort
175
201
  const smart_median_time = this._getMedian(this.smartVectors, 'time');
202
+
176
203
  cohorts['smart_investors'] = this.smartVectors
177
204
  .filter(u => u.time >= smart_median_time)
178
- .map(u => u.userId);
205
+ .map(u => { assignedSmart.add(u.userId); return u.userId; });
206
+
179
207
  cohorts['smart_scalpers'] = this.smartVectors
180
208
  .filter(u => u.time < smart_median_time)
209
+ .map(u => { assignedSmart.add(u.userId); return u.userId; });
210
+
211
+ // --- FIX [PROBLEM 9]: Add uncategorized bucket ---
212
+ cohorts['uncategorized_smart'] = this.smartVectors
213
+ .filter(u => !assignedSmart.has(u.userId))
181
214
  .map(u => u.userId);
182
215
 
183
216
  // 2. Process Dumb Cohort
@@ -186,14 +219,19 @@ class CohortDefiner {
186
219
 
187
220
  cohorts['fomo_chasers'] = this.dumbVectors
188
221
  .filter(u => u.fomo >= dumb_median_fomo && u.bagholder < dumb_median_bag)
189
- .map(u => u.userId);
222
+ .map(u => { assignedDumb.add(u.userId); return u.userId; });
190
223
 
191
224
  cohorts['patient_losers'] = this.dumbVectors
192
225
  .filter(u => u.fomo < dumb_median_fomo && u.bagholder >= dumb_median_bag)
193
- .map(u => u.userId);
226
+ .map(u => { assignedDumb.add(u.userId); return u.userId; });
194
227
 
195
228
  cohorts['fomo_bagholders'] = this.dumbVectors
196
229
  .filter(u => u.fomo >= dumb_median_fomo && u.bagholder >= dumb_median_bag)
230
+ .map(u => { assignedDumb.add(u.userId); return u.userId; });
231
+
232
+ // --- FIX [PROBLEM 9]: Add uncategorized bucket ---
233
+ cohorts['uncategorized_dumb'] = this.dumbVectors
234
+ .filter(u => !assignedDumb.has(u.userId))
197
235
  .map(u => u.userId);
198
236
 
199
237
  // Output is a compact map of cohort_name -> [userIds]
@@ -94,20 +94,20 @@ class GaussDivergenceSignal {
94
94
  return {};
95
95
  }
96
96
 
97
- // Define which cohorts are "Smart" and which are "Dumb"
98
- // These names must match the keys from Pass 2
99
97
  const SMART_COHORTS = ['smart_investors', 'smart_scalpers'];
100
98
  const DUMB_COHORTS = ['fomo_chasers', 'patient_losers', 'fomo_bagholders'];
101
99
 
102
100
  const blendedFlows = new Map(); // Map<ticker, { smart: 0, dumb: 0 }>
103
101
 
104
- // 1. Blend all cohort flows into two buckets
102
+ // 1. Blend all cohort flows
105
103
  for (const cohortName in cohortFlows) {
106
104
  const isSmart = SMART_COHORTS.includes(cohortName);
107
105
  const isDumb = DUMB_COHORTS.includes(cohortName);
108
106
  if (!isSmart && !isDumb) continue;
109
107
 
110
- const assets = cohortFlows[cohortName]?.assets;
108
+ // --- REVISED ---
109
+ // Read from the 'assets' property, which contains the map of tickers
110
+ const assets = cohortFlows[cohortName]?.assets;
111
111
  if (!assets) continue;
112
112
 
113
113
  for (const [ticker, data] of Object.entries(assets)) {
@@ -115,7 +115,6 @@ class GaussDivergenceSignal {
115
115
  blendedFlows.set(ticker, { smart: 0, dumb: 0 });
116
116
  }
117
117
 
118
- // Use net_flow_contribution, which is the %-point flow
119
118
  const flow = data.net_flow_contribution || 0;
120
119
 
121
120
  if (isSmart) {
@@ -126,20 +125,14 @@ class GaussDivergenceSignal {
126
125
  }
127
126
  }
128
127
 
129
- // 2. Calculate final signal
128
+ // 2. Calculate final signal (logic unchanged)
130
129
  const result = {};
131
130
  for (const [ticker, data] of blendedFlows.entries()) {
132
-
133
- // The core signal is the divergence: (Smart Flow - Dumb Flow)
134
- // If Smart buys (+1) and Dumb sells (-1), score is +2.
135
- // If Smart sells (-1) and Dumb buys (+1), score is -2.
136
131
  const divergence = data.smart - data.dumb;
137
-
138
- // Normalize the score to a -10 to +10 range
139
132
  const gauss_score = this._normalize(divergence);
140
133
 
141
134
  let signal = "Neutral";
142
- if (gauss_score > 7.0) signal = "Strong Buy"; // e.g., > 1.5% net divergence
135
+ if (gauss_score > 7.0) signal = "Strong Buy";
143
136
  else if (gauss_score > 2.0) signal = "Buy";
144
137
  else if (gauss_score < -7.0) signal = "Strong Sell";
145
138
  else if (gauss_score < -2.0) signal = "Sell";
@@ -152,7 +145,6 @@ class GaussDivergenceSignal {
152
145
  };
153
146
  }
154
147
 
155
- // Final output is compact and non-sharded.
156
148
  return result;
157
149
  }
158
150
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aiden-shared-calculations-unified",
3
- "version": "1.0.78",
3
+ "version": "1.0.80",
4
4
  "description": "Shared calculation modules for the BullTrackers Computation System.",
5
5
  "main": "index.js",
6
6
  "files": [