File size: 5,519 Bytes
9fbb3f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
const BASE = "";

let _token = null;

export function setToken(token) {
  _token = token;
}

function authHeaders() {
  const headers = { "Content-Type": "application/json" };
  if (_token) {
    headers["Authorization"] = `Bearer ${_token}`;
  }
  return headers;
}

async function post(path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method: "POST",
    headers: authHeaders(),
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`${res.status}: ${text}`);
  }
  return res;
}

async function get(path) {
  const res = await fetch(`${BASE}${path}`, {
    headers: authHeaders(),
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`${res.status}: ${text}`);
  }
  return res;
}

export async function computeAnalysis(portfolio) {
  const res = await post("/analysis/compute", portfolio);
  return res.json();
}

export async function computeFrontier(portfolio) {
  const res = await post("/analysis/frontier", portfolio);
  return res.json();
}

export async function runAgents(portfolio, userProfile, financialGoal) {
  const res = await post("/agents/run", {
    portfolio,
    user_profile: userProfile,
    financial_goal: financialGoal,
  });
  return res.json();
}

export async function askCIO(question, metrics, inferences, frontierSummary, userProfile, goalProjection) {
  const res = await post("/agents/cio", {
    question,
    metrics,
    inferences,
    frontier_summary: frontierSummary,
    user_profile: userProfile,
    goal_projection: goalProjection,
  });
  return res.json();
}

export async function textToSpeech(text, voice = "Rachel") {
  const res = await post("/tts/report", { text, voice });
  return res.blob();
}

export async function loadUserData() {
  const res = await get("/user/data");
  return res.json();
}

export async function saveUserData(data) {
  const res = await post("/user/data", data);
  return res.json();
}

// ── Insights ──────────────────────────────────────────────

export async function fetchSectorExposure(tickers, weights) {
  const res = await post("/insights/sector-exposure", { tickers, weights });
  return res.json();
}

export async function fetchDividends(tickers, weights, investment_amount = 100000) {
  const res = await post("/insights/dividends", { tickers, weights, investment_amount });
  return res.json();
}

export async function fetchRebalancing(tickers, target_weights, portfolio_value = 100000, drift_threshold = 0.05) {
  const res = await post("/insights/rebalancing", { tickers, target_weights, portfolio_value, drift_threshold });
  return res.json();
}

export async function fetchMacroCorrelations(tickers, weights, start_date) {
  const res = await post("/insights/macro-correlations", { tickers, weights, start_date });
  return res.json();
}

export async function fetchTaxHarvest(tickers, weights, portfolio_value = 100000, cost_basis_date = "2020-01-01", tax_rate = 0.15) {
  const res = await post("/insights/tax-harvest", { tickers, weights, portfolio_value, cost_basis_date, tax_rate });
  return res.json();
}

// ── PDF report ──────────────────────────────────────────────

export async function generatePDFReport(reportData) {
  const res = await post("/reports/pdf", reportData);
  return res.blob();
}

// ── Portfolio versions ──────────────────────────────────────

export async function savePortfolioSnapshot(tickers, weights, label, performance) {
  const res = await post("/portfolio/versions/save", { tickers, weights, label, performance });
  return res.json();
}

export async function listPortfolioSnapshots() {
  const res = await get("/portfolio/versions/list");
  return res.json();
}

// ── Alerts ──────────────────────────────────────────────────

export async function checkAlerts(portfolio, rules) {
  const res = await post("/alerts/check", { portfolio, rules });
  return res.json();
}

// ── SSE streaming agents ────────────────────────────────────

export function streamAgents(portfolio, userProfile, financialGoal, onEvent) {
  const body = JSON.stringify({
    portfolio,
    user_profile: userProfile,
    financial_goal: financialGoal,
  });

  fetch(`${BASE}/agents/run-stream`, {
    method: "POST",
    headers: authHeaders(),
    body,
  }).then(async (response) => {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });

      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      let currentEvent = null;
      for (const line of lines) {
        if (line.startsWith("event: ")) {
          currentEvent = line.slice(7).trim();
        } else if (line.startsWith("data: ") && currentEvent) {
          try {
            const data = JSON.parse(line.slice(6));
            onEvent(currentEvent, data);
          } catch { /* skip malformed */ }
          currentEvent = null;
        }
      }
    }
  });
}