@mnemopay/sdk 0.9.3 → 1.0.0

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,253 @@
1
+ /**
2
+ * Behavioral Finance Engine — Psychology-Backed Financial Intelligence
3
+ *
4
+ * Implements Nobel Prize-winning behavioral economics research to help
5
+ * AI agents (and their human principals) make better financial decisions.
6
+ *
7
+ * Core models implemented:
8
+ * 1. Prospect Theory value function (Kahneman & Tversky, 1979/1992)
9
+ * 2. Quasi-hyperbolic discounting (Laibson, 1997)
10
+ * 3. Dynamic cooling-off periods (MnemoPay original)
11
+ * 4. Loss-framed nudges (Tversky & Kahneman, 1981)
12
+ * 5. Commitment devices / Save More Tomorrow (Thaler & Benartzi, 2004)
13
+ * 6. Regret memory + prediction (Zeelenberg & Pieters, 2007)
14
+ * 7. Overconfidence brake (Barber & Odean, 2000)
15
+ * 8. Intelligent expense reframing (Thaler, 1985 mental accounting)
16
+ * 9. Endowed progress effect (Nunes & Dreze, 2006)
17
+ * 10. Anti-herd alerting (Shiller, 2000)
18
+ *
19
+ * All parameters sourced from peer-reviewed publications with exact citations.
20
+ * Zero external dependencies.
21
+ *
22
+ * References (selected):
23
+ * - Tversky & Kahneman (1992). "Advances in Prospect Theory"
24
+ * - Laibson (1997). "Golden Eggs and Hyperbolic Discounting"
25
+ * - Thaler & Benartzi (2004). "Save More Tomorrow"
26
+ * - Barber & Odean (2000). "Trading Is Hazardous to Your Wealth"
27
+ * - Madrian & Shea (2001). "The Power of Suggestion"
28
+ */
29
+ export interface ProspectValue {
30
+ /** The psychologically perceived value (positive = gain, negative = loss) */
31
+ value: number;
32
+ /** Original monetary amount */
33
+ amount: number;
34
+ /** Whether this is a gain or loss */
35
+ domain: "gain" | "loss";
36
+ /** Loss aversion multiplier applied (lambda) */
37
+ lossAversion: number;
38
+ /** Explanation for the agent/user */
39
+ explanation: string;
40
+ }
41
+ export interface CoolingOffResult {
42
+ /** Whether a cooling-off period is recommended */
43
+ recommended: boolean;
44
+ /** Hours to wait before executing */
45
+ hours: number;
46
+ /** Reason for the recommendation */
47
+ reason: string;
48
+ /** Risk level of the purchase */
49
+ riskLevel: "low" | "medium" | "high" | "extreme";
50
+ /** Estimated regret probability based on history */
51
+ regretProbability: number;
52
+ }
53
+ export interface CommitmentResult {
54
+ /** Projected savings rates over time */
55
+ projectedRates: number[];
56
+ /** Projected total savings at each cycle */
57
+ projectedSavings: number[];
58
+ /** Final rate after all cycles */
59
+ finalRate: number;
60
+ /** Explanation of the SMarT plan */
61
+ explanation: string;
62
+ }
63
+ export interface LossFrame {
64
+ /** The loss-framed message */
65
+ message: string;
66
+ /** Equivalent gain message for comparison */
67
+ gainMessage: string;
68
+ /** Expected effectiveness multiplier vs gain framing */
69
+ effectivenessMultiplier: number;
70
+ /** Days of goal delay this spending causes */
71
+ goalDelayDays: number;
72
+ }
73
+ export interface ReframedExpense {
74
+ /** Original amount and frequency */
75
+ original: {
76
+ amount: number;
77
+ frequency: string;
78
+ };
79
+ /** Reframed amounts at different timescales */
80
+ daily: number;
81
+ weekly: number;
82
+ monthly: number;
83
+ annual: number;
84
+ /** The most psychologically impactful frame */
85
+ impactFrame: string;
86
+ /** Opportunity cost: what else this money could do */
87
+ opportunityCost: string;
88
+ }
89
+ export interface RegretEntry {
90
+ /** Purchase amount */
91
+ amount: number;
92
+ /** Category of purchase */
93
+ category: string;
94
+ /** Self-rated regret 0-10 (10 = deeply regret) */
95
+ regretScore: number;
96
+ /** ISO timestamp */
97
+ timestamp: string;
98
+ }
99
+ export interface RegretPrediction {
100
+ /** Predicted regret probability 0-1 */
101
+ probability: number;
102
+ /** Confidence in the prediction 0-1 */
103
+ confidence: number;
104
+ /** Historical context */
105
+ historicalRegretRate: number;
106
+ /** Category-specific regret rate */
107
+ categoryRegretRate: number;
108
+ /** Recommendation */
109
+ recommendation: string;
110
+ /** Whether to invoke cooling-off */
111
+ triggerCoolingOff: boolean;
112
+ }
113
+ export interface TradeEntry {
114
+ /** Timestamp of trade */
115
+ timestamp: number;
116
+ /** Trade amount */
117
+ amount: number;
118
+ /** Direction */
119
+ direction: "buy" | "sell";
120
+ /** Asset or category */
121
+ asset: string;
122
+ /** Realized P/L if closed */
123
+ realizedPL?: number;
124
+ }
125
+ export interface OverconfidenceResult {
126
+ /** Whether overconfidence is detected */
127
+ detected: boolean;
128
+ /** Current trading frequency (trades per period) */
129
+ frequency: number;
130
+ /** Optimal frequency (derived from historical performance) */
131
+ optimalFrequency: number;
132
+ /** Estimated annual performance drag from overtrading (percentage points) */
133
+ performanceDrag: number;
134
+ /** Disposition effect detected (holding losers, selling winners) */
135
+ dispositionEffect: boolean;
136
+ /** Recommendation */
137
+ recommendation: string;
138
+ }
139
+ export interface AssetMetrics {
140
+ /** Current price-to-earnings ratio */
141
+ peRatio: number;
142
+ /** Historical mean P/E */
143
+ historicalMeanPE: number;
144
+ /** Historical standard deviation of P/E */
145
+ historicalStdPE: number;
146
+ /** Recent price change (percent, 30-day) */
147
+ recentReturn30d: number;
148
+ /** Volume spike (current vs average) */
149
+ volumeRatio: number;
150
+ }
151
+ export interface HerdAlert {
152
+ /** Whether herd behavior is detected */
153
+ detected: boolean;
154
+ /** Severity: low, medium, high */
155
+ severity: "low" | "medium" | "high";
156
+ /** CAPE-like ratio relative to mean */
157
+ valuationSigma: number;
158
+ /** Alert message */
159
+ message: string;
160
+ /** Contrarian recommendation */
161
+ recommendation: string;
162
+ }
163
+ export interface FinancialGoal {
164
+ /** Goal name */
165
+ name: string;
166
+ /** Target amount */
167
+ target: number;
168
+ /** Current progress toward goal */
169
+ current: number;
170
+ /** Monthly savings rate toward this goal */
171
+ monthlySavings: number;
172
+ }
173
+ export interface EndowedProgress {
174
+ /** Percentage complete toward goal */
175
+ percentComplete: number;
176
+ /** Framed message using endowed progress effect */
177
+ message: string;
178
+ /** Expected completion boost from endowed framing (Nunes & Dreze: 34% vs 19%) */
179
+ expectedCompletionRate: number;
180
+ }
181
+ export interface BehavioralConfig {
182
+ /** Prospect theory: loss aversion coefficient. Tversky & Kahneman 1992: 2.25 */
183
+ lambda: number;
184
+ /** Prospect theory: gain curvature. T&K 1992: 0.88 */
185
+ alpha: number;
186
+ /** Prospect theory: loss curvature. T&K 1992: 0.88 */
187
+ beta_pt: number;
188
+ /** Quasi-hyperbolic: present bias. Laibson 1997: 0.70 */
189
+ beta_discount: number;
190
+ /** Quasi-hyperbolic: exponential discount. Laibson 1997: 0.96 */
191
+ delta: number;
192
+ /** Base cooling-off hours for amount = income. Default 2 */
193
+ baseCoolingHours: number;
194
+ /** Minimum purchase amount to trigger cooling-off. Default 100 */
195
+ coolingThreshold: number;
196
+ /** Overconfidence: max trades per month before alert. Barber & Odean: monthly turnover > 8.8% */
197
+ maxTradesPerMonth: number;
198
+ /** Annual performance drag per excess trade (basis points). B&O 2000: ~6.5pp for highest quartile */
199
+ excessTradeCostBps: number;
200
+ }
201
+ export declare const DEFAULT_BEHAVIORAL_CONFIG: BehavioralConfig;
202
+ export declare class BehavioralEngine {
203
+ readonly config: BehavioralConfig;
204
+ private regretHistory;
205
+ private static readonly MAX_REGRET_HISTORY;
206
+ constructor(config?: Partial<BehavioralConfig>);
207
+ prospectValue(amount: number): ProspectValue;
208
+ /**
209
+ * Compare gain vs loss framing of the same amount.
210
+ * Shows why loss framing is 2.25x more effective for behavior change.
211
+ */
212
+ compareFraming(amount: number): {
213
+ gainValue: number;
214
+ lossValue: number;
215
+ ratio: number;
216
+ insight: string;
217
+ };
218
+ discount(periods: number): number;
219
+ /**
220
+ * Calculate the present-biased value of a future amount.
221
+ * Shows how much a rational agent values $X received in T periods.
222
+ */
223
+ presentValue(futureAmount: number, periods: number): {
224
+ discountedValue: number;
225
+ discountFactor: number;
226
+ lostValue: number;
227
+ explanation: string;
228
+ };
229
+ coolingOff(amount: number, monthlyIncome: number, userBeta?: number): CoolingOffResult;
230
+ lossFrame(spendAmount: number, goal: FinancialGoal): LossFrame;
231
+ commitmentDevice(currentSavingsRate: number, raisePercent: number, cycles: number): CommitmentResult;
232
+ recordRegret(entry: RegretEntry): void;
233
+ predictRegret(amount: number, category: string): RegretPrediction;
234
+ overconfidenceBrake(trades: TradeEntry[], periodDays?: number): OverconfidenceResult;
235
+ reframeExpense(amount: number, frequency: "daily" | "weekly" | "monthly" | "annual"): ReframedExpense;
236
+ endowedProgress(goal: FinancialGoal): EndowedProgress;
237
+ antiHerdAlert(metrics: AssetMetrics): HerdAlert;
238
+ private _computeRegretRatio;
239
+ private _validateConfig;
240
+ /** Get regret history for analysis */
241
+ getRegretHistory(): RegretEntry[];
242
+ /** Serialize for persistence */
243
+ serialize(): {
244
+ config: BehavioralConfig;
245
+ regretHistory: RegretEntry[];
246
+ };
247
+ /** Deserialize with validation */
248
+ static deserialize(data: {
249
+ config?: Partial<BehavioralConfig>;
250
+ regretHistory?: RegretEntry[];
251
+ }): BehavioralEngine;
252
+ }
253
+ //# sourceMappingURL=behavioral.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"behavioral.d.ts","sourceRoot":"","sources":["../src/behavioral.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAIH,MAAM,WAAW,aAAa;IAC5B,6EAA6E;IAC7E,KAAK,EAAE,MAAM,CAAC;IACd,+BAA+B;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,qCAAqC;IACrC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,gDAAgD;IAChD,YAAY,EAAE,MAAM,CAAC;IACrB,qCAAqC;IACrC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,gBAAgB;IAC/B,kDAAkD;IAClD,WAAW,EAAE,OAAO,CAAC;IACrB,qCAAqC;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAC;IACf,iCAAiC;IACjC,SAAS,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;IAC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