SPB Git forge

spb/pdb-api

Public
1commits 1branches 0releases
436.0 KBsize
maindefault branch
5 h agolast push
JavaScript 58.4% Python 26.8% CSS 7.5% Objective-C 3% R 2.6% HTML 1.7%
5.6 KB · 112 lines objective-c
Raw Blame History
1%% pdb_api.m — utiliser la PDB API (SEC Project Intelligence Database, UQO) dans MATLAB2%  MATLAB R2018a ou plus récent (webread / webwrite / jsondecode). Aucun toolbox requis.3%  Usage : ouvrir ce fichier, remplacer KEY, exécuter section par section (Ctrl+Entrée).4%  Les fonctions pdb_get / pdb_sql / pdb_all sont définies en fin de fichier (fonctions locales de script).56BASE = "https://www.pdb-api.co/v1";7KEY  = getenv("PDB_API_KEY"); if isempty(KEY), KEY = "VOTRE_CLE"; end89%% 1. Vérifier le service et la clé10disp(pdb_get(BASE, KEY, "health"))11ov = pdb_get(BASE, KEY, "stats").overview;12fprintf("%d projets, %d mentions, %d entreprises\n", ov.projects, ov.mentions, ov.companies);1314%% 2. Centres de données > 500 M$, du plus gros au plus petit15r  = pdb_get(BASE, KEY, "projects", type="data_center", min_amount=5e8, sort="amount", limit=10);16dc = struct2table(r.items);          % tableau MATLAB17disp(dc(:, {'ticker','project_name','canonical_location','total_amount_usd','first_seen'}))1819%% 3. Tout un secteur (pagination automatique) puis agrégation20util = pdb_all(BASE, KEY, "projects", sector="Utilities");        % ~1 956 lignes21G = groupsummary(util, "project_type", "sum", "total_amount_usd");22G = sortrows(G, "GroupCount", "descend");23disp(G(1:10, :))2425%% 4. Export CSV direct (le plus simple pour un jeu de données complet)26opts = weboptions("HeaderFields", ["X-API-Key", KEY], "ContentType", "text", "Timeout", 120);27csvText = webread(BASE + "/projects/export.csv", "type", "plant_construction", opts);28fid = fopen("usines.csv", "w"); fwrite(fid, csvText); fclose(fid);29usines = readtable("usines.csv", "TextType", "string");30fprintf("usines : %d lignes\n", height(usines));3132%% 5. Fiche d'un projet : chronologie et projets similaires33p1    = pdb_get(BASE, KEY, "projects", ticker="TSLA", q="energy storage", limit=1);34fiche = pdb_get(BASE, KEY, "projects/" + string(p1.items(1).project_id));35fprintf("%s — %s\n", fiche.project.project_name, fiche.project.status);36disp(struct2table(fiche.timeline)(:, {'filing_date','form_type','status','amount_usd'}))37disp(struct2table(fiche.similar)(:, {'score','ticker','project_name'}))3839%% 6. Profil d'une entreprise (ticker ou CIK)40duk = pdb_get(BASE, KEY, "companies/DUK");41disp(struct2table(duk.by_type)(:, {'label','n','amount_usd'}))42figure; bar([duk.by_year.n]); xticklabels(string([duk.by_year.year])); xticks(1:numel(duk.by_year));43title("Duke Energy — mentions par année"); ylabel("mentions");4445%% 7. Recherche sémantique (langage naturel, anglais recommandé)46sem = pdb_get(BASE, KEY, "search/semantic", q="battery cell factory", k=5);47disp(struct2table(sem.items)(:, {'score','ticker','project_name'}))4849%% 8. SQL libre (DuckDB, lecture seule) -> table50ia = pdb_sql(BASE, KEY, join([ ...51    "select year(filing_date) as yr, count(*) n", ...52    "from project_mentions where project_type = 'ai_initiative'", ...53    "group by 1 order by 1"], " "));54figure; plot(ia.yr, ia.n, "-o"); xlabel("année"); ylabel("mentions"); title("Initiatives IA dans les filings");5556%% 9. Panel entreprise × année pour l'économétrie57panel = pdb_sql(BASE, KEY, join([ ...58    "select cik, any_value(ticker) ticker, any_value(sector) sector,", ...59    "       year(first_seen) as yr, count(*) n_projets, sum(total_amount_usd) capital_usd", ...60    "from projects group by 1, 4 order by 1, 4"], " "), 5000);61fprintf("panel : %d lignes\n", height(panel));62% mdl = fitlm(panel, "n_projets ~ yr + sector");   % Statistics and Machine Learning Toolbox6364%% 10. Graphe : projets rattachés au Texas65tx = pdb_get(BASE, KEY, "graph/node/L:texas", limit=500);66fprintf("degré de L:texas : %d\n", tx.degree);67disp(struct2table(tx.edges)(1:6, {'rel','neighbor_type','neighbor_label'}))6869%% ------------------------------------------------------------------ fonctions locales70function out = pdb_get(base, key, path, varargin)71% GET générique : pdb_get(BASE, KEY, "projects", type="data_center", limit=10)72    opts = weboptions("HeaderFields", ["X-API-Key", key], "ContentType", "json", "Timeout", 120);73    args = {};74    for i = 1:2:numel(varargin)75        v = varargin{i+1};76        if isnumeric(v), v = num2str(v, "%.10g"); end77        args(end+1:end+2) = {char(varargin{i}), char(string(v))};78    end79    try80        out = webread(base + "/" + path, args{:}, opts);81    catch e82        error("PDB API : %s", e.message);      % 401 = clé invalide, 404 = introuvable, 429 = trop de requêtes83    end84end8586function T = pdb_sql(base, key, sql, limit)87% Requête SQL de lecture -> table MATLAB88    if nargin < 4, limit = 500; end89    opts = weboptions("HeaderFields", ["X-API-Key", key], "MediaType", "application/json", "ContentType", "json", "Timeout", 120);90    res = webwrite(base + "/sql", struct("sql", sql, "limit", limit), opts);91    if isempty(res.rows), T = table(); return; end92    rows = res.rows;93    if iscell(rows), rows = vertcat(rows{:}); end      % cellules si types mixtes94    T = cell2table(num2cell(rows), "VariableNames", matlab.lang.makeValidName(string(res.columns)));95    if iscell(rows) || ~isnumeric(rows)96        T = cell2table(rows, "VariableNames", matlab.lang.makeValidName(string(res.columns)));97    end98end99100function T = pdb_all(base, key, path, varargin)101% Pagination automatique (500 par page) -> table complète102    offset = 0; parts = {};103    while true104        page = pdb_get(base, key, path, varargin{:}, "limit", 500, "offset", offset);105        if isempty(page.items), break; end106        parts{end+1} = struct2table(page.items, "AsArray", true); %#ok<AGROW>107        offset = offset + numel(page.items);108        if offset >= page.total, break; end109    end110    T = vertcat(parts{:});111end112