Compare commits
28
Commits
b24f132210
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2a5149788 | ||
|
|
bf15c709ea | ||
|
|
6bd5d6cc69 | ||
|
|
dbe5cea9ae | ||
|
|
12d26c5d68 | ||
|
|
3ee26e5a85 | ||
|
|
3f67cc7ed5 | ||
|
|
11f54276b3 | ||
|
|
c4bcc8f42c | ||
|
|
b9b3b9bf4e | ||
|
|
7837ac6631 | ||
|
|
c902e14107 | ||
|
|
74d05009fb | ||
|
|
c660559f74 | ||
|
|
9a4c7cc57c | ||
|
|
88dae754ca | ||
|
|
59245ee54d | ||
|
|
c4178fe779 | ||
|
|
affc65cd67 | ||
|
|
b7b16c9448 | ||
|
|
382c980c35 | ||
|
|
8c247c7ea4 | ||
|
|
96b4ccbe1d | ||
|
|
3f8cc91da9 | ||
|
|
80b8fa8bf9 | ||
|
|
84a873f3bc | ||
|
|
264fbf164b | ||
|
|
2aeb0e5674 |
@@ -26,7 +26,7 @@ Agent-first toolkit for advising a Prosperous Universe player. The player asks q
|
||||
- Scope: whole universe supported; default exchange from `DEFAULT_CX` (AI1 = Antares), `--cx` to change.
|
||||
|
||||
## Layout
|
||||
- `CLAUDE.md` this file; `README.md` for humans.
|
||||
- `CLAUDE.md` this file; `README.md` for humans (short pitch), `docs/usage.md` the human tool/setup reference.
|
||||
- `docs/` GAME and toolkit knowledge, safe to publish: `mechanics.md` (verified rules), `saturation-design.md` (market model), `decisions.md` (toolkit decisions and guardrails), `roadmap.md`.
|
||||
- `empire/` (**gitignored**) OUR game state, nothing here goes public: `PROFILE.md`, `state/company.yaml` (synced from FIO), `plans/` (own plan specs), `docs/` (handoffs, build plans, personal notes).
|
||||
- `puga/` library; `tools/` CLIs; `plans/examples/` generic plan specs (also test fixtures); `state/company.example.yaml` example state; `tests/`; `data/` (gitignored fetched data cache); `ref/` (gitignored PRUNplanner source).
|
||||
@@ -35,18 +35,46 @@ Agent-first toolkit for advising a Prosperous Universe player. The player asks q
|
||||
## Library use (not just CLI)
|
||||
For anything the CLI tools don't expose (custom what-ifs, cost breakdowns with wages/capex, ad-hoc market checks) import `puga.*` directly in a short inline script instead of stretching a tool's flags. See `docs/library.md` for the module map and patterns; most non-trivial answers in this project came from a `python - <<EOF` block, not a CLI flag.
|
||||
|
||||
## Self-improve the harness
|
||||
If you catch yourself writing similar ad-hoc `python - <<EOF` code for the same kind of workload more than once in a session (a reverse recipe lookup, a planet/resource search, a marginal-ROI diff, a jump-distance check), stop and abstract it into a `puga/` function plus a `tools/*.py` CLI instead of repeating it by hand again. This is exactly how `tools/route.py`, `tools/whatif.py`, `tools/chain.py --consumers` and `tools/planet.py` got built - noticing the repeated-by-hand pattern, then promoting it. Register the new tool in this file's Tools list and in `docs/roadmap.md`; add a matching entry to `docs/library.md` if it's a new `puga/` module. This is the harness improving itself through use, not a one-off - keep doing it.
|
||||
|
||||
## Tools
|
||||
Run as `puga <tool> ...` (e.g. `puga scan --min-n 3`, `puga plan pull <uuid>`); the `tools/x.py` paths below are the same programs.
|
||||
- `tools/state.py sync|show` refreshes `empire/state/company.yaml` from live FIO (cash, permits, buildings, real production efficiency, storage, ships).
|
||||
- `tools/plan_push.py` builds/validates PRUNplanner plans from YAML specs (`plans/examples/`, `empire/plans/`). Dry run by default; `--apply` only after the player says yes; only `[PuGa]`-named plans are created/updated/deleted (`delete <uuid>`, only when asked); `list` shows the account's plans, `pull <uuid> -o file.yaml` reads a plan back into a YAML spec including edits made in the PRUNplanner UI. Workflow: push a plan, the player refines it in the UI and saves, then `pull` / `simulate --uuid` read it back and you continue from there.
|
||||
- `tools/simulate.py <spec.yaml | --uuid U> [--off EXT,SME] [--basis real|uni30|vwap30|ask|...]` replica of PRUNplanner's simulator (efficiency, workforce, material I/O, profit). Flows and efficiency verified exact vs screenshots; profit within ~2%. The NEW CAPEX line = planned minus already built (from state), the honest payback; ignore the plan-level ROI (PRUNplanner always adds a core module). `--uuid` reads the SAVED plan from the account (UI edits must be saved first).
|
||||
- `tools/scan.py` DEPTH-AWARE recipe scan (use this): buildings the market could absorb, ROI for our own size, patient prices, ask-walked inputs. Fully staffed AND understaffed variants by default (`--staffing`), freight netted out (`--trip-cost`, `--cargo`), HQ/COGC/experts/faction, `--planet ID` adds that planet's extraction, fertility and COGC (a planet not in state is a new base: no HQ, permits+1), `--deprec 60` prices demolish-later. `--min-n` is ONLY a noise filter on market capacity (use 3, ideally 10); ROI is always for our own size (`--own`, default 1 building), never at the filtered scale. Below 1 lets sub-building junk in. `--json rows.json` feeds `persistence.py`. Library: `puga/saturation.py`.
|
||||
- `tools/scan.py` DEPTH-AWARE recipe scan (use this): buildings the market could absorb, ROI for our own size, patient prices, ask-walked inputs. Fully staffed AND understaffed variants by default (`--staffing`), freight netted out (`--trip-cost`, `--cargo`), HQ/COGC/experts/faction, `--planet ID` adds that planet's extraction, fertility and COGC (a planet not in state is a new base: no HQ, permits+1), `--deprec 60 [--reclaim-frac 0.65]` prices demolish-later: amortizes the UNRECLAIMED capex (not full capex - real FIO reclaim data shows 50-86% comes back even at near-100% condition, see `docs/decisions.md`) over the holding period. `--min-n` is ONLY a noise filter on market capacity (use 3, ideally 10); ROI is always for our own size (`--own`, default 1 building), never at the filtered scale. Below 1 lets sub-building junk in. `--json rows.json` feeds `persistence.py`. `--sort area` ranks by profit/day per tile of BUILDING area (FIO `AreaCost`, not hab area) - once an existing base's area cap binds, this is the real allocation criterion, not %-yield/payback (a higher-%% recipe needing much more area can lose to a lower-%% one that fits more densely). `--max-impact 10` (stage 2 only) flags `[exit-thin]` when the LIVE bid book can't absorb even 1 day of 1 building's output within that %% (`puga.saturation.max_units_at_impact`) - an INSTANT-DUMP/panic-exit liquidity check, not production price impact (that's what `market`/`lim` already measure via real 30-day flow); a single snapshot (orders change constantly), so it's a WARNING, not folded into `market`/`lim`. Library: `puga/saturation.py`.
|
||||
- `tools/history.py TICKER` monthly margin history of the recipe producing TICKER; `tools/persistence.py rows.json` re-prices scan rows over history (mean ROI 7/14/30/90/180d, payback, net gain over 7 and 14 days, % days profitable). ALWAYS check persistence before recommending: current margins are often a spike.
|
||||
- `tools/buy.py <spec.yaml|--uuid U> --days N` cash-aware shopping list: construction gap (plan vs empire state's built buildings) plus N days of the plan's NET operating stock (via `simulate()`, so self-produced inputs like AL net against consumption), priced at real fill cost, checked against cash/reserve. Pass a plan covering the WHOLE base for restocking, not just a new addition (see `docs/library.md`).
|
||||
- `tools/sell.py TICKER QTY [--tight]` where to post an ask, expected hours to clear, and a self-contained tranche split: aggressive (undercut) tranche capped at the median 30d-volume quantile (or 80th pct with `--tight`, for when a payment is imminent and stockout risk outweighs a few points of margin), patient tranche priced just under the next competitor tier. `--show-bid` for the instant-bid comparison (off by default; usually worse).
|
||||
- `tools/sell.py TICKER QTY [--tight]` where to post an ask, expected hours to clear, and a self-contained tranche split: aggressive (undercut) tranche capped at the median 30d-volume quantile (or 80th pct with `--tight`, for when a payment is imminent and stockout risk outweighs a few points of margin), patient tranche priced just under the next competitor tier. `--show-bid` for the instant-bid comparison (off by default; usually worse). `--tiers [--rate R]` answers "is it ever worth pricing above the current market": combines queue-depth days (real resting quantity, within the traded range) with an EMPIRICAL first-passage estimate from the ticker's own multi-year price history (no random-walk assumption - a driftless-walk closed form was tried first and backtested wrong, see `docs/decisions.md`'s "Optimal ask price" entry), via max (the binding constraint). `rate` should be the player's REALIZED capital growth rate (read off their equity-growth chart, default 0.05), not a theoretical build ROI. Library: `puga/history.py::empirical_touch()`.
|
||||
- `tools/network.py <chain.yaml>` models a MULTI-BASE chain (e.g. mine LST at Nike, ship it, make BSE at Deimos): simulates each base, nets a transferred material's producer-surplus against consumer-need, charges real freight only on what's moved (`puga/network.py`). Spec and worked example in `plans/chains/`. `cm_free: true` per base for a new founding covered by a Core Module Kit. profit/day per base is the WHOLE plan, not the marginal addition - diff against the base's plan without the addition for a true marginal ROI.
|
||||
- `tools/whatif.py <before.yaml> [--add BUILDING:AMOUNT[:RECIPE]] [--infra HB1:+1] [--after after.yaml]` marginal payback of adding to a base you already run (whole-plan diff, same rule as buy/runway - pass the WHOLE base, not just the addition). `--add` mutates a copy of `before` in-memory (reuses an existing building's recipe if omitted, e.g. `--add POL:1`); `--after` takes a second full spec instead. Flags any workforce tier the addition newly overloads (vs. a pre-existing one, which it won't flag) - this is what caught the PP2/pioneer-housing and 2nd-CHP/pioneer-housing surprises by hand before this tool existed. Charges marginal freight too (real fuel model, CX-to-planet, via `puga.shipping`): a CONTINUOUS amortized rate (extra tonnage/cargo-hold x round-trip cost), scaling with the addition's own tonnage, not a step function - a small addition adds a small continuous freight cost, not exactly zero, and a recipe whose ROI looks great only because its freight cost was left out still gets caught.
|
||||
- `tools/runway.py <spec.yaml|--uuid U> [--no-inbound]` days of runway per material before a base stalls: real NET consumption via `simulate()` (self-produced inputs excluded), base storage, PLUS (by default) any ship currently flying to that planet, auto-detected from live flight data (`tools/state.py` tags each ship with its flight origin/destination). Pass the WHOLE base plan (see `docs/library.md`).
|
||||
- `tools/chain.py TICKER` make-vs-buy cost tree plus sourcing depth of inputs.
|
||||
- `tools/undervalued.py [--cx AI1] [--min-vol 5] [--top 20]` manufactured goods currently priced below implied production cost - buy-and-hold-for-reversion candidates, not build candidates. **Expected ROI is much lower than production builds** (~0.10-0.24%/day backtested, vs 14-29%/day for the builds this toolkit recommends) - only worth it for excess idle capital once better-yielding builds are exhausted. Library: `puga/undervalued.py`.
|
||||
- `tools/chain.py TICKER` make-vs-buy cost tree plus sourcing depth of inputs. `--consumers` flips it: what recipes EAT this ticker as an input, with each output's market depth - for "is there a deeper downstream product worth chaining into" questions (e.g. checking BOR/BSE/BBH for further processing).
|
||||
- `tools/planet.py RESOURCE [--min-factor X] [--from PLANET] [--top N]` ranks planets for a raw resource by extraction factor, with founding cost straight from FIO's own `BuildRequirements` (real environment-extras materials, not guessed temperature/pressure thresholds - PRUNplanner's own calculations don't model those either) and optional jump distance via `tools/route.py`. Pure-factor ranking alone is misleading - the best-factor planets are often thousands of ly away; always pass `--from` an existing base. Library: `puga/planet.py`.
|
||||
- `tools/route.py <from planet/system> <to planet/system>` jump-distance route (not a PRUNplanner feature - built from FIO's `/systemstars` graph, Dijkstra by straight-line ly since that's what FTL fuel/time scale with, jump count reported alongside). Accepts planet natural IDs, system natural IDs, or names. Library: `puga/route.py`.
|
||||
- `tools/shiptrip.py SHIP FROM TO [--v0 X --v1 Y]` the simple ship-trip tool: give a ship registration + start + stop, it works out jumps/charges/landing fuel itself via `tools/route.py`'s jump graph and reports fuel cost (defaults to max sliders). Direct-jump routes only - an unconnected pair means gateway-only, and it tells you exactly what to read off the live APEX Ship Flight Control screen (the LOCK fee - genuinely not available via FIO/PRUNplanner, confirmed by inspecting both) and what to run instead (`tools/shipcost.py`). Warns if the given ship's live specs (FIO `/ship/ships/{user}`) don't match the calibrated hull/reactor.
|
||||
- `tools/shipcost.py [--jumps N --charges N] [--v0 X --v1 Y] [--gateways N --lock-fee AMOUNT:CURRENCY] [--to PLANET]` the explicit/manual version: fuel/AIC cost of a ship trip from physics parameters you already know (jump count, slider values, gateway LOCK fees read off the live game) - use `tools/shiptrip.py` instead if you just want "ship X from A to B". Landing fuel is a measured-planet lookup via `--to`, independent of whether the route used jumps or gateways. Both tools scoped to this account's one hull/reactor (blueprint BP-STRT-0000, shared by both ships AVI-07JFB/AVI-07JFC); open caveats (v0 relative to current fuel load, landing fuel confounded with gravity/distance, no second hull to cross-check) are in `puga/shipping.py`'s module docstring - don't trust magnitudes beyond what's there. Raw calibration data (APEX DOM reads, 2026-10-09): `empire/data/shipping_calibration/`. Also wired into `tools/network.py`'s freight cost (direct-jump transfers use the real model; gateway transfers need an explicit `trip_cost` in the chain YAML, else a 9250 AIC fallback). Library: `puga/shipping.py` (`trip_fuel()`, `round_trip_cost()`).
|
||||
- `tools/parkcash.py [--min-spread X] [--min-trade-days N] [--rate R] [--top N]` where to park idle cash as a buy-low/sell-high position (not a build) while ships are busy or cash has no better use right now - scans every ticker for a big bid/ask spread AND real trading liquidity (trade-days/gap over a calendar window - a huge spread with few trading days is a stale-quote trap, confirmed by hand: AST showed a 130% spread but its resting ask had gone stale after a 60% real price crash). Round-trip wait/value is EMPIRICAL (`puga.history.empirical_touch`, same model as `tools/sell.py --tiers`), not an assumed random walk - a driftless-walk version was tried and backtested wrong (overstated reachability 2-4x vs 3 years of real data, see `docs/decisions.md`). This dropped the whole universe's top pick from ~94%/day to ~1%/day with real waits of 19-194+ days - treat any number from the old model as stale. `--rate` defaults to 0.0 (matches the idle-cash premise; pass your realized growth rate if this cash IS earmarked) and shows up as a separate `discounted_pct` column (margin% x real odds both legs ever happen) alongside the simple non-compounding `daily_pct` used for ranking. Library: `puga/parkcash.py`.
|
||||
- `tools/contd.py [--cx AI1]` evaluates this account's OPEN CONTD contract offers (the NPC logistics-officer
|
||||
pool in APEX's CONTD panel, usually 3 at a time, only one acceptable) - payment, each required
|
||||
material priced at real buy-fresh cost, and net. Deliberately leaves conditions it can't price
|
||||
(EXPLORATION, REPAIR_SHIP, HEADQUARTERS_UPGRADE, BASE_CONSTRUCTION, CONTRIBUTION, WAIT,
|
||||
INCREASE_SATISFACTION - real cost depends on context the API can't see, e.g. a ship already flying
|
||||
that route) as flagged, unpriced conditions, and doesn't account for materials you may already hold
|
||||
in storage - it's a breakdown for the caller to judge, not a verdict. Library: `puga/contd.py`.
|
||||
- `tools/lmscan.py PLANET [--direction source|destination] [--min-margin X]` live Local Market hauling-ad scan (FIO, public/no-auth - real player-posted freight jobs, not the CONTD player-contract system), ranked by margin after real fuel cost (`puga.shipping.leg_cost`). One-way cost only - margin assumes the next job is picked up near the destination, not an empty flight home. A small measured gateway-fee table covers ANT<->HRT/BEN; other gateway routes can't be priced (LOCK fee isn't available via any API). Library: `puga/contracts.py`.
|
||||
- `tools/buildcost.py BUILDING [--planet ID] [--amount N] [--cx AI1]` full construction material
|
||||
list for one building, priced at real fill cost; `--planet` adds that planet's environment-extra
|
||||
materials (SEA/HSE/MGC/BL/INS/TSH - threshold table in `docs/mechanics.md`). Also wired into
|
||||
`whatif.py`/`buy.py`/`scan.py`'s own capex numbers via `simulate(planet=...)` / `scan.py`'s
|
||||
`bcost()`. Library: `puga/planet.py::environment_extras()`.
|
||||
- `tools/actpkg.py NAME TICKER:QTY [TICKER:QTY ...] [--cx AI1] [-o file.json]` emits a Refined PrUn
|
||||
(browser extension, github.com/refined-prun/refined-prun) `XIT ACT` action-package JSON for a buy
|
||||
list - paste into the extension's Import Action Package to pre-fill the in-game CXPO buy tile per
|
||||
material (player still clicks the real buy button - semi-auto, not full auto). NAME must be
|
||||
letters/digits/spaces only; punctuation is stripped automatically. Library: `puga/actpkg.py`.
|
||||
- `tools/price.py` prices across exchanges with VWAP, volume, fill price for a quantity; `tools/book.py` order-book ladder.
|
||||
- `tools/prun_scan.py`, `tools/prun_cxarb.py` legacy top-of-book scans; overstate thin markets. Baseline only. `tools/arb.py` replacement is on the roadmap.
|
||||
- `puga/econ.py` pure formulas ported from PRUNplanner (efficiency stack, workforce, extraction, production I/O, hab optimizer); `tests/test_econ.py` holds the reference values.
|
||||
|
||||
@@ -6,122 +6,40 @@
|
||||
<br><br>
|
||||
</h1>
|
||||
|
||||
A set of tools and know-how for Claude (Claude Code) to assist in the game [Prosperous Universe](https://prosperousuniverse.com), usable by humans too. You ask questions in plain language; Claude answers by running the tools in this repo against live market data and your own company data, instead of guessing.
|
||||
A recursively self-improving harness for Claude and humans for the game [Prosperous Universe](https://prosperousuniverse.com). You ask questions in plain language; Claude answers by running the tools in this repo against live market data and your own company data, instead of guessing - and when it catches itself doing the same ad-hoc work by hand more than once, it builds a tool for it instead, so the harness keeps getting sharper the more it's used.
|
||||
|
||||
```
|
||||
what should I build next?
|
||||
is a second smelter still worth it, or is the AL market full?
|
||||
simulate adding a CHP to Deimos before I spend anything
|
||||
how long until Nike runs out of RAT?
|
||||
where do I post 40 BHP so it actually clears today?
|
||||
```
|
||||
|
||||
Name origin:
|
||||
Plutonium–gallium alloy (Pu–Ga) is a specialized metallic blend of plutonium and gallium primarily used to stabilize the desirable delta (δ) phase of plutonium at room temperature.
|
||||
|
||||
## How it is meant to be used
|
||||
## What it can do
|
||||
|
||||
Open Claude Code in this folder. `CLAUDE.md` is loaded automatically: it tells Claude which tools exist, which numbers to trust, and how to answer. Claude also reads `empire/PROFILE.md` (who you are, how you want answers) if you have one. Then just ask, e.g. *"what should I build on Sunday?"*, *"is BHP still worth it?"*, *"how long until I can afford it?"*. Claude answers by running the tools against live market data and your own company data, instead of guessing. Every tool is also a normal command (`puga <tool>`), so you can run them yourself. Claude can also read and write your plans in PRUNplanner (`puga plan`), so you can check and tweak them in the web UI and Claude picks up your saved changes.
|
||||
- **Find what to build.** Every recipe, but with market depth: how many buildings the market absorbs, what you'd really get for the output, and whether the margin has held for months or is a spike.
|
||||
- **Simulate before you spend.** A replica of the PRUNplanner simulator, verified against the real thing. Marginal payback of one more building, and a warning if it overloads your housing.
|
||||
- **Watch your position.** Cash, permits, buildings, storage and ships synced from FIO. Runway per material, cash-aware shopping lists, multi-base chains with real freight.
|
||||
- **Trade.** Where to post an ask, how to split it, how long it takes to clear, where idle cash can sit meanwhile.
|
||||
- **Talk to PRUNplanner.** Reads your plans, writes new ones, picks up edits you make in the web UI. Only touches plans it created.
|
||||
|
||||
Everything the tools print is an **estimate** from public and personal game data. Prices move; re-run before acting.
|
||||
Every number is an estimate from public and personal game data. Prices move; re-run before acting.
|
||||
|
||||
## Features
|
||||
|
||||
**Data layer**
|
||||
- Cached clients for the FIO REST API and the PRUNplanner API (public game data, order books, price history, your own sites, storage, production, ships, cash).
|
||||
|
||||
**Market tools**
|
||||
- `price`: bid, ask, 7/30-day VWAP, daily volume, supply and demand at every exchange; fill price for a quantity.
|
||||
- `book`: order-book ladder with cumulative depth (market-maker orders handled).
|
||||
|
||||
**Economics engine** (`puga/econ.py`, ported from the PRUNplanner source, which is treated as the source of truth and checked against its own tests and live FIO values)
|
||||
- Building efficiency: COGC, HQ, experts, faction bonus, fertility, building condition.
|
||||
- Workforce satisfaction and consumption, extraction rates, production per day, housing optimizer.
|
||||
|
||||
**Finding opportunities**
|
||||
- `scan`: ranks every recipe with a depth-aware market model, so it does not recommend recipes whose whole market fits one or two buildings. Fully staffed and understaffed variants, freight cost, HQ/COGC/experts, `--min-n` filter for real markets, a `--planet` mode (extraction, fertility, COGC of a specific planet) and a demolish-later cost.
|
||||
- `persistence` and `history`: how long has a margin lasted? Re-prices any opportunity over the exchange history (30/90/180 days), with payback and expected net gain over 7 and 14 days.
|
||||
- `chain`: make-versus-buy cost tree with sourcing depth of every input.
|
||||
- `arb` (planned) and the legacy `prun_scan` / `prun_cxarb` (kept as a baseline, they overstate thin markets).
|
||||
|
||||
**Your own position**
|
||||
- `state`: syncs `empire/state/company.yaml` from FIO: cash, permits, buildings, real production efficiency, storage and ships.
|
||||
- `simulate`: a Python replica of the PRUNplanner simulator (workforce, efficiency, material I/O, profit), verified against screenshots of it. Reads a local plan or a saved plan from your account, and reports the real new capex (planned minus already built).
|
||||
- `plan` (plan_push): reads plans from your PRUNplanner account into small YAML files and writes them back (create, update, delete), so you and Claude can edit the same plan, you in the UI and Claude in code. Dry run by default; only plans named `[PuGa] ...` can be written or deleted.
|
||||
|
||||
**Knowledge for Claude** (`CLAUDE.md`, `docs/`)
|
||||
- Verified game mechanics, the market-saturation design, a decision log and a roadmap (`docs/`). Everything specific to your own empire (profile, state, plans, notes) lives in the gitignored `empire/` folder, so this repo can stay public.
|
||||
|
||||
## Setup
|
||||
|
||||
Requires Python 3.12 or newer and git.
|
||||
## Quick start
|
||||
|
||||
```sh
|
||||
git clone <repo-url> PuGa
|
||||
cd PuGa
|
||||
|
||||
# 1. virtual environment; installs the `puga` command into it
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -e ".[dev]"
|
||||
source .venv/bin/activate # once per shell, so `puga` is on your PATH
|
||||
|
||||
# 2. keys
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
$EDITOR .env # fill in the values below
|
||||
|
||||
# 3. optional: the PRUNplanner source used as reference for game mechanics (gitignored)
|
||||
tools/refresh_refs.sh
|
||||
|
||||
# 4. check it works
|
||||
puga test
|
||||
puga price BHP --cx AI1
|
||||
git clone <repo-url> PuGa && cd PuGa
|
||||
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
||||
cp .env.example .env # FIO and PRUNplanner keys, see docs/usage.md
|
||||
claude # open Claude Code here and ask
|
||||
```
|
||||
|
||||
### `.env`
|
||||
Every tool is also a command: `puga scan`, `puga simulate plan.yaml`, `puga sell BHP 40`. Tool list, setup and layout: [`docs/usage.md`](docs/usage.md). Verified game mechanics and the market model: [`docs/`](docs/).
|
||||
|
||||
`.env` is gitignored and never committed. Do not paste keys into chat; edit the file.
|
||||
|
||||
| Variable | What it is |
|
||||
|---|---|
|
||||
| `FIO_USERNAME` | your in-game / FIO user name |
|
||||
| `FIO_REST_KEY` | your FIO REST key (used for your own sites, storage, production, ships, cash on `rest.fnar.net`) |
|
||||
| `FIO_API_KEY` | your FIO API (web) key; separate from the REST key, currently unused |
|
||||
| `PRUNPLANNER_API_KEY` | API key from your PRUNplanner account, sent as `Authorization: Api-Key <key>` |
|
||||
| `COMPANY_CODE` | your company code (used by `tools/state.py` for the first sync) |
|
||||
| `DEFAULT_CX`, `DEFAULT_REGION` | default exchange (`AI1` = Antares) and region |
|
||||
|
||||
Only the public data works without keys (prices, recipes, planets). Your own data needs the FIO extension for the browser client to have uploaded it recently: run `puga state sync` and check the `as_of` time.
|
||||
|
||||
## Usage
|
||||
|
||||
`puga help` lists the tools; `puga <tool> --help` shows the options.
|
||||
|
||||
```sh
|
||||
puga state sync # refresh your company state from FIO
|
||||
puga price BHP --cx AI1 # prices, VWAP, volume, fill price for a quantity
|
||||
puga scan --cogc METALLURGY --experts METALLURGY=2 --min-n 3 --top 20
|
||||
puga scan --planet ZV-307d --min-n 3 # a specific planet
|
||||
puga scan --min-n 3 --json rows.json && puga persistence rows.json
|
||||
puga chain KV --qty 13 # make-vs-buy and input sourcing
|
||||
puga simulate plans/examples/hwp_buildout.yaml --basis vwap30
|
||||
|
||||
puga plan list # plans in your PRUNplanner account
|
||||
puga plan pull <uuid> -o my_plan.yaml # read a plan (including your UI edits) into a YAML file
|
||||
puga plan my_plan.yaml # dry run: validated summary of what would be written
|
||||
puga plan my_plan.yaml --apply # write it to your account as a [PuGa] plan
|
||||
puga simulate --uuid <uuid> # simulate the plan as saved in your account
|
||||
```
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
CLAUDE.md entry point for Claude: rules, tool index, source-of-truth order
|
||||
docs/ game and toolkit knowledge: mechanics, market model, decisions, roadmap
|
||||
puga/ library: data clients, market, economics, saturation, simulator
|
||||
tools/ command line tools
|
||||
plans/examples/ generic plan specs (also test fixtures)
|
||||
state/ company.example.yaml, the shape of your synced state
|
||||
tests/ pytest suite
|
||||
empire/ (gitignored) YOUR empire: PROFILE.md, state/company.yaml, plans/, docs/ (notes, build plans)
|
||||
data/ (gitignored) fetched data cache
|
||||
ref/ (gitignored) PRUNplanner source, read-only reference
|
||||
```
|
||||
|
||||
### The `empire/` folder
|
||||
|
||||
Game knowledge and generic methods go in `docs/`; anything about your own bases, cash, decisions or preferences goes in `empire/`, which is gitignored. `tools/state.py sync` creates `empire/state/company.yaml` (on first use set `COMPANY_CODE` in `.env`). Add `empire/PROFILE.md` yourself: your name, company, how you want answers, agreements with Claude.
|
||||
Your own empire (profile, state, plans, notes) lives in the gitignored `empire/` folder, so the repo stays public.
|
||||
|
||||
Not affiliated with Prosperous Universe, FIO or PRUNplanner.
|
||||
|
||||
@@ -16,3 +16,146 @@
|
||||
4. Big-money recommendations (e.g. BHP go/no-go, roughly 100k AIC): independent second opinion on the numbers.
|
||||
- If a bigger-model spawn is refused, tell the player and ask them to run the review.
|
||||
- Routine tool building is not reviewed by a bigger model.
|
||||
|
||||
## 2026-10-10 Optimal ask price: first-passage-time (Black-Scholes), not order-book depth
|
||||
**SUPERSEDED same day - see "Black-Scholes model backtested wrong" below. The closed form here
|
||||
(`daily_log_vol()`, a driftless-random-walk assumption) is no longer what `tools/sell.py --tiers`
|
||||
uses; kept for the reasoning trail, not as current guidance.**
|
||||
- The naive model ("units ahead of me in the book ÷ historical daily volume = days to clear")
|
||||
is WRONG: it assumes the book is static (no one else reprices, cancels, or adds orders while
|
||||
you wait) and that historical trade volume at normal prices still applies at a resting ask far
|
||||
outside the recently-traded range. Tried first, broke immediately: fed a fat-finger 1,000,000
|
||||
AIC ask the same reachability as the real book, "confirming" it as optimal.
|
||||
- Correct model: whether the market ever pays price P is governed by price DIFFUSION, not queue
|
||||
depth. Model ln(price) as a driftless random walk with the ticker's own measured daily
|
||||
log-return volatility sigma (deliberately no drift - same "don't model trend" rule as
|
||||
`puga/parkcash.py`), and ask for the discounted value of the first time it diffuses up to P.
|
||||
Closed form (standard Brownian-motion hitting-time Laplace transform):
|
||||
y = ln(P/s0), rho = ln(1 + rate), D(P) = P * exp(-(y/sigma) * sqrt(2*rho)) for P > s0
|
||||
D(P) = P for P <= s0
|
||||
`rate` is the player's own REALIZED capital growth rate (opportunity cost of the delay - see
|
||||
below), not a theoretical marginal-build ROI.
|
||||
- ln(D) is LINEAR in y, so there is no interior optimum: D is strictly decreasing past the
|
||||
current price (sell near top of book / at the last traded price wins) whenever
|
||||
`sigma < sqrt(2*rho)`, and rises without bound (a degenerate corner case, not real free money)
|
||||
otherwise. Checked against this account's real tickers (AL 2.5%/day, BHP 8.1%/day, DEC
|
||||
10.8%/day vol, all against a 5%/day rate -> threshold ~31%/day): every one is comfortably in
|
||||
the "sell now dominates" regime. Treat a result where climbing pays as a signal to double
|
||||
check sigma/rate inputs, not as license to post a speculative high ask.
|
||||
- Implementation: `puga.history.daily_log_vol()` (pooled variance estimator, scales each
|
||||
consecutive trading-day gap's squared log-return by its elapsed days so sparse tickers don't
|
||||
understate how far price can move between trades) + `tools/sell.py --tiers --rate R`.
|
||||
- This also resolved the earlier "what discount rate" question: use the player's REALIZED equity
|
||||
growth rate (read off their own in-game equity-growth chart, ~5%/day as of 2026-10-10), not the
|
||||
scan/build tools' marginal per-building ROI figures (14-29%/day) - those are a ceiling on one
|
||||
marginal building at current scale (capped by permits, workforce-arrival delay, and market-
|
||||
depth saturation the moment you scale), not what a freed-up dollar actually compounds at. The
|
||||
realized rate already nets out all of that friction, which is exactly what a discount rate for
|
||||
"should I wait for a better price" needs to reflect.
|
||||
|
||||
## 2026-10-10 Black-Scholes closed form backtested wrong - empirical model instead
|
||||
- Tested the driftless-random-walk assumption above against this account's real exchange history
|
||||
(BHP: 802 trading days, sigma 7.39%/day; AL: 995 days, sigma 4.42%/day). Model predicts
|
||||
P(touch level k*sigma*sqrt(T)) = 2*(1-Phi(k)), independent of T - the scale-invariance signature
|
||||
of a true random walk. Measured the real empirical touch frequency for the same (k, T) pairs:
|
||||
|
||||
| k | model pred | BHP empirical (T=7/14/30/60d) | AL empirical (T=7/14/30/60d) |
|
||||
|-----|-----------:|----------------------------------|-----------------------------------|
|
||||
| 0.5 | 61.7% | 16.6% / 18.0% / 17.5% / 20.1% | 32.6% / 33.9% / 32.4% / 40.1% |
|
||||
| 1.0 | 31.7% | 8.8% / 8.0% / 8.2% / 7.9% | 9.2% / 10.2% / 10.8% / 16.7% |
|
||||
| 1.5 | 13.4% | 4.1% / 3.8% / 0.1% / 0.0% | 3.9% / 3.9% / 4.4% / 2.7% |
|
||||
| 2.0 | 4.6% | 2.0% / 1.2% / 0.0% / 0.0% | 1.9% / 1.5% / 2.0% / 0.0% |
|
||||
| 3.0 | 0.3% | 0.5% / 0.0% / 0.0% / 0.0% | 0.7% / 0.5% / 0.0% / 0.0% |
|
||||
|
||||
Model overstates touch probability by roughly 2-4x at low-moderate k, consistently across both
|
||||
tickers. Scale-invariance partially holds at low k (flat across T, locally random-walk-like
|
||||
short-term) but breaks down at higher k/longer T (empirical rate COLLAPSES faster than the model
|
||||
past k=1.5, instead of staying flat) - the signature of mean reversion: real prices are anchored
|
||||
to production cost/supply-demand equilibrium, not free-floating, so they wander less far over
|
||||
longer horizons than a pure random walk would.
|
||||
- The 2-4x figure overstates how much of this is mean reversion specifically: touches were
|
||||
measured on daily VWAPs, a discrete sample of a continuous path, and the model's prediction
|
||||
assumes continuous monitoring. Discrete sampling can only miss touches (an intraday spike that
|
||||
reverts before the next VWAP looks like "no touch"), biasing the measured gap upward especially
|
||||
at short horizons (k=0.5, T=7 - standard discrete-barrier corrections put this at roughly
|
||||
0.58*sigma*sqrt(step) per sampling interval, shrinking as the horizon grows). The k>=1.5/T>=30
|
||||
COLLAPSE is not explained by discretization (a roughly constant/shrinking effect, not a
|
||||
progressive one) - that part is real mean reversion.
|
||||
- Consequence: the model's absolute numbers are upper bounds, not honest estimates - directionally
|
||||
conservative (it already said "don't climb the book," and the true probability of ever
|
||||
profitably climbing is even lower than it claimed) but not quantitatively trustworthy.
|
||||
- Replaced with `puga.history.empirical_touch()`: a non-parametric estimator measuring first-
|
||||
passage directly from the ticker's own full multi-year history (every historical start day,
|
||||
first time the price actually moved by the target amount, right-censored samples contribute 0
|
||||
rather than being excluded) - no assumed distribution, so whatever mean-reversion/fat-tails/etc.
|
||||
the real data has shows up directly. Inherits the same daily-VWAP discretization conservatism as
|
||||
the backtest above (a resting ask can fill on an intraday high the VWAP series never shows) - so
|
||||
it also leans a little more toward "sell now" than fully warranted, not corrected for. Used by
|
||||
`tools/sell.py --tiers` (combined with queue-depth as a deterministic shift of the hitting time,
|
||||
not a max - ranking by the resulting hit_factor, not a point estimate of median days) and
|
||||
`puga/parkcash.py` (two sequential legs: buy-dip,
|
||||
sell-recovery).
|
||||
- Refined further: the unconditional version above still averages over EVERY historical start day,
|
||||
which answers "how often does this ticker move by y from an arbitrary day" - but mean reversion
|
||||
specifically means the answer depends on where price is NOW relative to its own recent trend.
|
||||
Conditioned on state instead (`empirical_touch(..., condition_on_state=True)`, the default):
|
||||
only start days whose z-score against a trailing 60-day mean is within +/-0.5 of TODAY's are
|
||||
used, falls back to every start day if there's not enough history to compute today's z-score or
|
||||
the match band is empty. Stays non-parametric (no fitted mean-reversion speed/strength). Real
|
||||
effect confirmed on DEC (`tools/parkcash.py`): round-trip wait dropped from 19 days
|
||||
(unconditional) to 3 days once conditioned on DEC's actual current state - a big, real
|
||||
difference, not a rounding adjustment.
|
||||
|
||||
## 2026-10-10 Price-impact cap: real book depth, not a flat 25%-of-flow guess
|
||||
- `puga/saturation.py`'s `S_SHARE=0.25` capped planned output at a flat 25% of a ticker's traded
|
||||
flow, regardless of how deep or thin that specific market's standing bid book actually is -
|
||||
never estimated how much price actually falls as supply rises, flagged by review.
|
||||
- Tried first: a day-over-day regression of d(log price) on d(log volume) per ticker, the
|
||||
textbook first-order elasticity estimate. Real data killed it: BHP -0.009, AL +0.004,
|
||||
DEC +0.038, KV +0.007 - near zero and inconsistently signed. Cause: daily volume spikes in this
|
||||
market are mostly DEMAND-driven (more buyers -> more volume AND flat/higher price), which
|
||||
swamps and often reverses the sign of the SUPPLY-side effect we actually want. Shipping this
|
||||
would have been worse than the flat guess (could tell you adding supply raises price).
|
||||
- Fix: `puga.saturation.max_units_at_impact()` walks the LIVE bid book (same mechanics as
|
||||
`puga.market.walk()`) and returns how many units you could sell before the realized price
|
||||
degrades more than `--max-impact`%% (default 10) below vwap7/bid - a real, ticker-specific
|
||||
measure, no regression, no confounding.
|
||||
- Caveat, caught immediately when first wired as a hard `min()` cap alongside the flow-based
|
||||
check: a live order book is a SINGLE SNAPSHOT - standing bids get added/withdrawn constantly,
|
||||
same class of problem already found and fixed twice this session (`sell.py`'s queue model,
|
||||
`parkcash.py`'s driftless walk), and we have no historical book-snapshot log to tell a
|
||||
structurally-thin book from an unlucky instant. Using it as a hard cap let one noisy snapshot
|
||||
silently zero out `n_lim` and hide a recipe entirely (happened to KV: flow-based n_lim 10.6 ->
|
||||
0.0 purely from the snapshot). The 30-day flow figure (`tref_precise`) is the more reliable
|
||||
signal precisely because it aggregates many real days, not one instant.
|
||||
- Final design: `n_lim`/filtering stays flow-only (unchanged, reliable). `max_units_at_impact()`
|
||||
surfaces as an `[exit-thin]` WARNING flag instead (can the live book absorb an instant dump of 1
|
||||
day of 1 building's output right now, if cash were needed immediately?) - a panic-exit liquidity
|
||||
check, NOT a production price-impact measure (that's `market`/`lim`, which price via patient
|
||||
asks, the real selling mechanism) - visible, not silently filtering. Caught real signal on
|
||||
several recipes (KV, SC, HER, TRN, NL, RG all flagged) without hiding any of them.
|
||||
|
||||
## 2026-10-10 Demolition value: flat reclaim fraction, not a time-decay curve
|
||||
- `tools/scan.py --deprec` assumed building value decays LINEARLY to 0 over ~60 days (a guess,
|
||||
never checked against real data). Checked it: pulled this account's live FIO reclaimables
|
||||
(`/rain/userplanetbuildingreclaimables/{user}`) for all 8 owned building types, normalized by
|
||||
built-count, and compared to real construction cost (FIO `BuildingCosts` at live ask prices).
|
||||
- Result: reclaim fraction is 50-86% (CHP 68.7, EXT 86.5, HB1 58.3, HB2 50.9, HWP 73.1, POL 78.0,
|
||||
SME 74.6; CM a low outlier at 7.4%, likely a core-module-specific rule) - but EVERY one of these
|
||||
buildings is at ~99.7-99.9% live condition (this account's base is young). If reclaim really
|
||||
decayed from ~100% toward 0 over 60 days, a near-perfect-condition building should reclaim close
|
||||
to 100%, not 50-86%. This contradicts the decay-curve premise and is more consistent with a
|
||||
roughly FLAT, material-dependent reclaim fraction that doesn't move much with condition in the
|
||||
normal operating range.
|
||||
- Can't fully settle the shape - no aged/low-condition building exists in this account to check
|
||||
the other end of the curve, so this is suggestive, not conclusive (single base, narrow condition
|
||||
range, small sample).
|
||||
- Fix: `scan.py --deprec` now amortizes `capex * (1 - --reclaim-frac)` (the UNRECLAIMED portion)
|
||||
over the holding period, not full capex. `--reclaim-frac` defaults to 0.65 (the mean of the 7
|
||||
non-CM observations) - still a rough placeholder, not a calibrated curve; re-check once an aged
|
||||
building exists to compare against.
|
||||
|
||||
## 2026-10-09 Drop "ROI/day %" terminology
|
||||
- `profit/day ÷ new_capex` (what tools were calling "ROI/day X%") is just 1/payback_days rewritten as a percentage. It is NOT a compoundable rate of return - there's no reinvestment mechanism, and every opportunity here is capacity/market-limited (saturation), so it can't be extrapolated or annualized like an interest rate.
|
||||
- Report **payback in days** as the primary number everywhere. A "%/day" figure, if shown at all, must be labelled as simple/non-compounding and never compared to a real yield/interest rate.
|
||||
- Applies to `tools/whatif.py`, `tools/simulate.py`, `tools/scan.py`, `tools/persistence.py`, `tools/history.py`, and anything built after this that reports a return on a one-time building cost.
|
||||
|
||||
+59
-3
@@ -39,12 +39,68 @@ EOF
|
||||
per-tier need table), `HAB_CAP`/`HAB_AREA`, `TIERS`. This is what you use for "what if I
|
||||
understaff this building" or "what's the real wage bill for N heads" — the CLI tools only
|
||||
expose fixed slices of this.
|
||||
- **`puga.saturation`** — `tref`, `n_out`, `p_patient`, `effective_supply`, `is_thin`: the
|
||||
depth/persistence primitives behind `scan.py`. Reuse these instead of re-deriving a "how many
|
||||
buildings can the market take" estimate by hand.
|
||||
- **`puga.saturation`** — `tref` (cheap, Poisson-bounded, for stage-1 screening), `tref_precise`
|
||||
(real daily-volume variance, for a bounded candidate set), `n_out` (flow x queue, NO demand
|
||||
term - thin resting-bid books don't disqualify a market sold into via patient asks), `p_patient`,
|
||||
`effective_supply`, `is_thin` (demand still checked here, independently), `max_units_at_impact`
|
||||
(real live bid-book depth cap - how many units before realized price degrades past a threshold;
|
||||
replaced a flat 25%-of-flow guess after a naive price-vs-volume elasticity regression on real
|
||||
data came back near-zero/wrong-signed, see `docs/decisions.md`): the depth/persistence
|
||||
primitives behind `scan.py`. Reuse these instead of re-deriving a "how many buildings can the
|
||||
market take" estimate by hand.
|
||||
- **`puga.simulate`** — `simulate(plan, recipes, buildings, resources, fertility, price, ...)`:
|
||||
the PRUNplanner-simulator replica. Reuse this for anything plan-shaped rather than reimplementing
|
||||
efficiency/workforce/flows again.
|
||||
- **`puga.route`** — `load_graph()`, `resolve_system(query)` (planet/system natural id or name
|
||||
-> SystemId), `shortest_path(src, dst, graph=None)` (Dijkstra by straight-line ly over FIO's
|
||||
`/systemstars` jump graph; returns jumps, distance_ly, path). Not a PRUNplanner feature, built
|
||||
for this project since travel isn't modelled anywhere else. CLI: `tools/route.py`.
|
||||
- **`puga.shipping`** — `cruise_leg_fuel(v0)`, `jump_fuel(v1)`, `charge_fuel(v1)`,
|
||||
`gateway_hop_cost(lock_fee_amount, lock_fee_currency)`, `landing_fuel(planet_natural_id)` (lookup
|
||||
only, `None` if unmeasured), `trip_fuel(...)` (one-way total, shared by the CLIs),
|
||||
`leg_cost(src, dst, sf_price, ff_price, v0=1.0, v1=1.0)` (one-way AIC cost; uses
|
||||
`KNOWN_GATEWAY_ROUTES` when the pair has a measured gateway chain, else the direct-jump graph;
|
||||
`None` if neither applies), `round_trip_cost(...)` (there-and-back via two `leg_cost` calls,
|
||||
`None` if either leg is unpriceable or carries a non-AIC fee - used by `tools/network.py`'s
|
||||
freight cost): real ship flight fuel model, linear in the fuel-usage (v0) / reactor-usage (v1)
|
||||
sliders, additive/no cross-term. Scoped to this account's one hull/reactor (BP-STRT-0000, both
|
||||
ships confirmed identical); see the module
|
||||
docstring for confirmed-vs-open caveats before trusting a number. CLIs: `tools/shiptrip.py`
|
||||
(ship+from+to, auto-computes everything via `puga.route`), `tools/shipcost.py` (explicit
|
||||
jumps/sliders/gateway-fees, for when you already know the breakdown). Raw calibration data:
|
||||
`empire/data/shipping_calibration/`.
|
||||
- **`puga.parkcash`** — `scan(cx="AI1", min_spread_pct=20.0, days=30, rate=0.05)`: every ticker
|
||||
with a live quote and a big bid/ask spread, scored on real trading liquidity
|
||||
(`puga.history.trading_days()`/`trade_gaps_days()`) and an EMPIRICAL round-trip estimate
|
||||
(`puga.history.empirical_touch()`, two sequential legs: dip to bid, recover to ask) - no
|
||||
random-walk assumption. CLI: `tools/parkcash.py`. See the module docstring for open gaps (no fee
|
||||
data; the two legs are treated as independent, an approximation).
|
||||
- **`puga.history`** — `daily_prices(tk, cx)`, `trading_days(tk, cx, days)` (real calendar-window
|
||||
trading days, not "last N rows" - a sparse ticker needs this distinction), `trade_gaps_days(dates)`,
|
||||
`full_series(tk, cx)` (all available history, ascending), `empirical_touch(series, y, rate)`
|
||||
(non-parametric first-passage stats for a target log-move `y` - hit_factor/touched_frac/
|
||||
median_days, estimated directly from how often/fast the ticker's own real history has made
|
||||
moves of that size, by default only drawing on historical days in a similar state to today
|
||||
(trailing-60d z-score within +/-0.5, `condition_on_state=True`) since mean reversion's effect
|
||||
depends on where price is now, not just the move size. Optional `horizon` (days, off by
|
||||
default): bounds both eligibility and the search window to a fixed number of days so every
|
||||
start-day sample gets the same fair window, instead of recent start days being biased by
|
||||
running out of data to search. Replaced an earlier driftless-random-walk formula that
|
||||
backtested wrong, see `docs/decisions.md`). Shared by `tools/history.py`, `tools/sell.py`, `tools/undervalued.py`,
|
||||
`puga.parkcash`.
|
||||
- **`puga.contracts`** — `scan(planet, direction, sf_price, ff_price, v0=1.0, v1=1.0)`: live
|
||||
Local Market hauling ads (FIO `/localmarket/shipping/{source,destination}`), each enriched with
|
||||
real one-way fuel cost (`puga.shipping.leg_cost`) and margin. CLI: `tools/lmscan.py`.
|
||||
- **`puga.undervalued`** — `manufacturing_candidates()`, `current_margin(ticker, recipe, cx)`,
|
||||
`scan_current(cx, min_vol=5.0)`: manufactured goods priced below implied production cost, for
|
||||
a buy-and-hold-for-reversion trade, not a build decision. Backtested expected return is
|
||||
~0.10-0.24%/day - far below production's 14-29%/day, only worth excess idle capital. CLI:
|
||||
`tools/undervalued.py`. Shares `puga.history.daily_prices` with `tools/history.py`.
|
||||
- **`puga.planet`** — `candidates(resource_ticker, min_factor=0.0)`: every planet with that
|
||||
resource, sorted by extraction factor, each with temperature/pressure/gravity/fertility/faction
|
||||
and `build_requirements` (FIO's own founding-cost materials for that specific planet — real
|
||||
data, not guessed environment thresholds). CLI: `tools/planet.py`, pass `--from` an existing
|
||||
base or pure-factor ranking is misleading (best-factor planets are often thousands of ly away).
|
||||
- **`puga.config`** — `get(key)` reads `.env`; `state_path()` returns the real
|
||||
`empire/state/company.yaml` if synced, else the tracked example.
|
||||
|
||||
|
||||
@@ -59,6 +59,52 @@ Sources: Prosperous Universe dev log #239 "Enlisting Labor" (https://prosperousu
|
||||
- Report cadence seen on one planet: weekly, Wednesdays ~08:00 UTC (report #289 on 16 Sep 2026).
|
||||
- The old handoff detail "bases keep 75% of workforce between reports" is not in these sources; treat as unverified.
|
||||
|
||||
## Gateway (GTW) jump transit time (measured 2026-10-09)
|
||||
Sources: our own live APEX Ship Flight Control DOM reads (`empire/data/shipping_calibration/{hrt,ben}.json`) and the official handbook (handbook.apex.prosperousuniverse.com/wiki/infrastructure-gateway). The PrUn forum thread "Gateway Question Roundup" (Oct 2024) quotes a dev (molp) saying the team was "considering a fixed transit time, independent of the link length" during pre-launch design.
|
||||
- Our measured GTW segment durations contradict that design intent, if it shipped as described: 17 parsecs -> 5h41m and 5h43m; 15 parsecs -> 5h1m and 5h3m; 10 parsecs -> 3h18m. All five data points land within 19.8-20.2 minutes per parsec - a tight linear fit, not a fixed duration.
|
||||
- Treat GTW transit time as scaling ~linearly with the link's parsec distance (~20 min/parsec) until a wider sample says otherwise (n=3 distinct distances, 2 routes, not independently varied against other factors). The forum statement is 2024 pre-launch discussion, not a current source - our own measurement wins per this project's source-of-truth order.
|
||||
- No fuel or time model for GTW duration exists yet in `puga/shipping.py` (fuel-only); this is a documented fact for whoever builds that next, not wired into any tool.
|
||||
- Per the handbook: LOCK fees have no public formula (gateway-operator-set, displayed in SFC); some gateway links are one-way; each gateway has its own max per-jump cargo volume (m3), separate from ship hold size - none of these are modelled anywhere in this project yet.
|
||||
|
||||
## Placing CX orders at a remote exchange with no base/warehouse there (confirmed 2026-10-10)
|
||||
Player confirms: placing a BUY order at a remote exchange (tested: NC2, Hubur Station) works with
|
||||
no local base, storage, or warehouse rental there beforehand - the "Storage Location: Warehouse"
|
||||
option in the Place Order panel is usable by default, not something you need to build/rent first.
|
||||
Still UNCONFIRMED: whether holding the resulting inventory there afterward incurs any ongoing
|
||||
storage fee - this only confirms placing the order doesn't require a prerequisite warehouse, not
|
||||
that storage itself is free. Also still unconfirmed: FX conversion fee size (a forum thread titled
|
||||
"remove FX transaction fee entirely" implies one exists, but no amount confirmed).
|
||||
|
||||
## Planet environment-extra materials (per community handbook, confirmed live against Nike)
|
||||
FIO's `/planet/full/{id}` -> `BuildRequirements` lists a superset across hazard types and is NOT
|
||||
a direct per-building material list - compute it instead from the planet's own Pressure/Gravity/
|
||||
Temperature/Surface fields against these threshold rules (source: Prosperous Universe Handbook,
|
||||
building-costs page):
|
||||
|
||||
| condition | extra material | quantity |
|
||||
|---|---|---|
|
||||
| rocky | MCG | area x 4 |
|
||||
| gaseous | AEF | area / 3 |
|
||||
| pressure < 0.25 atm | SEA | area x 1 |
|
||||
| pressure > 2.0 atm | HSE | 1/building |
|
||||
| gravity < 0.25g | MGC | 1/building |
|
||||
| gravity > 2.5g | BL | 1/building |
|
||||
| temp < -25C | INS | area x 10 |
|
||||
| temp > 75C | TSH | 1/building |
|
||||
|
||||
Applies per building (construction AND repair), area-scaled rows use the building's own `AreaCost`.
|
||||
Implemented in `puga/planet.py::environment_extras()`, used by `tools/buildcost.py` and wired into
|
||||
`whatif.py`/`buy.py`/`scan.py`'s own capex numbers.
|
||||
|
||||
## CX order cancellation penalty (UNCONFIRMED numbers, forum-sourced)
|
||||
Deleting too many unfilled/partially-filled CX orders on the same ticker within a day triggers a
|
||||
fee (added per dev patch notes to deter bot-style requoting); a warning appears around the 4th
|
||||
attempt. No confirmed threshold or fee formula - forum reports range from 3 to 5-6 cancels/ticker/
|
||||
day, fee said to scale with order size. Effect: rate-limits requoting, so effective spreads widen
|
||||
and top-of-book gets sticky/stale - chasing the top spot is still possible within the free
|
||||
cancel budget (~3-5/ticker/day per forum reports), just be aware each reprice spends one of those
|
||||
before the fee kicks in.
|
||||
|
||||
## HQ in game vs PRUNplanner's "HQ" flag (observed 2026-09-21)
|
||||
- The HQ screen (level 1, base permits 1 / 2) shows "Efficiency gains: Electronics 20.0%", and 23.3% for the next level (permits 1 / 3). That is exactly the faction bonus formula (Antares electronics 5% x 2 x (3 - 2 x used/total)), so the HQ display is the faction bonus.
|
||||
- PRUNplanner's plan flag "HQ" (x1.1 on every building) is NOT visible in live efficiencies (smelters 1.3361, HWP 1.0696 both match the model without it). Keep it off. The HQ upgrade adds a base permit and raises the faction bonus.
|
||||
|
||||
+43
-25
@@ -1,31 +1,49 @@
|
||||
# Roadmap
|
||||
|
||||
Legend: [ ] todo, [x] done. Build order matters; each step is usable on its own.
|
||||
Open work only - what's already built/fixed is discoverable from `CLAUDE.md`'s Tools list,
|
||||
`docs/library.md`, `docs/decisions.md`, and module docstrings, not repeated here.
|
||||
|
||||
1. [x] Repo skeleton, git (master), venv, CLAUDE.md, mechanics from PRUNplanner.
|
||||
2. [x] `puga/fio.py`: cached FIO client (TTL per endpoint, keys from `.env`), plus `puga/prunplanner.py` for `api.prunplanner.org/data/*`. Inspect what `exchanges/` adds (VWAP?) vs FIO `/exchange/all`.
|
||||
3. [x] (price + book tools done; cxpc trend history not needed, PRUNplanner has vwap7/30) `puga/market.py` + `tools/price.py`, `tools/book.py`: prices across all CX, trends from cxpc, order-book walk for real fill price at quantity N.
|
||||
4. [x] `puga/econ.py` (22 tests pass, expected values from PRUNplanner's suite): efficiency stack, workforce consumption, hab LP, extraction (port the formulas from `docs/mechanics.md`, with tests against PRUNplanner values).
|
||||
5. [x] (v1 done; see saturation-design.md for refinements) `tools/scan.py` (replaces prun_scan.py): depth-aware ROI. Per recipe report: buildings the market can absorb (output demand + traded volume, input supply), ROI at fill price for N buildings, absorbable profit/day. Filter `--min-buildings`. Both CX-local and universe.
|
||||
5b. [ ] `tools/arb.py` (replaces prun_cxarb.py): inter-CX arbitrage on `market.walk` at real fill size; capital required, fuel/shipping cost from state, profit per trip within cash. Reason: old script uses top-of-book spread x min(supply,demand); on 2 of 4 top hits it overstated profit 7 to 11x (WAI, SCN).
|
||||
6. [x] `tools/chain.py`: full bill of materials, make-vs-buy per node.
|
||||
7. [ ] `tools/whatif.py`: marginal ROI of adding a building to the actual state (uses `state/company.yaml`, efficiency stack, imports).
|
||||
8. [ ] `tools/planet.py`, `tools/found.py`: rank planets for a resource; founding cost including environment extras.
|
||||
13b. [x] `puga/network.py` + `tools/network.py`: multi-base chain modelling (per-base simulate, net transfers against real freight, `cm_free` for kits). Worked example: `plans/chains/nike_deimos_lst.yaml` (Nike LST -> Deimos PP2/BSE). Known gap: reports whole-plan profit per base, not the marginal addition; caller must diff manually.
|
||||
9. [ ] `tools/route.py`, `tools/haul.py`: jump graph, fuel, profit per trip.
|
||||
9b. [x] (dry-run default, --apply after user yes) `tools/plan_push.py`: create/update `[PuGa]` plans in PRUNplanner from YAML (Api-Key auth; see decisions.md for guardrails).
|
||||
10. [x] `tools/state.py sync` (sites, production efficiency, storage, ships, cash, permits): inventory, production, ships into `state/`.
|
||||
11. [ ] Docs to fill: `docs/apex.md`, `docs/fio.md`, `docs/playbook.md` (question type -> tool), `docs/decisions.md`.
|
||||
## Todo
|
||||
- [ ] `tools/network.py`/`puga/network.py`'s `combine()` doesn't pass `planet` into `simulate()`
|
||||
yet (environment-extra construction materials, `puga/planet.py::environment_extras()`) -
|
||||
`whatif.py`/`buy.py`/`scan.py` already do.
|
||||
- [ ] `tools/arb.py`: inter-CX arbitrage at real fill size (replaces `prun_cxarb.py`, which
|
||||
overstated profit 7-11x on 2/4 top hits).
|
||||
- [ ] `tools/haul.py`: fuel cost / profit per trip (route.py has the jump graph).
|
||||
- [ ] `tools/portfolio.py`: profit-maximizing set of 1-building opportunities under shared
|
||||
housing/capex/permits. Ties into backlog #2 (profit/permit ranking, needs this tool to mean
|
||||
anything - permits bind at the whole-base level, not per-recipe).
|
||||
- [ ] Docs to fill: `docs/apex.md`, `docs/fio.md`, `docs/playbook.md`.
|
||||
|
||||
13. [x] `tools/buy.py`: cash-aware shopping list (construction gap vs empire state's built count, plus N days of net operating stock via simulate(), priced at real fill cost, checked against cash/reserve).
|
||||
14. [x] `tools/sell.py`: ask-post-price + expected-clear-time advisor from 30d traded-volume percentiles, vs hitting the bids now.
|
||||
|
||||
15. [x] `tools/runway.py`: days-of-runway per material from simulate()'s net consumption, base storage plus auto-detected inbound ship cargo (tools/state.py now tags each ship with its live flight origin/destination, and each STORE with its planet, needed once a 2nd base existed).
|
||||
|
||||
12. [ ] `tools/portfolio.py`: choose the set of 1-building opportunities for one base that maximises total profit given shared whole-building housing (HB1/HB2/...), capex, permits and (for demolish-later) 60-day value decay. Persistence check exists (`tools/persistence.py`); wire it into the ranking.
|
||||
## Backlog: review findings, still open (spot-checked against code)
|
||||
1. [ ] `scan.py` payback ignores working capital (input stock/output inventory/consumables) - can
|
||||
rival building capex for smelting-type recipes. `buy.py` already computes this number.
|
||||
2. [ ] No profit/permit ranking (permits bind at the base level, not per-recipe) - needs
|
||||
`tools/portfolio.py`'s cross-recipe/whole-base view.
|
||||
3. [ ] `scan.py` doesn't charge degradation (capex/180/day) like `simulate.py` does - small but real
|
||||
inconsistency between tools ranking the same thing.
|
||||
4. [ ] No input-side flow cap (buying a big share of an input's flow should price-impact like
|
||||
selling output does) - documented as absent, not modelled.
|
||||
5. [ ] `persistence.py --lag 3` default is too low given `docs/mechanics.md`'s weekly workforce
|
||||
distribution - real lag is 3-10 days.
|
||||
6. [ ] Possible forward-fill bias if any tool reindexes `daily_prices()` onto a full calendar grid
|
||||
(it only emits trade days) - would understate volatility for sparse tickers. Not yet confirmed
|
||||
whether `persistence.py`/`undervalued.py` actually do this.
|
||||
7. [ ] `undervalued.py`'s backtest (+21.3%/3mo) has no control group - meaningless without the
|
||||
universe's unconditional return over the same window.
|
||||
8. [ ] `persistence.py` measures past margin variance of a market we were NOT in - can't see the
|
||||
dominant real risk (our own entry + the next player's compressing margin).
|
||||
9. [ ] `undervalued.py::manufacturing_candidates()` keeps the first recipe seen per output, not
|
||||
the cheapest (`seen.setdefault`).
|
||||
10. [ ] `scan.py` hab cost ignores combined habs (HBB/HBC/HBM/HBL), which can be cheaper per head.
|
||||
11. [ ] `scan.py --trip-cost` still defaults to the flat 9250 placeholder despite the real
|
||||
`puga/shipping.py` model existing and already used by `whatif.py`.
|
||||
12. [ ] `sell.py`'s `s0` is the day's VWAP, not its high - `--tiers` touch probability is slightly
|
||||
pessimistic (same discretization conservatism as `empirical_touch()`, see `docs/decisions.md`).
|
||||
13. [ ] `empirical_touch()`'s optional `horizon` (fixed-window right-censoring) exists but isn't
|
||||
wired into any tool's default call yet.
|
||||
|
||||
## Open questions
|
||||
- PRUNplanner auth is known (`Authorization: Api-Key <key>`). FIO REST and FIO API are separate services with separate keys (separate services with separate keys; an earlier "one API" reading was wrong). Keys are in `.env`. Verified 2026-09-18: FIO_REST_KEY works on rest.fnar.net as `Authorization: <key>` (own /sites, /storage etc. readable); FIO_API_KEY gives 401 there, host unknown. PRUNplanner key works (plans 0, empires 1, cx prefs 1 on his account). Still unknown: the OpenAPI spec at https://doc.fnar.net/api.json has no securitySchemes. Probe with read-only calls.
|
||||
- (resolved) PRUNplanner `exchanges/` has vwap_daily/7d/30d and traded volume; merged into `puga/market.py`. Trend history via cxpc still todo.
|
||||
- Extraction: concentration to daily rate formula.
|
||||
- (resolved 2026-09-25) Real price-band filtering (`NarrowPriceBandLow/High`, `WidePriceBandLow/High`) implemented in `puga/saturation.py` (`in_band`, `effective_demand`, `effective_supply` band param) and wired into `tools/scan.py` stage 2. Was flagged as an unimplemented refinement in saturation-design.md since day one; the player noticed a stale out-of-band bid in a live screenshot and asked the right question.
|
||||
- FIO REST and FIO API are separate services/keys (`.env`). FIO_REST_KEY works on rest.fnar.net;
|
||||
FIO_API_KEY's host is unknown; PRUNplanner's Api-Key works. `doc.fnar.net/api.json` has no
|
||||
securitySchemes.
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
# Usage reference
|
||||
|
||||
Every tool runs as `puga <tool> [args]` (or `tools/<tool>.py`). `puga help` lists them, `puga <tool> --help` shows the options. `CLAUDE.md` has the authoritative one-paragraph description of each tool and its caveats; this page is the human-facing index.
|
||||
|
||||
## Tools
|
||||
|
||||
**Market**
|
||||
- `price TICKER` bid, ask, 7/30-day VWAP, volume, supply and demand at every exchange; fill price for a quantity.
|
||||
- `book TICKER` order-book ladder with cumulative depth.
|
||||
- `sell TICKER QTY [--tight] [--tiers]` where to post an ask, expected time to clear, a tranche split, and whether pricing above market is ever worth the wait.
|
||||
- `parkcash` where to park idle cash in a buy-low/sell-high position while it has no better use.
|
||||
- `undervalued` manufactured goods priced below their input cost (buy-and-hold candidates, low return).
|
||||
|
||||
**Finding what to build**
|
||||
- `scan` ranks every recipe with a depth-aware market model: buildings the market can absorb, payback at realistic fill prices, staffed and understaffed variants, freight, planet-specific extraction and COGC (`--planet`).
|
||||
- `persistence rows.json` re-prices scan rows over 30/90/180 days of history: is the margin a spike?
|
||||
- `history TICKER` monthly margin history of one recipe.
|
||||
- `chain TICKER` make-vs-buy cost tree; `--consumers` lists what eats the ticker downstream.
|
||||
- `planet RESOURCE --from PLANET` ranks planets for a resource by extraction factor, founding cost and jump distance.
|
||||
- `route A B` jump route between planets or systems.
|
||||
|
||||
**Your own position**
|
||||
- `state sync|show` refreshes `empire/state/company.yaml` from FIO: cash, permits, buildings, efficiency, storage, ships.
|
||||
- `simulate spec.yaml | --uuid U` replica of the PRUNplanner simulator; reports the real new capex (planned minus built).
|
||||
- `whatif base.yaml --add CHP:1` marginal payback of adding to a base you already run; flags newly overloaded workforce tiers and charges marginal freight.
|
||||
- `buy base.yaml --days N` shopping list: construction gap plus N days of net operating stock, checked against cash.
|
||||
- `runway base.yaml` days per material before the base stalls, including ships already inbound.
|
||||
- `network chain.yaml` multi-base chain: mine here, ship, process there, with real freight.
|
||||
- `plan list | pull UUID | spec.yaml [--apply] | delete UUID` read and write plans in your PRUNplanner account. Dry run by default; only `[PuGa]`-named plans are ever written.
|
||||
|
||||
**Ships**
|
||||
- `shiptrip SHIP FROM TO` fuel cost of a trip for one of your ships.
|
||||
- `shipcost --jumps N ...` the same from explicit physics parameters (gateway routes).
|
||||
- `lmscan PLANET` live Local Market hauling ads ranked by margin after fuel.
|
||||
|
||||
**Legacy**
|
||||
- `prun_scan`, `prun_cxarb` top-of-book scans kept as a baseline; they overstate thin markets.
|
||||
|
||||
## Examples
|
||||
|
||||
```sh
|
||||
puga state sync
|
||||
puga price BHP --cx AI1
|
||||
puga scan --cogc METALLURGY --experts METALLURGY=2 --min-n 3 --top 20
|
||||
puga scan --planet ZV-307d --min-n 3
|
||||
puga scan --min-n 3 --json rows.json && puga persistence rows.json
|
||||
puga chain KV --qty 13
|
||||
puga simulate plans/examples/hwp_buildout.yaml --basis vwap30
|
||||
puga whatif my_base.yaml --add CHP:1
|
||||
puga buy my_base.yaml --days 1.5
|
||||
puga runway my_base.yaml
|
||||
puga planet FEO --min-factor 0.5 --from ZV-759c
|
||||
|
||||
puga plan list
|
||||
puga plan pull <uuid> -o my_plan.yaml
|
||||
puga plan my_plan.yaml # dry run
|
||||
puga plan my_plan.yaml --apply
|
||||
puga simulate --uuid <uuid>
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
Requires Python 3.12 or newer and git.
|
||||
|
||||
```sh
|
||||
git clone <repo-url> PuGa && cd PuGa
|
||||
python3 -m venv .venv
|
||||
.venv/bin/pip install -e ".[dev]"
|
||||
source .venv/bin/activate # once per shell, so `puga` is on your PATH
|
||||
cp .env.example .env && chmod 600 .env && $EDITOR .env
|
||||
tools/refresh_refs.sh # optional: PRUNplanner source as mechanics reference (gitignored)
|
||||
puga test
|
||||
puga price BHP --cx AI1
|
||||
```
|
||||
|
||||
### `.env`
|
||||
|
||||
Gitignored, never committed. Do not paste keys into chat; edit the file.
|
||||
|
||||
| Variable | What it is |
|
||||
|---|---|
|
||||
| `FIO_USERNAME` | your in-game / FIO user name |
|
||||
| `FIO_REST_KEY` | FIO REST key (your sites, storage, production, ships, cash on `rest.fnar.net`) |
|
||||
| `FIO_API_KEY` | FIO API (web) key; separate from the REST key, currently unused |
|
||||
| `PRUNPLANNER_API_KEY` | API key from your PRUNplanner account, sent as `Authorization: Api-Key <key>` |
|
||||
| `COMPANY_CODE` | your company code, used by the first `state sync` |
|
||||
| `DEFAULT_CX`, `DEFAULT_REGION` | default exchange (`AI1` = Antares) and region |
|
||||
|
||||
Public data (prices, recipes, planets) works without keys. Your own data needs the FIO browser extension to have uploaded recently; run `puga state sync` and check `as_of`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
CLAUDE.md entry point for Claude: rules, tool index, source-of-truth order
|
||||
docs/ game and toolkit knowledge: mechanics, market model, decisions, roadmap, this file
|
||||
puga/ library: data clients, market, economics, saturation, simulator, shipping
|
||||
tools/ command line tools
|
||||
plans/examples/ generic plan specs (also test fixtures)
|
||||
state/ company.example.yaml, the shape of your synced state
|
||||
tests/ pytest suite
|
||||
empire/ (gitignored) YOUR empire: PROFILE.md, state/company.yaml, plans/, docs/
|
||||
data/ (gitignored) fetched data cache
|
||||
ref/ (gitignored) PRUNplanner source, read-only reference
|
||||
```
|
||||
|
||||
Game knowledge and generic methods go in `docs/`; anything about your own bases, cash, decisions or preferences goes in `empire/`. `puga state sync` creates `empire/state/company.yaml` (set `COMPANY_CODE` in `.env` first). Add `empire/PROFILE.md` yourself: who you are, how you want answers, agreements with Claude.
|
||||
@@ -1,8 +1,9 @@
|
||||
# Multi-base chain: Nike mines LST, ships it to Deimos, Deimos turns it (+ market AL) into BSE.
|
||||
# trip_cost/cargo are placeholders (see tools/network.py) until a real fuel model exists.
|
||||
# trip_cost omitted below: tools/network.py computes it from the real fuel model (puga.shipping)
|
||||
# since Nike<->Deimos is a direct-jump route. cargo is still a placeholder (ship hold size).
|
||||
name: "Nike LST -> Deimos PP2 (BSE)"
|
||||
bases:
|
||||
nike: {plan: plans/examples/nike_lst_ext.yaml, cm_free: true} # founded via the faction expansion contract's kit
|
||||
deimos: plans/examples/deimos_pp2_bse.yaml
|
||||
transfers:
|
||||
- {material: LST, src: nike, dst: deimos, trip_cost: 9250, cargo: 500}
|
||||
- {material: LST, src: nike, dst: deimos, cargo: 500}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Refined PrUn (github.com/refined-prun/refined-prun) XIT ACT action-package JSON - the semi-auto
|
||||
buy-list format: importing one pre-fills the in-game CXPO buy tile for each material, the player
|
||||
still clicks the real buy button themselves. Schema confirmed from the extension's own source
|
||||
(src/store/user-data.types.d.ts, src/features/XIT/ACT/actions/cx-buy/cx-buy.ts, 2026-10-17).
|
||||
|
||||
Gotcha (verified against the real extension, not just reading the source): `global.name` (and group/
|
||||
action names) get turned directly into an in-game command string by ActionPackageList.vue - spaces
|
||||
become underscores but other punctuation survives into the command literally, and APEX's command
|
||||
parser then rejects it with a generic "Illegal command" error on Edit/Execute (NOT on import, so it
|
||||
looks like the JSON is fine until you actually open it). sanitize_name() strips anything but
|
||||
letters/digits/spaces to avoid this.
|
||||
"""
|
||||
import re
|
||||
|
||||
|
||||
def sanitize_name(name: str) -> str:
|
||||
return re.sub(r"[^A-Za-z0-9 ]", "", name).strip()
|
||||
|
||||
|
||||
def build_package(name: str, materials: dict[str, float], exchange: str = "AI1") -> dict:
|
||||
"""materials: {ticker: qty}. Quantities are rounded up to whole units (CXPO buy amounts aren't
|
||||
fractional)."""
|
||||
name = sanitize_name(name)
|
||||
group = sanitize_name(name.lower()) or "group"
|
||||
import math
|
||||
mats = {tk.upper(): math.ceil(qty) for tk, qty in materials.items() if qty > 0}
|
||||
return {
|
||||
"global": {"name": name},
|
||||
"groups": [
|
||||
{"type": "Manual", "name": group, "materials": mats},
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"type": "CX Buy",
|
||||
"name": f"Buy {name}",
|
||||
"group": group,
|
||||
"exchange": exchange,
|
||||
"priceLimits": {},
|
||||
"buyPartial": False,
|
||||
"allowUnfilled": False,
|
||||
"useCXInv": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Player-to-player CONTD contracts (FIO /contract/allcontracts/{user}) - the NPC logistics-officer
|
||||
offers shown in APEX's CONTD panel, not the public Local Market hauling ads in puga/contracts.py.
|
||||
Only OPEN contracts are real choices - exactly one of the pool of (usually 3) offers can be accepted;
|
||||
CANCELLED/REJECTED/FULFILLED/PARTIALLY_FULFILLED are history or already-committed work.
|
||||
|
||||
Each condition's own `Party` field ("CUSTOMER" or "PROVIDER") says who performs it, checked
|
||||
against the contract's own top-level `Party` field (the player's role in that contract - usually
|
||||
"CUSTOMER"). Condition vocabulary, direction confirmed against real contract JSON (2026-10-17):
|
||||
PAYMENT/REPUTATION (always granted TO the player by the PROVIDER, regardless of which `Party` the
|
||||
condition lists), PROVISION_SHIPMENT (the player's `Party` supplies this material - a real COST,
|
||||
buy-fresh-priced), COMEX_PURCHASE_PICKUP (the partner already bought this via Comex - a REWARD
|
||||
handed to the player, sell-valued), PICKUP_SHIPMENT/DELIVERY_SHIPMENT (a logistics leg performed
|
||||
by whichever `Party` it lists - free to the player when that's the PROVIDER's leg, e.g. their
|
||||
transporter collecting what you provisioned; a real freight cost via `puga.shipping` when it's the
|
||||
player's own leg, not priced by this module, flagged with weight/volume/address instead), and
|
||||
open-ended ones this module deliberately does NOT price because their real cost depends on context
|
||||
this API can't see (a ship already flying that route, a planet you were about to survey anyway, a
|
||||
ship already damaged): EXPLORATION (Address = planet to survey), REPAIR_SHIP,
|
||||
HEADQUARTERS_UPGRADE, BASE_CONSTRUCTION, CONTRIBUTION, WAIT, INCREASE_SATISFACTION. Judging
|
||||
whether one of those is actually cheap right now is the caller's job.
|
||||
"""
|
||||
from . import fio, market
|
||||
|
||||
|
||||
def open_contracts():
|
||||
me = fio.me()
|
||||
data = fio.own(f"/contract/allcontracts/{me}", ttl=60)
|
||||
return [c for c in data if c["Status"] == "OPEN"]
|
||||
|
||||
|
||||
def evaluate(contract: dict, cx: str) -> dict:
|
||||
"""Payment, materials the contract hands TO the player (COMEX_PURCHASE_PICKUP, sell-valued),
|
||||
materials the player must supply (PROVISION_SHIPMENT on the player's own Party, buy-fresh
|
||||
cost), freight legs the player must personally fly (PICKUP/DELIVERY_SHIPMENT on the player's
|
||||
own Party - weight/volume flagged, not priced), and any other unpriced/contextual conditions -
|
||||
all for the caller to weigh. net = payment + reward_value - cost_value (freight excluded,
|
||||
flagged separately)."""
|
||||
my_party = contract.get("Party") # the player's role in THIS contract, e.g. "CUSTOMER"
|
||||
payment = 0.0
|
||||
reputation = False
|
||||
rewards, costs, freight_legs = [], [], []
|
||||
flags = []
|
||||
deadline_days = 0.0
|
||||
for cond in contract["Conditions"]:
|
||||
t = cond["Type"]
|
||||
mine = cond.get("Party") == my_party
|
||||
if t == "PAYMENT" and cond.get("Amount"):
|
||||
payment += cond["Amount"]
|
||||
elif t == "REPUTATION":
|
||||
reputation = True
|
||||
elif t == "COMEX_PURCHASE_PICKUP" and cond.get("MaterialTicker"):
|
||||
rewards.append((cond["MaterialTicker"], cond["MaterialAmount"], cond.get("Address")))
|
||||
elif t == "PROVISION_SHIPMENT" and cond.get("MaterialTicker") and mine:
|
||||
costs.append((cond["MaterialTicker"], cond["MaterialAmount"], cond.get("Address")))
|
||||
elif t in ("PICKUP_SHIPMENT", "DELIVERY_SHIPMENT") and mine:
|
||||
freight_legs.append((t, cond.get("Address"), cond.get("Weight"), cond.get("Volume")))
|
||||
elif t not in ("PAYMENT", "REPUTATION", "COMEX_PURCHASE_PICKUP", "PROVISION_SHIPMENT",
|
||||
"PICKUP_SHIPMENT", "DELIVERY_SHIPMENT"):
|
||||
flags.append((t, cond.get("Address")))
|
||||
dl = cond.get("DeadlineDurationMs")
|
||||
if dl:
|
||||
deadline_days = max(deadline_days, dl / 86400000)
|
||||
|
||||
def price_all(items, side):
|
||||
total, priced = 0.0, []
|
||||
for tick, qty, addr in items:
|
||||
r = market.walk(tick, cx, qty, side)
|
||||
priced.append({"ticker": tick, "qty": qty, "address": addr, "value": r["total"], "short": r["short"]})
|
||||
total += r["total"]
|
||||
return total, priced
|
||||
|
||||
reward_value, priced_rewards = price_all(rewards, "sell")
|
||||
cost_value, priced_costs = price_all(costs, "buy")
|
||||
|
||||
return {
|
||||
"id": contract["ContractLocalId"],
|
||||
"partner": contract.get("PartnerName"),
|
||||
"payment": payment,
|
||||
"reputation": reputation,
|
||||
"deadline_days": deadline_days,
|
||||
"rewards": priced_rewards,
|
||||
"reward_value": reward_value,
|
||||
"costs": priced_costs,
|
||||
"cost_value": cost_value,
|
||||
"freight_legs": freight_legs,
|
||||
"net": payment + reward_value - cost_value,
|
||||
"flags": flags,
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Local Market hauling-ad scan: live ads from FIO's /localmarket/shipping/{source,destination}
|
||||
(public, no auth - real player-posted freight-for-hire jobs, NOT the CONTD player-to-player
|
||||
custom contract system). Evaluates each against the real fuel model (puga.shipping).
|
||||
|
||||
SHIP_CARGO is this account's actual ship hold (both AVI-07JFB/AVI-07JFC: 500 t, 500 m3 - confirmed
|
||||
via FIO /storage/{user} SHIP_STORE). A contract whose cargo exceeds this needs multiple round
|
||||
trips to fulfil in one hull; that case is flagged, not computed.
|
||||
|
||||
One-way cost only: this does NOT add a return trip home, because the realistic loop is picking
|
||||
up the NEXT ad near the destination, not flying back empty. That makes the margin reported here
|
||||
optimistic for a one-off job with nothing lined up on the return leg.
|
||||
"""
|
||||
from . import fio, shipping
|
||||
|
||||
SHIP_CARGO = 500.0 # t and m3, both ships
|
||||
|
||||
|
||||
def scan(planet: str, direction: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||
"""direction: 'source' (ads picking up AT `planet`) or 'destination' (ads dropping off there).
|
||||
Returns a list of ads enriched with cost/margin, deduplicated by ContractNaturalId."""
|
||||
ads = fio.lm_shipping_source(planet) if direction == "source" else fio.lm_shipping_destination(planet)
|
||||
seen, rows = set(), []
|
||||
for ad in ads:
|
||||
cid = ad["ContractNaturalId"]
|
||||
if cid in seen:
|
||||
continue
|
||||
seen.add(cid)
|
||||
over_capacity = ad["CargoWeight"] > SHIP_CARGO or ad["CargoVolume"] > SHIP_CARGO
|
||||
cost = None if over_capacity else shipping.leg_cost(ad["OriginPlanetNaturalId"], ad["DestinationPlanetNaturalId"],
|
||||
sf_price, ff_price, v0, v1)
|
||||
payout = ad["PayoutPrice"] if ad["PayoutCurrency"] == "AIC" else None # non-AIC payout not priced here
|
||||
margin = (payout - cost["aic"]) if (cost and payout is not None) else None
|
||||
rows.append({**ad, "over_capacity": over_capacity, "cost": cost, "margin_aic": margin,
|
||||
"margin_per_day": margin / max(ad["DeliveryTime"], 1) if margin is not None else None})
|
||||
return rows
|
||||
@@ -22,6 +22,12 @@ def planets_full(refresh=False): return _g("/planet/allplanets/full", STATI
|
||||
def workforce_needs(refresh=False): return _g("/global/workforceneeds", STATIC, refresh)
|
||||
def systems(refresh=False): return _g("/systemstars", STATIC, refresh)
|
||||
def stations(refresh=False): return _g("/exchange/station", STATIC, refresh)
|
||||
def lm_shipping_source(planet: str, refresh=False):
|
||||
"""Live Local Market hauling ads where `planet` is the pickup - public, no auth needed."""
|
||||
return _g(f"/localmarket/shipping/source/{planet}", 15 * 60, refresh)
|
||||
def lm_shipping_destination(planet: str, refresh=False):
|
||||
"""Live Local Market hauling ads where `planet` is the drop-off - public, no auth needed."""
|
||||
return _g(f"/localmarket/shipping/destination/{planet}", 15 * 60, refresh)
|
||||
|
||||
|
||||
def own(path: str, ttl: int = 300, refresh: bool = False):
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
"""Daily exchange price/volume series from FIO's cxpc candles, shared by tools/history.py,
|
||||
tools/undervalued.py, tools/sell.py and puga/parkcash.py."""
|
||||
import datetime, math, statistics
|
||||
from . import fio
|
||||
|
||||
|
||||
def daily_prices(tk: str, cx: str) -> dict:
|
||||
"""date -> (VWAP price, units traded) for days with trades, from FIO cxpc DAY_ONE candles."""
|
||||
out = {}
|
||||
for e in fio.cxpc(tk, cx):
|
||||
if e.get("Interval") == "DAY_ONE" and e.get("Traded"):
|
||||
out[datetime.datetime.fromtimestamp(e["DateEpochMs"] / 1000, datetime.timezone.utc).date()] = (e["Volume"] / e["Traded"], e["Traded"])
|
||||
return out
|
||||
|
||||
|
||||
def trading_days(tk: str, cx: str, days: int = 30) -> list[tuple[datetime.date, float]]:
|
||||
"""(date, units traded) for actual trading days in the last `days` CALENDAR days - fio.cxpc
|
||||
only emits a row when a trade happened, so a sparse ticker needs a real calendar cutoff here,
|
||||
not "last N rows" (that would silently reach back far more than `days` actual days)."""
|
||||
cutoff = datetime.datetime.now(datetime.timezone.utc).date() - datetime.timedelta(days=days)
|
||||
return sorted((d, v) for d, (_, v) in daily_prices(tk, cx).items() if d >= cutoff)
|
||||
|
||||
|
||||
def trade_gaps_days(dates: list[datetime.date]) -> list[int]:
|
||||
return [(b - a).days for a, b in zip(dates, dates[1:])]
|
||||
|
||||
|
||||
def full_series(tk: str, cx: str) -> list[tuple[datetime.date, float]]:
|
||||
"""Full traded-price history (all available days, not windowed) ascending by date - for the
|
||||
empirical first-passage estimator below, which needs as much real history as exists rather
|
||||
than a 30d window, especially for distant target prices."""
|
||||
return sorted((d, p) for d, (p, _) in daily_prices(tk, cx).items())
|
||||
|
||||
|
||||
def _trailing_zscores(logp: list[float], trail: int = 60, min_window: int = 10) -> list[float | None]:
|
||||
"""z-score of each day's log-price against its own trailing `trail`-day mean/stdev (None where
|
||||
there isn't `min_window` days of history yet). A flat window (stdev 0) scores 0, not None -
|
||||
the price IS exactly at its own flat mean, that's a real, defined state, not missing data."""
|
||||
z = [None] * len(logp)
|
||||
for i in range(len(logp)):
|
||||
window = logp[max(0, i - trail + 1):i + 1]
|
||||
if len(window) < min_window:
|
||||
continue
|
||||
m = statistics.mean(window)
|
||||
sd = statistics.stdev(window) if len(window) > 1 else 0.0
|
||||
z[i] = (logp[i] - m) / sd if sd > 1e-12 else 0.0
|
||||
return z
|
||||
|
||||
|
||||
def empirical_touch(series: list[tuple[datetime.date, float]], y: float, rate: float,
|
||||
condition_on_state: bool = True, trail: int = 60, z_tol: float = 0.5,
|
||||
horizon: int | None = None) -> dict:
|
||||
"""Non-parametric first-passage stats for a target log-move `y` = ln(target_price/start_price),
|
||||
estimated directly from how often and how fast this ticker's REAL price history has made moves
|
||||
of that size - no random-walk/GBM assumption, so real mean-reversion shows up directly in the
|
||||
result instead of being assumed away (see docs/decisions.md for the evidence that real prices
|
||||
here do mean-revert).
|
||||
|
||||
Mean reversion means the answer depends on WHERE price is now relative to its own recent
|
||||
trend, not just on the move size - a 20% rise is more/less likely depending on whether today
|
||||
is already above or below the recent mean. With `condition_on_state` (default), only historical
|
||||
start days whose z-score against a trailing `trail`-day mean are within `z_tol` of TODAY's
|
||||
z-score (the series' last point) are used - keeping the estimate non-parametric (no fitted
|
||||
mean-reversion speed/strength) while still making it state-aware. Falls back to using every
|
||||
start day if there isn't enough history to compute today's z-score, or if the z_tol band is
|
||||
empty (too little data to condition on, not a real "always/never" signal).
|
||||
|
||||
For each eligible historical day i, scan forward for the first day j>i where the cumulative
|
||||
log-return reaches y (>= y if y>0, <= y if y<0). Contributes e^(-rho*dt) to the discount-factor
|
||||
average, where dt is the elapsed calendar days and rho = ln(1+rate); a day that NEVER reaches y
|
||||
within the observed history contributes 0 (not excluded - excluding right-censored samples
|
||||
would bias the estimate toward only the easy cases, since the hard/slow/never cases are exactly
|
||||
the ones that get cut off by the data running out).
|
||||
|
||||
CAVEAT: `series` is daily VWAP (one point per day), a discrete sample of a continuous price
|
||||
path. Discrete monitoring can only miss touches, never invent them - an intraday spike that
|
||||
crosses the target and reverts before the next day's VWAP is computed shows up as "not
|
||||
touched" here even though a resting ask would genuinely have filled on it. So this estimator
|
||||
is systematically conservative: real touch probability/hit_factor is at least this high, likely
|
||||
somewhat higher, and the resulting "sell now" lean (tools/sell.py --tiers) is a bit stronger
|
||||
than fully warranted. Standard discrete-monitoring barrier corrections (e.g. Broadie-Glasserman-
|
||||
Kou) put the gap at roughly 0.58*sigma*sqrt(step) per sampling interval for a short horizon -
|
||||
real at short horizons, shrinking as the horizon grows. Not corrected for here.
|
||||
|
||||
Without `horizon`, "never reached" means "not reached before the series ends" - which gives
|
||||
start days near the end of history much less time to ever register a hit than start days near
|
||||
the beginning, purely from running out of data, not economics. With `horizon` (days), only
|
||||
start days with at least that much real history remaining are used, and the search for day j
|
||||
is capped at `horizon` days past i for all of them - every sample gets the same fixed window,
|
||||
so touched_frac/hit_factor are comparable across samples instead of recency-biased. Off by
|
||||
default (every caller currently omits it) since it discards the most recent `horizon` days of
|
||||
start-day samples entirely - a real tradeoff, not a strict improvement on small histories.
|
||||
|
||||
Returns: hit_factor (empirical E[e^-rho*tau], the discounted-value multiplier), touched_frac
|
||||
(share of start days that ever reached y at all within their remaining history), median_days
|
||||
(None if touched_frac < 0.5 - can't report a median that was never reached more than half the
|
||||
time), n (sample count - note: these are heavily OVERLAPPING windows, not independent draws,
|
||||
so n overstates the effective sample size; same caveat as the backtest this reuses).
|
||||
"""
|
||||
n = len(series)
|
||||
if y == 0 or n < 2:
|
||||
return {"hit_factor": 1.0, "touched_frac": 1.0, "median_days": 0.0, "n": n}
|
||||
dates = [d for d, _ in series]
|
||||
logp = [math.log(p) for _, p in series if p > 0]
|
||||
rho = math.log(1 + rate)
|
||||
|
||||
eligible = range(n - 1)
|
||||
if horizon is not None:
|
||||
eligible = [i for i in eligible if (dates[-1] - dates[i]).days >= horizon]
|
||||
if condition_on_state:
|
||||
z = _trailing_zscores(logp, trail)
|
||||
z_today = z[-1]
|
||||
if z_today is not None:
|
||||
matched = [i for i in eligible if z[i] is not None and abs(z[i] - z_today) <= z_tol]
|
||||
if matched:
|
||||
eligible = matched
|
||||
|
||||
discount_sum, hit_days, count = 0.0, [], 0
|
||||
for i in eligible:
|
||||
target = logp[i] + y
|
||||
found = None
|
||||
for j in range(i + 1, n):
|
||||
if horizon is not None and (dates[j] - dates[i]).days > horizon:
|
||||
break
|
||||
if (y > 0 and logp[j] >= target) or (y < 0 and logp[j] <= target):
|
||||
found = j
|
||||
break
|
||||
count += 1
|
||||
if found is not None:
|
||||
dt = (dates[found] - dates[i]).days
|
||||
discount_sum += math.exp(-rho * dt)
|
||||
hit_days.append(dt)
|
||||
touched_frac = len(hit_days) / count if count else 0.0
|
||||
median_days = statistics.median(hit_days) if touched_frac >= 0.5 else None
|
||||
return {"hit_factor": discount_sum / count if count else 0.0, "touched_frac": touched_frac,
|
||||
"median_days": median_days, "n": count}
|
||||
+12
-1
@@ -8,6 +8,15 @@ the transferred quantity (base A "sells" it, base B "buys" it, at the same price
|
||||
combined total needs only ONE correction: the real freight cost of physically moving it, which
|
||||
isn't in either base's isolated numbers. Leftover surplus (more produced than a partner needs) is
|
||||
still validly sold at market by the producing base; leftover deficit is still validly bought.
|
||||
|
||||
CAVEAT: the "cancel out" claim only holds when the price basis prices buy and sell sides of a
|
||||
ticker identically (true for `uni30`, the default in tools/network.py). Under `--basis real`
|
||||
(or any basis with a genuine bid/ask spread), each base's own `simulate()` correctly books its
|
||||
flows at the real sell (bid/vwap) or buy (ask) price - but for the `moved` quantity, that's not
|
||||
what actually happens: it moves at no transaction price at all, not at both a real sale AND a
|
||||
real purchase. Summing the two bases' independent numbers and subtracting only freight therefore
|
||||
UNDERSTATES the true combined profit by the bid-ask spread on the moved quantity - a real gap,
|
||||
not symmetric cancellation, under any basis with a spread. Not corrected here.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from . import fio
|
||||
@@ -33,7 +42,9 @@ class Transfer:
|
||||
material: str
|
||||
src: str # producing base's name (key in the `bases` dict)
|
||||
dst: str # consuming base's name
|
||||
trip_cost: float = 9250.0 # AIC per round trip; PLACEHOLDER until a real route/fuel model exists
|
||||
trip_cost: float = 9250.0 # AIC per round trip; tools/network.py fills this from puga.shipping.round_trip_cost()
|
||||
# when src/dst are a direct-jump route and no explicit value is given in the chain
|
||||
# YAML - this default is the fallback for gateway routes/transfers without one
|
||||
cargo: float = 500.0 # t or m3 per trip
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Where to park idle cash as a buy-low/sell-high position (not a build) while ships are busy or
|
||||
cash has no better immediate use - the market-making tactic worked out by hand in-session before
|
||||
this existed. A big bid/ask spread alone is a trap (see OPEN GAPS below); this scores candidates
|
||||
on spread, real trading liquidity, and an EMPIRICAL round-trip estimate from the ticker's own
|
||||
price history - no random-walk/mean-reversion assumption (an earlier driftless-random-walk
|
||||
version of this kind of model was built for tools/sell.py and backtested WRONG against 3 years of
|
||||
real data - see docs/decisions.md's 2026-10-10 entries - so this one measures directly instead).
|
||||
|
||||
Method per ticker:
|
||||
- spread_pct: (ask - bid) / bid at the live quote.
|
||||
- liquidity: trading_days()/trade_gaps_days() over the last `days` calendar days - trades on most
|
||||
days with a short gap is real liquidity; a huge spread with few trading days is the trap this
|
||||
project already got burned by once (AST: 130% spread, 19/30 trading days, but the resting ask
|
||||
was stale - real last-traded price had already crashed 60% below it).
|
||||
- round trip = two sequential empirical first-passage legs (puga.history.empirical_touch), using
|
||||
the ticker's own full multi-year history, not an assumed distribution:
|
||||
buy leg: y = ln(bid/latest) - how often/fast has a move of this size (usually downward)
|
||||
actually happened, ever, in this ticker's real history?
|
||||
sell leg: y = ln(ask/bid) - same question for the recovery back up to ask.
|
||||
combined_days = buy.median_days + sell.median_days (both must happen, in sequence)
|
||||
combined_hit = buy.hit_factor * sell.hit_factor (treats the two legs as independent - an
|
||||
approximation, not exact, but each factor is itself a real empirically-measured expectation,
|
||||
not a parametric guess).
|
||||
- daily_pct: (ask-bid)/bid pessimistic margin over combined_days, as a SIMPLE (non-compounding)
|
||||
rate - see docs/decisions.md's "Drop ROI/day %" entry. For ranking by speed, not a yield.
|
||||
- discounted_pct: margin_pct x combined_hit - the SAME margin, discounted by both legs' real odds
|
||||
of ever happening at all (`--rate`'s only effect on the output; a low/near-0 default matches
|
||||
this tool's "idle cash, no better use" premise - pass a higher rate if this money actually IS
|
||||
earmarked for something and waiting has a real opportunity cost). A big gap between daily_pct
|
||||
and discounted_pct means the raw speed number is flattering a trade that may just never clear.
|
||||
|
||||
OPEN GAPS:
|
||||
- No CX transaction/fee field in FIO's exchange data (checked) - can't confirm or rule out a fee
|
||||
eating into the spread; not modelled.
|
||||
- Treating buy-leg and sell-leg as independent (multiplying hit factors, adding median days) is an
|
||||
approximation - the real joint distribution of "time to dip to bid, THEN time to recover to ask
|
||||
starting from wherever it actually dipped to" isn't computed exactly.
|
||||
"""
|
||||
import math, statistics
|
||||
from . import market
|
||||
from .history import daily_prices, trading_days, trade_gaps_days, full_series, empirical_touch
|
||||
|
||||
|
||||
def scan(cx: str = "AI1", min_spread_pct: float = 20.0, days: int = 30, rate: float = 0.0):
|
||||
"""Every (ticker, cx) with a live quote and spread_pct >= min_spread_pct, scored by pessimistic
|
||||
simple daily-equivalent return from the empirical round-trip model. Returns a list of dicts,
|
||||
unsorted (sort by 'daily_pct' - or let the caller filter on 'trade_days'/'gap_days' first,
|
||||
since those are what separate a real opportunity from a stale-quote trap)."""
|
||||
snap = market.snapshot()
|
||||
rows = []
|
||||
for (tk, q_cx), q in snap.items():
|
||||
if q_cx != cx or not q.ask or not q.bid or q.bid <= 0:
|
||||
continue
|
||||
spread_pct = 100 * (q.ask - q.bid) / q.bid
|
||||
if spread_pct < min_spread_pct:
|
||||
continue
|
||||
dp = daily_prices(tk, cx)
|
||||
if len(dp) < 2:
|
||||
continue
|
||||
td = trading_days(tk, cx, days)
|
||||
gaps = trade_gaps_days([d for d, _ in td])
|
||||
gap_days = statistics.median(gaps) if gaps else None
|
||||
if not gap_days or gap_days <= 0:
|
||||
continue
|
||||
series = full_series(tk, cx)
|
||||
latest = series[-1][1]
|
||||
if latest <= 0:
|
||||
continue
|
||||
buy = empirical_touch(series, math.log(q.bid / latest), rate)
|
||||
sell = empirical_touch(series, math.log(q.ask / q.bid), rate)
|
||||
if buy["median_days"] is None or sell["median_days"] is None:
|
||||
continue # one leg has never reliably happened in this ticker's real history
|
||||
combined_days = buy["median_days"] + sell["median_days"]
|
||||
combined_hit = buy["hit_factor"] * sell["hit_factor"]
|
||||
margin_pct = 100 * (q.ask - q.bid) / q.bid
|
||||
rows.append(dict(tk=tk, cx=cx, bid=q.bid, ask=q.ask, spread_pct=spread_pct, latest=latest,
|
||||
margin_pct=margin_pct, trade_days=len(td), window_days=days, gap_days=gap_days,
|
||||
buy_touch=buy["touched_frac"], sell_touch=sell["touched_frac"],
|
||||
wait_days=combined_days, hit_factor=combined_hit,
|
||||
daily_pct=margin_pct / combined_days if combined_days else 0.0,
|
||||
discounted_pct=margin_pct * combined_hit))
|
||||
return rows
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Rank planets by extraction factor for a resource. Also holds environment_extras(): FIO's own
|
||||
BuildRequirements field is an unreliable superset across hazard types (confirmed wrong in-game,
|
||||
see docs/mechanics.md) - the real per-building material is computed from the planet's own
|
||||
pressure/gravity/temperature/surface against the Prosperous Universe Handbook's threshold table,
|
||||
which PRUNplanner's own calculations don't model either."""
|
||||
from . import fio
|
||||
|
||||
# (condition check, ticker, qty per unit area, flat qty) - handbook building-costs table
|
||||
ENV_RULES = [
|
||||
(lambda p: (p.get("pressure") or 0) < 0.25, "SEA", 1.0, 0.0),
|
||||
(lambda p: (p.get("pressure") or 0) > 2.0, "HSE", 0.0, 1.0),
|
||||
(lambda p: 0 < (p.get("gravity") or 1) < 0.25, "MGC", 0.0, 1.0),
|
||||
(lambda p: (p.get("gravity") or 0) > 2.5, "BL", 0.0, 1.0),
|
||||
(lambda p: (p.get("temperature") if p.get("temperature") is not None else 20) < -25, "INS", 10.0, 0.0),
|
||||
(lambda p: (p.get("temperature") or 0) > 75, "TSH", 0.0, 1.0),
|
||||
]
|
||||
|
||||
|
||||
def environment_extras(planet: dict, area: float) -> dict[str, float]:
|
||||
"""Extra construction/repair materials a building needs beyond its normal BuildingCosts and
|
||||
the universal MCG area cost (already handled elsewhere, e.g. simulate()'s mcg_per_area) - one
|
||||
row per hazard the planet actually has (pressure/gravity/temperature; rocky-vs-gaseous MCG/AEF
|
||||
swap not covered here). planet needs lowercase pressure/gravity/temperature keys, e.g. from
|
||||
prunplanner._g('/data/planet/{id}/') or fio.planets_full() remapped to lowercase."""
|
||||
out: dict[str, float] = {}
|
||||
for cond, tk, per_area, flat in ENV_RULES:
|
||||
if cond(planet):
|
||||
out[tk] = out.get(tk, 0.0) + per_area * area + flat
|
||||
return out
|
||||
|
||||
|
||||
def candidates(resource_ticker: str, min_factor: float = 0.0):
|
||||
"""All planets with this resource, sorted by factor descending. Each: PlanetNaturalId,
|
||||
PlanetName, factor, resource_type, plus the raw planet record (temperature/pressure/
|
||||
gravity/fertility/faction/BuildRequirements/SystemId etc)."""
|
||||
mats = {m["Ticker"]: m["MaterialId"] for m in fio.materials()}
|
||||
mid = mats.get(resource_ticker.upper())
|
||||
if not mid:
|
||||
raise ValueError(f"unknown material ticker {resource_ticker!r}")
|
||||
out = []
|
||||
for p in fio.planets_full():
|
||||
for r in p.get("Resources", []):
|
||||
if r["MaterialId"] == mid and r["Factor"] >= min_factor:
|
||||
out.append({
|
||||
"natural_id": p["PlanetNaturalId"], "name": p["PlanetName"],
|
||||
"factor": r["Factor"], "resource_type": r["ResourceType"],
|
||||
"temperature": p["Temperature"], "pressure": p["Pressure"], "gravity": p["Gravity"],
|
||||
"fertility": p["Fertility"], "faction": p.get("FactionCode"),
|
||||
"system_id": p["SystemId"], "build_requirements": p.get("BuildRequirements", []),
|
||||
})
|
||||
out.sort(key=lambda x: -x["factor"])
|
||||
return out
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Jump-graph routing between systems/planets, built from FIO's /systemstars (698 systems,
|
||||
3D coordinates + jump connections). Not in PRUNplanner's own source (it doesn't model travel) -
|
||||
this is the project's own addition. Edge weight = straight-line distance between connected
|
||||
systems (ly); PrUn's own FTL fuel/time scale with this, not raw jump count, so Dijkstra on
|
||||
distance gives the right "cheapest" route, with jump count reported alongside for reference."""
|
||||
import heapq
|
||||
import math
|
||||
from . import fio
|
||||
|
||||
|
||||
def _dist(a, b):
|
||||
return math.dist((a["PositionX"], a["PositionY"], a["PositionZ"]),
|
||||
(b["PositionX"], b["PositionY"], b["PositionZ"]))
|
||||
|
||||
|
||||
def load_graph():
|
||||
"""SystemId -> {name, natural_id, pos, neighbors: {SystemId: distance_ly}}"""
|
||||
systems = {s["SystemId"]: s for s in fio.systems()}
|
||||
g = {}
|
||||
for sid, s in systems.items():
|
||||
neighbors = {}
|
||||
for c in s.get("Connections", []):
|
||||
other = systems.get(c["ConnectingId"])
|
||||
if other:
|
||||
neighbors[c["ConnectingId"]] = _dist(s, other)
|
||||
g[sid] = {"name": s["Name"], "natural_id": s["NaturalId"], "pos": s, "neighbors": neighbors}
|
||||
return g
|
||||
|
||||
|
||||
def resolve_system(query: str) -> str:
|
||||
"""Planet natural id (e.g. ZV-759c), CX station code (ANT), system natural id (ZV-759), or
|
||||
a name -> SystemId."""
|
||||
q = query.strip().upper()
|
||||
for p in fio.planets_full():
|
||||
if p.get("PlanetNaturalId", "").upper() == q or (p.get("PlanetName") or "").upper() == q:
|
||||
return p["SystemId"]
|
||||
for st in fio.stations():
|
||||
if st["NaturalId"].upper() == q or st["Name"].upper() == q:
|
||||
return st["SystemId"]
|
||||
for s in fio.systems():
|
||||
if s["NaturalId"].upper() == q or s["Name"].upper() == q:
|
||||
return s["SystemId"]
|
||||
raise ValueError(f"no planet, station, or system matches {query!r}")
|
||||
|
||||
|
||||
def shortest_path(src_system_id: str, dst_system_id: str, graph=None):
|
||||
"""Dijkstra by straight-line ly distance. Returns dict: jumps, distance_ly, path (list of system natural ids)."""
|
||||
g = graph or load_graph()
|
||||
if src_system_id not in g or dst_system_id not in g:
|
||||
raise ValueError("unknown system id")
|
||||
dist = {src_system_id: 0.0}
|
||||
prev = {}
|
||||
pq = [(0.0, src_system_id)]
|
||||
seen = set()
|
||||
while pq:
|
||||
d, u = heapq.heappop(pq)
|
||||
if u in seen:
|
||||
continue
|
||||
seen.add(u)
|
||||
if u == dst_system_id:
|
||||
break
|
||||
for v, w in g[u]["neighbors"].items():
|
||||
nd = d + w
|
||||
if nd < dist.get(v, float("inf")):
|
||||
dist[v] = nd
|
||||
prev[v] = u
|
||||
heapq.heappush(pq, (nd, v))
|
||||
if dst_system_id not in dist:
|
||||
return None
|
||||
path = [dst_system_id]
|
||||
while path[-1] != src_system_id:
|
||||
path.append(prev[path[-1]])
|
||||
path.reverse()
|
||||
return {
|
||||
"jumps": len(path) - 1,
|
||||
"distance_ly": dist[dst_system_id],
|
||||
"path": [g[sid]["natural_id"] for sid in path],
|
||||
}
|
||||
+71
-9
@@ -1,34 +1,96 @@
|
||||
"""Saturation model v1 (docs/saturation-design.md, after Opus review 2026-09-18). Pure functions.
|
||||
Idea: N buildings is limited by (a) share of the market's steady traded flow, (b) the queue of existing
|
||||
sell orders (supply days) and (c) whether buy-side stock covers it. Price is a haircut model, not a book walk."""
|
||||
import math
|
||||
Idea: N buildings is limited by (a) share of the market's steady traded flow and (b) the queue of
|
||||
existing sell orders (supply days). Price is a haircut model, not a book walk.
|
||||
|
||||
is_thin() checks demand depth as an independent red flag (a genuinely dead bid book is worth
|
||||
knowing about); n_out() does not multiply by it (see n_out's own docstring for why)."""
|
||||
import math, statistics
|
||||
from .history import trading_days
|
||||
|
||||
S_SHARE = 0.25 # max share of traded flow one producer takes
|
||||
T_Q = 7 # days of flow the standing sell queue is compared against
|
||||
T_D = 7 # days of flow standing demand should cover
|
||||
T_D = 7 # days of flow standing demand should cover (used by is_thin only)
|
||||
T_W = 3 # patient-selling window (days)
|
||||
|
||||
|
||||
def tref(traded7: float, traded30: float) -> float:
|
||||
"""Conservative daily flow: min(7d, 30d); with a Poisson lower bound when 30d volume is small."""
|
||||
"""Conservative daily flow: min(7d, 30d); with a Poisson lower bound when 30d volume is small.
|
||||
CAVEAT: the Poisson term treats each traded UNIT as an independent event, which overstates
|
||||
confidence for lumpy real trades (one 500-unit trade is one event, not 500) - see
|
||||
`tref_precise()` for the real-variance version, used once a candidate reaches stage 2 (this
|
||||
cheap version stays for stage-1 screening across every recipe, where fetching daily history
|
||||
for every ticker would be too expensive)."""
|
||||
t = min(traded7, traded30)
|
||||
if 0 < traded30 < 20:
|
||||
t = min(t, max(0.0, traded30 * (1 - 1.96 / math.sqrt(30 * traded30))))
|
||||
return max(0.0, t)
|
||||
|
||||
|
||||
def tref_precise(tk: str, cx: str, traded7: float, traded30: float, days: int = 30) -> float:
|
||||
"""Like tref(), but the lower bound comes from the REAL variance of daily traded volume
|
||||
(`puga.history.trading_days`) instead of a Poisson unit-independence assumption - one 500-unit
|
||||
trade is one data point here, not 500 independent ones. Falls back to tref() if there's too
|
||||
little real history to estimate variance from (<=2 trading days).
|
||||
|
||||
`trading_days()` only returns days with a trade - zero-volume days are absent, not zero - so
|
||||
the volume list is padded with explicit zeros for the missing calendar days before computing
|
||||
mean/stdev, and `days` (not the trading-day count) is used as n. Averaging only over the rows
|
||||
that have a trade would compute the mean volume ON TRADING DAYS, overstating real
|
||||
per-CALENDAR-day flow by 1/(fraction of days traded) - worst precisely for the sparse tickers
|
||||
this function exists to protect."""
|
||||
td = trading_days(tk, cx, days)
|
||||
if len(td) <= 2:
|
||||
return tref(traded7, traded30)
|
||||
vols = [v for _, v in td] + [0.0] * (days - len(td))
|
||||
mean = statistics.mean(vols)
|
||||
sd = statistics.stdev(vols)
|
||||
bound = max(0.0, mean - 1.96 * sd / math.sqrt(days))
|
||||
return max(0.0, min(tref(traded7, traded30), bound))
|
||||
|
||||
|
||||
def max_units_at_impact(bids: list[tuple[float, float]], ref_price: float, max_impact_pct: float = 10.0) -> float:
|
||||
"""Real, ticker-specific price-impact cap, replacing the flat S_SHARE guess for THIS check:
|
||||
how many units could be sold into the LIVE bid book before the price paid degrades more than
|
||||
`max_impact_pct` below `ref_price`. Walks bids highest-first (puga.market.walk's own
|
||||
mechanics) and stops at the first tier priced below the threshold.
|
||||
|
||||
A day-over-day price-vs-volume regression does not give a usable general elasticity estimate
|
||||
here: volume and price co-move mostly from DEMAND bursts (more buyers -> more volume AND
|
||||
steady/higher price), which swamps and often reverses the sign of the SUPPLY-side effect
|
||||
actually wanted (does MY added output push price down). Walking the real book sidesteps that
|
||||
confounding, but only captures the static liquidity snapshot, not how the market reprices
|
||||
over weeks of sustained extra output (nothing in available data answers that cleanly). See
|
||||
docs/decisions.md."""
|
||||
if not ref_price or ref_price <= 0:
|
||||
return 0.0
|
||||
threshold = ref_price * (1 - max_impact_pct / 100)
|
||||
cum = 0.0
|
||||
for price, qty in sorted(bids, key=lambda x: -x[0]):
|
||||
if price < threshold:
|
||||
break
|
||||
cum += qty
|
||||
return cum
|
||||
|
||||
|
||||
def is_thin(tr: float, demand: float, q_out: float) -> bool:
|
||||
return tr < 3 * q_out or demand < 7 * q_out
|
||||
|
||||
|
||||
def n_out(tr: float, supply: float, demand: float, q_out: float) -> float:
|
||||
"""Buildings the output market absorbs: flow share x queue penalty x demand coverage. 0 if no flow."""
|
||||
def n_out(tr: float, supply: float, q_out: float) -> float:
|
||||
"""Buildings the output market absorbs: flow share x queue penalty. 0 if no flow.
|
||||
|
||||
Deliberately has NO resting-bid-depth term: production sells via patient ASKS (`p_patient()`)
|
||||
that get taken by buyers crossing the spread, including walk-up buyers with no resting bid at
|
||||
all - a thin resting bid book doesn't mean they won't show up, since `tr` (real traded flow,
|
||||
already in `base`) is the actual evidence they do. A market with healthy ask-side flow and
|
||||
thin standing bids is normal (most buyers don't leave a bid sitting around), not evidence of
|
||||
absent demand. Real resting-bid demand is still checked independently by `is_thin()` as a red
|
||||
flag, not folded into this score."""
|
||||
if tr <= 0 or q_out <= 0:
|
||||
return 0.0
|
||||
base = S_SHARE * tr / q_out
|
||||
queue = min(1.0, T_Q * tr / supply) if supply > 0 else 1.0
|
||||
cover = min(1.0, demand / (T_D * tr))
|
||||
return base * queue * cover
|
||||
return base * queue
|
||||
|
||||
|
||||
def p_patient(asks: list[tuple[float, float]], tr: float, produced_per_day: float, bid: float, vwap7: float | None,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Ship flight fuel/cost model - STL cruise, FTL jumps/charges, gateway hops.
|
||||
|
||||
SCOPED TO ONE HULL/REACTOR: calibrated on AVI-07JFB (Freighter, blueprint BP-STRT-0000, stock
|
||||
reactor). The account has two ships - AVI-07JFB and AVI-07JFC - but both are the SAME blueprint
|
||||
with identical Acceleration/Thrust/ReactorPower/EmitterPower/OperatingEmptyMass (confirmed via
|
||||
FIO `/ship/ships/{user}`), so this model should apply to both; only their current cargo mass
|
||||
differs, and mass is already confirmed not to affect fuel/time (see below). Coefficients below
|
||||
are NOT confirmed to generalize to any OTHER hull or reactor module - there isn't one on this
|
||||
account to test against yet. Do not trust the magnitudes for a different hull/reactor without
|
||||
recalibrating (see "OPEN GAPS" below). Coefficients are fit from a controlled 4x4-grid sweep
|
||||
(fuel-usage x reactor-usage sliders) across 5 real destinations (Deimos, Nike, Vulcan, and
|
||||
gateway-routed Benten/Hortus), with exact values read from the live APEX Ship Flight Control DOM
|
||||
(never screenshots/estimates). Raw data: empire/data/shipping_calibration/.
|
||||
|
||||
CONFIRMED (high confidence, R^2 close to 1 on 4-point linear fits, cross-checked on 5 routes):
|
||||
- Fuel-usage slider (v0, 0..1 - NOT an absolute unit, see OPEN GAPS) and reactor-usage slider
|
||||
(v1, 0..1) are fully INDEPENDENT/additive - zero cross-term on any segment, confirmed on full
|
||||
4x4 grids. STL fuel never changes across different v1 at fixed v0, and vice versa for FTL.
|
||||
- STL cruise fuel (DEP/APP/long-TRA segments) = STL_INTERCEPT + STL_SLOPE * v0. Slope ~240
|
||||
units/unit-v0, essentially identical for DEP and APP and for long in-system TRA legs on
|
||||
gateway routes. Intercept is small (~1-8 units) and segment-specific.
|
||||
- FTL jump fuel = JUMP_FTL_SLOPE * v1 (no intercept). FTL recharge (CHRG, needed between two
|
||||
consecutive jumps with no landing in between) = CHARGE_FTL_SLOPE * v1 (no intercept, lower
|
||||
slope than a jump - recharging is cheaper than jumping).
|
||||
- LND (final landing) fuel is a CONSTANT per destination, independent of BOTH sliders -
|
||||
confirmed across full 4x4 grids on 3 planets (zero variation). This is NOT a formula, it's a
|
||||
per-planet constant that must be measured - see LANDING_FUEL below and its gravity/distance
|
||||
caveat.
|
||||
- Gateway (GTW) hops cost ZERO fuel (STL and FTL) - confirmed by direct inspection of raw
|
||||
segment rows on 2 different gateway-routed destinations (Benten: 3 gateways, Hortus: 2
|
||||
gateways). Cost is a fixed LOCK fee instead (AIC or CIS, varies per specific gateway, not
|
||||
predictable by formula - read it off the real route) plus a small fixed 5-unit STL cost for
|
||||
the LOCK maneuver itself. DCAY and short inter-gateway TRA hops are small fixed STL amounts
|
||||
(5-15 units) independent of both sliders. The reactor-usage slider is INERT on pure-gateway
|
||||
routes (no direct JMP segment) - confirmed its full allowed range changes nothing.
|
||||
|
||||
OPEN GAPS - do not assume these are resolved:
|
||||
1. v0's absolute meaning: at v0=1, STL fuel always came out to exactly the ship's then-current
|
||||
STL tank level (525-526, matching a tank at 526/1500 at calibration time) regardless of
|
||||
route distance - v0 looks like "fraction of CURRENTLY BUNKERED fuel to spend on this leg",
|
||||
not an absolute physical speed/fuel unit. This model's v0->fuel formula is calibrated
|
||||
against THAT fuel load; if the ship's tank level is very different, recalibrate rather than
|
||||
trust the magnitudes.
|
||||
2. DEP's departure-side gravity dependence is UNTESTED - every DEP segment in the calibration
|
||||
sweep departed from Antares Station (same origin, same gravity every time). A hypothesized
|
||||
"gravity-well-escape" term on departure has neither been confirmed nor refuted.
|
||||
3. LND fuel vs gravity vs distance is CONFOUNDED, not resolved - Deimos (gravity 1.032) and
|
||||
Vulcan (gravity 1.238) have near-identical landing distance (4,243 vs 4,441 km) and IDENTICAL
|
||||
landing fuel (38); Nike (gravity 0.624, lower) has a much longer landing distance (7,034 km)
|
||||
and higher fuel (48). This points at distance mattering more than gravity, but n=3 isn't
|
||||
enough for a real coefficient, and gravity/distance aren't varied independently in the
|
||||
sample. Don't predict LND fuel for an unmeasured planet - look it up for real.
|
||||
4. Hull/reactor generalization beyond this one blueprint (BP-STRT-0000, stock reactor) is
|
||||
COMPLETELY UNTESTED - both ships on this account (AVI-07JFB, AVI-07JFC) share it, so there's
|
||||
nothing else to cross-check against yet. The reactor-usage slider's own allowed range was
|
||||
only 0.303-1 even on direct-jump routes, suggesting the stock reactor is itself constrained -
|
||||
a different reactor module would need its own sweep, not an assumption that these
|
||||
slopes/intercepts carry over.
|
||||
5. KNOWN_GATEWAY_ROUTES assumes a gateway chain is usable and equally priced in both directions.
|
||||
Per the official handbook (handbook.apex.prosperousuniverse.com/wiki/infrastructure-gateway),
|
||||
some gateway links are ONE-WAY (map arrows show the permitted direction) - the reverse leg of
|
||||
a known route may not exist at all, not just cost something different. round_trip_cost()
|
||||
and leg_cost() have no way to detect this; don't trust a return leg on a gateway route until
|
||||
it's separately confirmed live.
|
||||
6. Each gateway has its own maximum per-jump VOLUME (m3) cap, per the handbook, independent of
|
||||
ship cargo capacity - not measured or modelled anywhere here. This matters for any "use a
|
||||
bigger ship to bundle more cargo through one gateway trip" reasoning (see tools/lmscan.py
|
||||
analysis) - a bigger hold doesn't help if the gateway's own cap is lower.
|
||||
7. TRIP TIME (not just fuel) is not modelled anywhere in this file. For what we do know about
|
||||
GTW segment duration (scales ~linearly with parsec distance at ~20 min/parsec, contradicting
|
||||
a pre-launch dev statement about a possibly-fixed duration), see docs/mechanics.md's
|
||||
"Gateway (GTW) jump transit time" section - built from the same raw data this module uses.
|
||||
"""
|
||||
|
||||
# Calibrated on AVI-07JFB, 2026-10-09. See module docstring for what's confirmed vs open.
|
||||
STL_SLOPE = 240.0 # units per unit of v0 (fuel-usage slider), DEP/APP/long-TRA alike
|
||||
STL_INTERCEPT = 3.0 # small, roughly the DEP/APP average; noise-level, not precise
|
||||
JUMP_FTL_SLOPE = 28.4 # units per unit of v1 (reactor-usage slider), per direct JMP
|
||||
CHARGE_FTL_SLOPE = 22.8 # units per unit of v1, per CHRG (recharge between consecutive jumps)
|
||||
|
||||
# Fixed, slider-independent costs on gateway-routed segments (confirmed on Benten/Hortus):
|
||||
GATEWAY_HOP_FIXED_STL = 5.0 # the LOCK maneuver itself
|
||||
SHORT_TRA_FIXED_STL = 15.0 # the ~10s hop immediately around a gateway
|
||||
DCAY_FIXED_STL = 5.0 # post-gateway decay step
|
||||
|
||||
# The hull/reactor this file is calibrated against (both AVI-07JFB and AVI-07JFC match this via
|
||||
# FIO /ship/ships/{user} - confirmed 2026-10-09). tools/shiptrip.py checks a given ship's live
|
||||
# specs against this and warns if they don't match (a third, different ship would invalidate
|
||||
# the coefficients above - see OPEN GAPS #4).
|
||||
CALIBRATED_SPEC = {"blueprint": "BP-STRT-0000", "acceleration": 78.4800033569336, "thrust": 125000.0,
|
||||
"reactor_power": 2400.0, "emitter_power": 725.0}
|
||||
|
||||
# LOOKUP, not a formula (see OPEN GAPS #3) - only destinations we've actually measured.
|
||||
# {planet_natural_id: (landing_fuel_STL, landing_distance_km, gravity)}
|
||||
LANDING_FUEL = {
|
||||
"ZV-759c": (38, 4243, 1.032), # Deimos
|
||||
"ZV-759b": (38, 4441, 1.238), # Vulcan
|
||||
"ZV-194a": (48, 7034, 0.624), # Nike
|
||||
}
|
||||
|
||||
|
||||
def cruise_leg_fuel(v0: float) -> float:
|
||||
"""One STL cruise leg (DEP, APP, or a long in-system TRA on a gateway route)."""
|
||||
return STL_INTERCEPT + STL_SLOPE * v0
|
||||
|
||||
|
||||
def jump_fuel(v1: float) -> float:
|
||||
"""One direct FTL jump (JMP segment, not a gateway hop)."""
|
||||
return JUMP_FTL_SLOPE * v1
|
||||
|
||||
|
||||
def charge_fuel(v1: float) -> float:
|
||||
"""One FTL recharge (CHRG) between two consecutive jumps with no landing between them."""
|
||||
return CHARGE_FTL_SLOPE * v1
|
||||
|
||||
|
||||
def gateway_hop_cost(lock_fee_amount: float, lock_fee_currency: str):
|
||||
"""One gateway hop (LOCK + GTW + DCAY + the short TRA around it): the GTW segment itself
|
||||
is free (confirmed), but LOCK charges a fixed real-money fee you must supply (not
|
||||
predictable - read it off the actual route, it varies per specific gateway pair)."""
|
||||
stl = GATEWAY_HOP_FIXED_STL + SHORT_TRA_FIXED_STL + DCAY_FIXED_STL
|
||||
return {"stl_fuel": stl, "fee_amount": lock_fee_amount, "fee_currency": lock_fee_currency}
|
||||
|
||||
|
||||
def landing_fuel(planet_natural_id: str):
|
||||
"""Looked-up, not predicted - returns None if we haven't actually measured this planet.
|
||||
See OPEN GAPS #3: don't extrapolate this to an unmeasured planet."""
|
||||
row = LANDING_FUEL.get(planet_natural_id)
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
# Specific gateway-chain routes we've actually measured, keyed by frozenset so the SAME entry
|
||||
# is used for either direction - NOT confirmed to be valid: the handbook says some gateway links
|
||||
# are one-way, so the reverse leg may not exist or may cost differently (see OPEN GAPS #5).
|
||||
# {frozenset({a, b}): [(fee_amount, fee_currency), ...]}
|
||||
KNOWN_GATEWAY_ROUTES = {
|
||||
frozenset({"ANT", "HRT"}): [(6000, "AIC"), (6000, "AIC")],
|
||||
frozenset({"ANT", "BEN"}): [(6000, "AIC"), (6000, "AIC"), (4000, "CIS")],
|
||||
}
|
||||
|
||||
|
||||
def cx_system(cx: str) -> str | None:
|
||||
"""CX code (AI1, CI1, ...) -> the natural id of its physical station, from FIO's own
|
||||
/exchange/station (ComexCode). Feeds leg_cost/round_trip_cost's src argument when the origin
|
||||
is "the home exchange" rather than a specific planet. None if the code isn't a real station."""
|
||||
from . import fio
|
||||
row = next((s for s in fio.stations() if s.get("ComexCode") == cx), None)
|
||||
return row["NaturalId"] if row else None
|
||||
|
||||
|
||||
def leg_cost(src: str, dst: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||
"""One-way fuel (+ gateway fee) AIC cost between two places (station/planet natural ids).
|
||||
Prefers a measured gateway chain (KNOWN_GATEWAY_ROUTES) when this exact pair has one;
|
||||
otherwise tries the direct-jump graph (puga.route). Returns None if neither applies - an
|
||||
unmeasured gateway route, where the LOCK fee can't be priced at all. Non-AIC gateway fees
|
||||
(e.g. CIS) are reported separately, not folded into `aic`."""
|
||||
from . import route
|
||||
key = frozenset({src, dst})
|
||||
if key in KNOWN_GATEWAY_ROUTES:
|
||||
result = trip_fuel(v0, v1, jumps=0, charges=0, cruise_legs=2, dest_planet_natural_id=dst,
|
||||
gateway_lock_fees=KNOWN_GATEWAY_ROUTES[key])
|
||||
else:
|
||||
try:
|
||||
src_sys, dst_sys = route.resolve_system(src), route.resolve_system(dst)
|
||||
except ValueError:
|
||||
return None
|
||||
if src_sys == dst_sys:
|
||||
jumps = 0
|
||||
else:
|
||||
r = route.shortest_path(src_sys, dst_sys)
|
||||
if r is None:
|
||||
return None
|
||||
jumps = r["jumps"]
|
||||
result = trip_fuel(v0, v1, jumps, max(jumps - 1, 0), cruise_legs=2, dest_planet_natural_id=dst)
|
||||
aic = result["stl_fuel"] * sf_price + result["ftl_fuel"] * ff_price
|
||||
aic += sum(amt for amt, cur in result["lock_fees"] if cur == "AIC")
|
||||
non_aic_fees = [(amt, cur) for amt, cur in result["lock_fees"] if cur != "AIC"]
|
||||
return {"aic": aic, "non_aic_fees": non_aic_fees, "stl_fuel": result["stl_fuel"], "ftl_fuel": result["ftl_fuel"],
|
||||
"landing_fuel_included": result["landing_fuel_included"]}
|
||||
|
||||
|
||||
def round_trip_cost(src: str, dst: str, sf_price: float, ff_price: float, v0: float = 1.0, v1: float = 1.0):
|
||||
"""AIC cost of a round trip (there and back) between two places - the sum of two `leg_cost`
|
||||
calls, there and back. Returns None if either leg can't be priced (an unmeasured gateway
|
||||
route) or either leg carries a non-AIC fee (no AIC exchange rate assumed here - see
|
||||
`leg_cost`'s `non_aic_fees`, which this collapses rather than silently drop)."""
|
||||
there, back = leg_cost(src, dst, sf_price, ff_price, v0, v1), leg_cost(dst, src, sf_price, ff_price, v0, v1)
|
||||
if there is None or back is None or there["non_aic_fees"] or back["non_aic_fees"]:
|
||||
return None
|
||||
return there["aic"] + back["aic"]
|
||||
|
||||
|
||||
def trip_fuel(v0: float, v1: float, jumps: int, charges: int, cruise_legs: int = 2,
|
||||
dest_planet_natural_id: str | None = None, gateway_lock_fees: list[tuple[float, str]] = ()):
|
||||
"""Total STL/FTL fuel (plus any gateway LOCK fees passed straight through) for one trip.
|
||||
This is the one place the cost arithmetic lives - tools/shipcost.py (manual/explicit
|
||||
params) and tools/shiptrip.py (--ship/--from/--to, auto-derives jumps/charges/landing)
|
||||
both call this instead of duplicating it. Returns {stl_fuel, ftl_fuel, lock_fees:
|
||||
[(amount, currency), ...], landing_fuel_included: bool}."""
|
||||
stl = cruise_legs * cruise_leg_fuel(v0)
|
||||
ftl = jumps * jump_fuel(v1) + charges * charge_fuel(v1)
|
||||
fees = []
|
||||
for amount, currency in gateway_lock_fees:
|
||||
g = gateway_hop_cost(amount, currency)
|
||||
stl += g["stl_fuel"]
|
||||
fees.append((g["fee_amount"], g["fee_currency"]))
|
||||
lnd = landing_fuel(dest_planet_natural_id) if dest_planet_natural_id else None
|
||||
if lnd is not None:
|
||||
stl += lnd
|
||||
return {"stl_fuel": stl, "ftl_fuel": ftl, "lock_fees": fees, "landing_fuel_included": lnd}
|
||||
+7
-3
@@ -2,6 +2,7 @@
|
||||
Input is a PRUNplanner plan JSON (as stored by the API, or built by tools/plan_push.build_payload). Pure given the data passed in.
|
||||
Validated against a screenshot of the real simulator (tests/test_simulate.py)."""
|
||||
from . import econ
|
||||
from . import planet as planet_mod
|
||||
|
||||
TIERS = econ.TIERS
|
||||
FARMS = {"FRM", "ORC"}
|
||||
@@ -10,8 +11,8 @@ DEGRADATION_DAYS = 180 # usePlanCalculation.ts: degradation/day = const
|
||||
|
||||
def simulate(plan: dict, recipes: list[dict], buildings: list[dict], resources: list[dict], fertility: float,
|
||||
price, faction: str | None = None, permits: tuple[float, float] = (1, 2), mcg_per_area: float = 4.0,
|
||||
built: dict[str, int] | None = None) -> dict:
|
||||
"""price(ticker, side) -> AIC per unit or None; side is "buy" (net consumed) or "sell" (net produced), like PRUNplanner BUY/SELL exchange preferences; construction uses "buy". resources: planet resources [{material_ticker, resource_type, daily_extraction}]."""
|
||||
built: dict[str, int] | None = None, planet: dict | None = None) -> dict:
|
||||
"""price(ticker, side) -> AIC per unit or None; side is "buy" (net consumed) or "sell" (net produced), like PRUNplanner BUY/SELL exchange preferences; construction uses "buy". resources: planet resources [{material_ticker, resource_type, daily_extraction}]. planet: optional, adds environment-extra construction materials via planet.environment_extras() (SEA/HSE/MGC/BL/INS/TSH - needs lowercase pressure/gravity/temperature keys)."""
|
||||
d = plan["plan_data"]
|
||||
bl = {b["building_ticker"]: b for b in buildings}
|
||||
rec = {r["recipe_id"]: r for r in recipes}
|
||||
@@ -69,7 +70,10 @@ def simulate(plan: dict, recipes: list[dict], buildings: list[dict], resources:
|
||||
|
||||
def unit_cost(tk):
|
||||
info = bl[tk]
|
||||
return sum(c["material_amount"] * (price(c["material_ticker"], "buy") or 0) for c in info["costs"]) + mcg_per_area * info["area_cost"] * (price("MCG", "buy") or 0)
|
||||
cost = sum(c["material_amount"] * (price(c["material_ticker"], "buy") or 0) for c in info["costs"]) + mcg_per_area * info["area_cost"] * (price("MCG", "buy") or 0)
|
||||
if planet is not None:
|
||||
cost += sum(qty * (price(etk, "buy") or 0) for etk, qty in planet_mod.environment_extras(planet, info["area_cost"]).items())
|
||||
return cost
|
||||
|
||||
# Verified vs simulator screenshots: degradation = production buildings' construction cost / 180 (infrastructure excluded);
|
||||
# plan cost and area also include one core module (CM), added automatically.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Finds manufactured goods currently selling below their implied production cost (output price
|
||||
minus input cost, from live daily VWAP candles) - the mirror image of saturation.py's "is this
|
||||
worth building" question: here we're asking "is this worth buying and holding for a price-
|
||||
reversion bounce."
|
||||
|
||||
Backtested 2026-10-09 across 326 output tickers / 112 distinct tickers that ever showed the
|
||||
signal, 287 independent dip-onset episodes (deduplicated so a persisting dip only counts once,
|
||||
at onset, not once per month it continues): at >=10 units/day traded volume, +3 months forward
|
||||
price return was mean +21.3%, median +8.9%, 73.2% of episodes positive (see empire/docs or the
|
||||
session that built this for the raw numbers). That is ~0.10-0.24%/day - MUCH lower than this
|
||||
project's production-building marginal ROI (14-29%/day seen this session). Only worth deploying
|
||||
*excess* capital into once better-yielding builds are exhausted, not as a primary strategy, and
|
||||
it's a gross-return backtest with no spread/freight/storage-fee/capital-lockup cost subtracted.
|
||||
"""
|
||||
from . import fio
|
||||
from .history import daily_prices
|
||||
|
||||
|
||||
def manufacturing_candidates():
|
||||
"""One representative recipe per output ticker, excluding pure-extraction buildings (no
|
||||
material inputs to compute an implied cost from)."""
|
||||
seen = {}
|
||||
for r in fio.recipes():
|
||||
if r["BuildingTicker"] in ("EXT", "COL", "RIG") or not r["Inputs"]:
|
||||
continue
|
||||
for o in r["Outputs"]:
|
||||
seen.setdefault(o["Ticker"], r)
|
||||
return seen
|
||||
|
||||
|
||||
def current_margin(ticker: str, recipe: dict, cx: str, window_days: int = 35, recent_days: int = 14):
|
||||
"""Mean margin%/price/volume over the most recent `recent_days` of overlapping price history
|
||||
for this recipe's inputs+output, within a `window_days` lookback. None if not enough history."""
|
||||
ins = {i["Ticker"]: i["Amount"] for i in recipe["Inputs"]}
|
||||
outs = {o["Ticker"]: o["Amount"] for o in recipe["Outputs"]}
|
||||
series = {m: daily_prices(m, cx) for m in list(ins) + list(outs)}
|
||||
if any(not s for s in series.values()):
|
||||
return None
|
||||
days = sorted(set().union(*[set(s) for s in series.values()]))[-window_days:]
|
||||
last = {}
|
||||
rows = []
|
||||
for d in days:
|
||||
for m, s in series.items():
|
||||
if d in s:
|
||||
last[m] = s[d][0]
|
||||
if len(last) == len(series):
|
||||
rev = sum(last[m] * n for m, n in outs.items())
|
||||
cost = sum(last[m] * n for m, n in ins.items())
|
||||
rows.append((rev, cost, last[ticker], series[ticker].get(d, (0, 0))[1]))
|
||||
recent = rows[-recent_days:]
|
||||
if len(recent) < recent_days // 2:
|
||||
return None
|
||||
rev_m = sum(x[0] for x in recent) / len(recent)
|
||||
cost_m = sum(x[1] for x in recent) / len(recent)
|
||||
px_m = sum(x[2] for x in recent) / len(recent)
|
||||
vol_m = sum(x[3] for x in recent) / len(recent)
|
||||
margin_pct = 100 * (rev_m - cost_m) / cost_m if cost_m else 0.0
|
||||
return {"margin_pct": margin_pct, "price": px_m, "volume": vol_m, "building": recipe["BuildingTicker"]}
|
||||
|
||||
|
||||
def scan_current(cx: str, min_vol: float = 5.0):
|
||||
"""Every manufactured good currently priced below its implied production cost, with enough
|
||||
volume to actually trade, sorted most-undervalued first."""
|
||||
out = []
|
||||
for t, r in manufacturing_candidates().items():
|
||||
m = current_margin(t, r, cx)
|
||||
if m and m["margin_pct"] < 0 and m["volume"] >= min_vol:
|
||||
out.append({"ticker": t, **m})
|
||||
out.sort(key=lambda x: x["margin_pct"])
|
||||
return out
|
||||
@@ -0,0 +1,72 @@
|
||||
import datetime, math
|
||||
from puga.history import empirical_touch, _trailing_zscores
|
||||
|
||||
|
||||
def _series(jump_idx, n=20, jump_price=220.0, base_price=100.0):
|
||||
base = datetime.date(2026, 1, 1)
|
||||
return [(base + datetime.timedelta(days=i), jump_price if i >= jump_idx else base_price) for i in range(n)]
|
||||
|
||||
|
||||
def test_hit_factor_has_no_cliff_at_the_50pct_touched_threshold():
|
||||
"""median_days flips from a number to None the instant touched_frac crosses 50% - that's
|
||||
fine as a reported diagnostic, but ranking by it (as sell.py's --tiers used to) creates a
|
||||
fake cliff: a tier touched 47% of the time would be valued at exactly 0, one touched 53% of
|
||||
the time at near-full value, even though hit_factor (the real E[e^-rho*tau]) moves smoothly
|
||||
between them. This is what tools/sell.py's --tiers ranks by instead."""
|
||||
y = math.log(2.0)
|
||||
below = empirical_touch(_series(jump_idx=9), y, rate=0.05, condition_on_state=False)
|
||||
above = empirical_touch(_series(jump_idx=10), y, rate=0.05, condition_on_state=False)
|
||||
assert below["median_days"] is None and above["median_days"] is not None
|
||||
assert below["touched_frac"] < 0.5 <= above["touched_frac"]
|
||||
# hit_factor must not have fallen off a cliff just because median_days did
|
||||
assert below["hit_factor"] > 0.5 * above["hit_factor"]
|
||||
|
||||
|
||||
def test_empirical_touch_trivial_for_zero_move():
|
||||
r = empirical_touch(_series(jump_idx=5), 0.0, rate=0.05)
|
||||
assert r == {"hit_factor": 1.0, "touched_frac": 1.0, "median_days": 0.0, "n": 20}
|
||||
|
||||
|
||||
def test_conditioning_on_state_uses_only_similar_regime_days():
|
||||
"""Mean reversion means the answer should depend on whether today looks like the ticker's
|
||||
readily-rising early regime or its since-flattened plateau - not blend both in unconditionally.
|
||||
Series: 20 flat days, then a steady climb, then 10 more flat days at the new high (today is
|
||||
in the plateau, not the climb)."""
|
||||
base = datetime.date(2026, 1, 1)
|
||||
prices = [100] * 20 + [100 + i * 5 for i in range(1, 11)] + [150] * 10
|
||||
series = [(base + datetime.timedelta(days=i), float(p)) for i, p in enumerate(prices)]
|
||||
y = math.log(1.1)
|
||||
uncond = empirical_touch(series, y, rate=0.05, condition_on_state=False)
|
||||
cond = empirical_touch(series, y, rate=0.05, condition_on_state=True)
|
||||
assert uncond["touched_frac"] > 0.5 # blends in the climb regime, looks like it moves readily
|
||||
assert cond["touched_frac"] < uncond["touched_frac"] # today's plateau regime moves less
|
||||
|
||||
|
||||
def test_trailing_zscores_flat_window_is_zero_not_none():
|
||||
logp = [math.log(100.0)] * 15
|
||||
z = _trailing_zscores(logp, trail=60, min_window=10)
|
||||
assert z[:9] == [None] * 9 # not enough window yet
|
||||
assert z[9:] == [0.0] * 6 # flat price is exactly at its own mean - a real, defined state
|
||||
|
||||
|
||||
def test_horizon_removes_recency_bias_from_right_censoring():
|
||||
"""Without a fixed horizon, start days near the end of history get an unfairly short (or
|
||||
long) remaining window to register a touch, purely from running out of data. A flat series
|
||||
with a late jump looks like it "touches" readily only because the jump happens to sit right
|
||||
next to the end-of-history start days; a fixed horizon gives every sample the same window."""
|
||||
base = datetime.date(2026, 1, 1)
|
||||
prices = [100.0] * 30 + [220.0] * 5
|
||||
series = [(base + datetime.timedelta(days=i), p) for i, p in enumerate(prices)]
|
||||
y = math.log(2.0)
|
||||
uncapped = empirical_touch(series, y, rate=0.05, condition_on_state=False)
|
||||
capped = empirical_touch(series, y, rate=0.05, condition_on_state=False, horizon=5)
|
||||
assert capped["touched_frac"] < uncapped["touched_frac"]
|
||||
assert capped["n"] < uncapped["n"] # the last `horizon` days of start days are dropped
|
||||
|
||||
|
||||
def test_empirical_touch_never_reached_is_zero_not_excluded():
|
||||
# a move far beyond anything the series ever does should look like "basically never"
|
||||
r = empirical_touch(_series(jump_idx=19, jump_price=101.0), math.log(50.0), rate=0.05)
|
||||
assert r["touched_frac"] == 0.0
|
||||
assert r["hit_factor"] == 0.0
|
||||
assert r["median_days"] is None
|
||||
@@ -0,0 +1,28 @@
|
||||
from puga import route
|
||||
|
||||
# Small synthetic graph: A-B-C in a line, A-D direct (shorter), D-C (closes a loop so Dijkstra has a choice)
|
||||
GRAPH = {
|
||||
"A": {"name": "A", "natural_id": "A", "pos": None, "neighbors": {"B": 10.0, "D": 3.0}},
|
||||
"B": {"name": "B", "natural_id": "B", "pos": None, "neighbors": {"A": 10.0, "C": 10.0}},
|
||||
"C": {"name": "C", "natural_id": "C", "pos": None, "neighbors": {"B": 10.0, "D": 10.0}},
|
||||
"D": {"name": "D", "natural_id": "D", "pos": None, "neighbors": {"A": 3.0, "C": 10.0}},
|
||||
}
|
||||
|
||||
|
||||
def test_shortest_path_picks_lower_total_distance_not_fewer_jumps():
|
||||
r = route.shortest_path("A", "C", graph=GRAPH)
|
||||
assert r["path"] == ["A", "D", "C"] # 3+10=13, beats A-B-C's 10+10=20 despite same jump count
|
||||
assert r["jumps"] == 2
|
||||
assert r["distance_ly"] == 13.0
|
||||
|
||||
|
||||
def test_same_system_is_zero_jumps():
|
||||
r = route.shortest_path("A", "A", graph=GRAPH)
|
||||
assert r["jumps"] == 0
|
||||
assert r["distance_ly"] == 0.0
|
||||
|
||||
|
||||
def test_no_route_returns_none():
|
||||
graph = dict(GRAPH)
|
||||
graph["E"] = {"name": "E", "natural_id": "E", "pos": None, "neighbors": {}}
|
||||
assert route.shortest_path("A", "E", graph=graph) is None
|
||||
@@ -1,3 +1,4 @@
|
||||
import datetime
|
||||
import math
|
||||
from puga import saturation as s, market, fio
|
||||
|
||||
@@ -8,12 +9,22 @@ def test_tref_uses_min_and_poisson_floor():
|
||||
assert s.tref(0, 0) == 0
|
||||
|
||||
|
||||
def test_n_out_penalises_queue_and_thin_demand():
|
||||
free = s.n_out(100, 0, 10_000, 5) # no queue, ample demand
|
||||
def test_tref_precise_pads_missing_calendar_days_not_just_trading_days(monkeypatch):
|
||||
# 10 trading days out of 30, each with volume 30 -> real per-calendar-day mean is 10, not 30.
|
||||
# The original bug averaged only over the 10 trading-day rows (mean 30), overstating the
|
||||
# bound 3x for exactly the sparse tickers it's meant to protect.
|
||||
base = datetime.date(2026, 1, 1)
|
||||
fake_td = [(base + datetime.timedelta(days=i * 3), 30.0) for i in range(10)]
|
||||
monkeypatch.setattr(s, "trading_days", lambda tk, cx, days: fake_td)
|
||||
bound = s.tref_precise("FAKE", "AI1", traded7=30, traded30=30, days=30)
|
||||
assert bound < 15.0 # well below the naive trading-day mean of 30, reflecting real sparsity
|
||||
|
||||
|
||||
def test_n_out_penalises_queue():
|
||||
free = s.n_out(100, 0, 5) # no queue
|
||||
assert math.isclose(free, 0.25 * 100 / 5)
|
||||
assert s.n_out(100, 7000, 10_000, 5) < free # 70 days of queue cuts it
|
||||
assert s.n_out(100, 0, 100, 5) < free # demand only 1 day of flow cuts it
|
||||
assert s.n_out(0, 0, 100, 5) == 0
|
||||
assert s.n_out(100, 7000, 5) < free # 70 days of queue cuts it
|
||||
assert s.n_out(0, 0, 5) == 0
|
||||
|
||||
|
||||
def test_thin_flag():
|
||||
@@ -57,3 +68,11 @@ def test_effective_demand_excludes_stale_bids_below_the_band():
|
||||
bids = [(4550, 8), (4200, 250), (2810, 8), (334, 19)]
|
||||
assert s.effective_demand(bids, band=(663, 16575)) == 8 + 250 + 8 # the 334 bid is stale, excluded
|
||||
assert s.effective_demand(bids, band=None) == 8 + 250 + 8 + 19
|
||||
|
||||
|
||||
def test_max_units_at_impact_stops_at_the_price_threshold():
|
||||
bids = [(100, 10), (95, 20), (85, 1000)] # ref 100, 10% floor = 90
|
||||
assert s.max_units_at_impact(bids, 100, max_impact_pct=10.0) == 30 # 100 and 95 tiers only
|
||||
assert s.max_units_at_impact(bids, 100, max_impact_pct=20.0) == 1030 # all three tiers now qualify
|
||||
assert s.max_units_at_impact([], 100) == 0.0
|
||||
assert s.max_units_at_impact(bids, 0) == 0.0
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Expected values from the real APEX Ship Flight Control DOM reads, 2026-10-09 calibration
|
||||
sweep (AVI-07JFB). Raw data in empire/data/shipping_calibration/."""
|
||||
import pytest
|
||||
from puga import shipping
|
||||
|
||||
|
||||
@pytest.mark.parametrize("v0,actual", [(0.01, 3), (0.34, 83), (0.67, 162), (1.0, 242)])
|
||||
def test_cruise_leg_fuel_matches_dep(v0, actual):
|
||||
assert shipping.cruise_leg_fuel(v0) == pytest.approx(actual, abs=5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("v1,actual", [(0.303, 8), (0.535, 15), (0.768, 21), (1.0, 28)])
|
||||
def test_jump_fuel(v1, actual):
|
||||
assert shipping.jump_fuel(v1) == pytest.approx(actual, abs=1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("v1,actual", [(0.303, 6), (0.535, 12), (0.768, 17), (1.0, 22)])
|
||||
def test_charge_fuel(v1, actual):
|
||||
assert shipping.charge_fuel(v1) == pytest.approx(actual, abs=1)
|
||||
|
||||
|
||||
def test_charge_cheaper_than_jump():
|
||||
for v1 in (0.3, 0.5, 0.7, 1.0):
|
||||
assert shipping.charge_fuel(v1) < shipping.jump_fuel(v1)
|
||||
|
||||
|
||||
def test_landing_fuel_lookup():
|
||||
assert shipping.landing_fuel("ZV-759c") == 38 # Deimos
|
||||
assert shipping.landing_fuel("ZV-759b") == 38 # Vulcan
|
||||
assert shipping.landing_fuel("ZV-194a") == 48 # Nike
|
||||
|
||||
|
||||
def test_landing_fuel_unmeasured_returns_none():
|
||||
assert shipping.landing_fuel("ZV-307") is None
|
||||
|
||||
|
||||
def test_gateway_hop_is_fuel_free_plus_fixed_fee():
|
||||
g = shipping.gateway_hop_cost(6000, "AIC")
|
||||
assert g["fee_amount"] == 6000
|
||||
assert g["fee_currency"] == "AIC"
|
||||
assert g["stl_fuel"] == shipping.GATEWAY_HOP_FIXED_STL + shipping.SHORT_TRA_FIXED_STL + shipping.DCAY_FIXED_STL
|
||||
|
||||
|
||||
def test_sliders_additive_no_cross_term():
|
||||
# cruise fuel must not depend on v1, jump fuel must not depend on v0 - the whole point
|
||||
# of the independence finding this model is built on.
|
||||
base = shipping.cruise_leg_fuel(0.5)
|
||||
assert shipping.cruise_leg_fuel(0.5) == base
|
||||
+16
-9
@@ -57,23 +57,30 @@ def test_switched_off_recipes_produce_nothing_but_keep_workforce(sim):
|
||||
assert r["flows"]["AL"]["inp"] == pytest.approx(42.78, abs=0.01)
|
||||
|
||||
|
||||
def test_cost_degradation_area_match_screenshots():
|
||||
"""Screenshots: full plan area 237, degradation 2,141.74, plan cost 737,076; HWP-only area 102, degradation 373.60, cost 418,812.
|
||||
Prices drift, so 3% tolerance on money values; area is exact."""
|
||||
from puga import market
|
||||
def test_area_matches_screenshots():
|
||||
"""Screenshots (2026-09-18): full plan area 237, HWP-only area 102 - exact, no price dependency.
|
||||
Degradation/plan_cost were checked against the same screenshots (2,141.74/737,076 and
|
||||
373.60/418,812) at the time and matched within rounding; not asserted here with those fixed
|
||||
money values since they're priced in live material costs that drift with the market - a fixed
|
||||
expected money value from one point in time isn't a meaningful regression check against an
|
||||
input that never stops moving (a fresh screenshot would be, this isn't that). The formula
|
||||
relationship itself (not tied to any particular price) is asserted instead, below."""
|
||||
try:
|
||||
recipes, blds = pp.recipes(), pp.buildings()
|
||||
planet = pp._g("/data/planet/ZV-759c/", 3600)
|
||||
snap = market.snapshot()
|
||||
except Exception as e:
|
||||
pytest.skip(f"offline: {e}")
|
||||
price = lambda t, side='both': market.uni30(snap, t)
|
||||
for fname, area, degr, cost in (("base_plus_hwp.yaml", 237, 2141.74, 737076.53), ("hwp_only.yaml", 102, 373.60, 418811.91)):
|
||||
for fname, area in (("base_plus_hwp.yaml", 237), ("hwp_only.yaml", 102)):
|
||||
plan = plan_push.build_payload(yaml.safe_load((ROOT / "plans" / "examples" / fname).read_text()), recipes, {b["building_ticker"] for b in blds})
|
||||
plan["plan_corphq"] = False
|
||||
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price)
|
||||
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], lambda t, side='both': 100.0)
|
||||
assert r["area"] == area
|
||||
assert r["degradation"] == pytest.approx(degr, rel=0.03) and r["plan_cost"] == pytest.approx(cost, rel=0.03)
|
||||
# Structural, price-independent regression check (puga/simulate.py): degradation is
|
||||
# production-building cost only (infra/CM excluded) divided by 180 days; plan cost is
|
||||
# production + infrastructure + one core module kit. Holds at any price, including this
|
||||
# constant-100 lambda - catches a formula regression without depending on live prices.
|
||||
assert r["degradation"] == pytest.approx(r["prod_cost"] / 180)
|
||||
assert r["plan_cost"] == pytest.approx(r["prod_cost"] + r["infra_cost"] + r["cm_cost"])
|
||||
|
||||
|
||||
def test_hq_multiplies_every_building_by_1_1(sim):
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "tools"))
|
||||
import whatif
|
||||
|
||||
|
||||
def test_apply_add_reuses_existing_recipe():
|
||||
spec = {"buildings": [{"building": "POL", "amount": 1, "recipes": ["EPO,PG=>DEC"]}]}
|
||||
whatif.apply_add(spec, "POL:1")
|
||||
assert spec["buildings"] == [{"building": "POL", "amount": 2, "recipes": ["EPO,PG=>DEC"]}]
|
||||
|
||||
|
||||
def test_apply_add_new_building_needs_explicit_recipe():
|
||||
spec = {"buildings": []}
|
||||
import pytest
|
||||
with pytest.raises(SystemExit):
|
||||
whatif.apply_add(spec, "CHP:1")
|
||||
|
||||
|
||||
def test_apply_add_appends_new_building_with_recipe():
|
||||
spec = {"buildings": []}
|
||||
whatif.apply_add(spec, "CHP:1:MG,S,CU=>IND")
|
||||
assert spec["buildings"] == [{"building": "CHP", "amount": 1, "recipes": ["MG,S,CU=>IND"]}]
|
||||
|
||||
|
||||
def test_apply_remove_drops_building_entirely_by_default():
|
||||
spec = {"buildings": [{"building": "HWP", "amount": 1, "recipes": ["AL,STL,HE=>BHP"]}]}
|
||||
whatif.apply_remove(spec, "HWP")
|
||||
assert spec["buildings"] == []
|
||||
|
||||
|
||||
def test_apply_remove_partial_amount():
|
||||
spec = {"buildings": [{"building": "CHP", "amount": 3, "recipes": ["MG,S,CU=>IND"]}]}
|
||||
whatif.apply_remove(spec, "CHP:1")
|
||||
assert spec["buildings"] == [{"building": "CHP", "amount": 2, "recipes": ["MG,S,CU=>IND"]}]
|
||||
|
||||
|
||||
def test_apply_infra_adds_delta():
|
||||
spec = {"infrastructure": {"HB1": 4}}
|
||||
whatif.apply_infra(spec, "HB1:+1,HB2:+2")
|
||||
assert spec["infrastructure"] == {"HB1": 5, "HB2": 2}
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Emit a Refined PrUn XIT ACT action-package JSON for a buy list - paste into the extension's
|
||||
"Import Action Package" (XIT ACT -> IMPORT) to pre-fill the CXPO buy tile for each material; you
|
||||
still click the real buy button yourself. See puga/actpkg.py for the schema/gotcha notes.
|
||||
|
||||
puga actpkg "Nike PP1 BDE buildout" BDE:3 BBH:3 BSE:4 MCG:76 PE:750
|
||||
puga actpkg "Nike PP1 BDE buildout" BDE:3 BBH:3 BSE:4 MCG:76 PE:750 --cx AI1 -o nike_pp1.json
|
||||
"""
|
||||
import argparse, json, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, actpkg
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("name", help="package name (letters/digits/spaces only - punctuation is stripped)")
|
||||
ap.add_argument("materials", nargs="+", help="TICKER:QTY pairs, e.g. BDE:3 MCG:76")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
ap.add_argument("-o", "--out", help="write to this file instead of stdout")
|
||||
a = ap.parse_args()
|
||||
|
||||
mats = {}
|
||||
for m in a.materials:
|
||||
tk, _, qty = m.partition(":")
|
||||
if not qty:
|
||||
sys.exit(f"bad material spec {m!r}, expected TICKER:QTY")
|
||||
mats[tk] = float(qty)
|
||||
|
||||
pkg = actpkg.build_package(a.name, mats, a.cx)
|
||||
text = json.dumps(pkg, indent=2)
|
||||
if a.out:
|
||||
Path(a.out).write_text(text)
|
||||
print(f"wrote {a.out}")
|
||||
else:
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full construction material list for one building, optionally on a specific planet (adds its
|
||||
environment-extra materials via puga.planet.environment_extras() - SEA/HSE/MGC/BL/INS/TSH).
|
||||
|
||||
puga buildcost HB1
|
||||
puga buildcost EXT --planet ZV-194a
|
||||
puga buildcost PP1 --planet ZV-194a --amount 1
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio, market, prunplanner as pp, planet as planet_mod
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("building", help="building ticker, e.g. HB1, EXT, PP1")
|
||||
ap.add_argument("--planet", help="planet natural id - adds its environment-extra materials")
|
||||
ap.add_argument("--amount", type=int, default=1)
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
blds = {b["Ticker"]: b for b in fio.buildings()}
|
||||
b = blds.get(a.building.upper())
|
||||
if not b:
|
||||
sys.exit(f"unknown building {a.building!r}")
|
||||
|
||||
need: dict[str, float] = {c["CommodityTicker"]: c["Amount"] for c in b["BuildingCosts"]}
|
||||
need["MCG"] = need.get("MCG", 0) + 4 * b["AreaCost"]
|
||||
|
||||
if a.planet:
|
||||
planet = pp._g(f"/data/planet/{a.planet}/", 3600)
|
||||
for tk, qty in planet_mod.environment_extras(planet, b["AreaCost"]).items():
|
||||
need[tk] = need.get(tk, 0) + qty
|
||||
print(f"# {b['Ticker']} on {planet['planet_name']} ({a.planet}): pressure {planet['pressure']:.3f}, "
|
||||
f"gravity {planet['gravity']:.2f}, temp {planet['temperature']:.1f}C")
|
||||
|
||||
total = 0.0
|
||||
for tk, qty in sorted(need.items()):
|
||||
qty *= a.amount
|
||||
cost = market.walk(tk, a.cx, qty, "buy")
|
||||
px = cost["total"] if not cost["short"] else None
|
||||
total += px or 0
|
||||
print(f"{tk:4} {qty:8.1f} {px:>10,.0f} AIC" if px is not None else f"{tk:4} {qty:8.1f} (short on {a.cx})")
|
||||
print(f"total: {total:,.0f} AIC" if total else "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+9
-4
@@ -20,14 +20,16 @@ from pathlib import Path
|
||||
import yaml
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio, market, prunplanner as pp
|
||||
from puga import planet as planet_mod
|
||||
from puga.simulate import simulate
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import plan_push
|
||||
|
||||
|
||||
def construction_items(plan: dict, buildings: list, built: dict) -> dict:
|
||||
"""Materials needed for the plan's buildings/infra beyond what `built` (ticker -> count) already has."""
|
||||
def construction_items(plan: dict, buildings: list, built: dict, planet: dict | None = None) -> dict:
|
||||
"""Materials needed for the plan's buildings/infra beyond what `built` (ticker -> count) already has.
|
||||
planet: optional, adds environment-extra materials (SEA/HSE/MGC/BL/INS/TSH) via planet.environment_extras()."""
|
||||
bl = {b["building_ticker"]: b for b in buildings}
|
||||
d = plan["plan_data"]
|
||||
need: dict[str, float] = {}
|
||||
@@ -39,6 +41,9 @@ def construction_items(plan: dict, buildings: list, built: dict) -> dict:
|
||||
for c in info["costs"]:
|
||||
need[c["material_ticker"]] = need.get(c["material_ticker"], 0) + c["material_amount"] * gap
|
||||
need["MCG"] = need.get("MCG", 0) + 4 * info["area_cost"] * gap
|
||||
if planet is not None:
|
||||
for etk, qty in planet_mod.environment_extras(planet, info["area_cost"]).items():
|
||||
need[etk] = need.get(etk, 0) + qty * gap
|
||||
return need
|
||||
|
||||
|
||||
@@ -101,9 +106,9 @@ def main():
|
||||
perm = (st.get("permits", {}).get("used", 1), st.get("permits", {}).get("total", 2))
|
||||
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
|
||||
price_ask = lambda t, side="buy": (lambda q: q.ask if q else None)(market.snapshot().get((t, a.cx)))
|
||||
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price_ask, faction, perm)
|
||||
r = simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price_ask, faction, perm, planet=planet)
|
||||
|
||||
con = net_of_on_hand(construction_items(plan, blds, built), on_hand)
|
||||
con = net_of_on_hand(construction_items(plan, blds, built, planet), on_hand)
|
||||
stk = net_of_on_hand(stock_items(r["flows"], a.days), on_hand)
|
||||
con_rows, con_total, con_w, con_v = price(con, a.cx)
|
||||
stk_rows, stk_total, stk_w, stk_v = price(stk, a.cx)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Where to post a BUY order (a resting bid) when there's a hard DEADLINE - not "is patience
|
||||
worth it forever" (that's tools/sell.py's problem, where foregone margin is the only cost of
|
||||
waiting). Here, a bid that never fills means a production-line STOCKOUT (check tools/runway.py
|
||||
for your real deadline), so the right question is: what's the cheapest price that's still likely
|
||||
to fill BY that deadline, with paying the ask as the fallback if it doesn't?
|
||||
|
||||
puga buyat PG 150 --deadline 3 # 3 days of runway left on PG
|
||||
|
||||
For each candidate price between the current ask and best bid, uses puga.history.empirical_touch
|
||||
with a fixed `horizon` (the deadline) to get the REAL empirical P(price actually falls to this
|
||||
level within that many days) - not "ever", which is the wrong question under a deadline. Expected
|
||||
cost = price * P(fill by deadline) + current_ask * (1 - P(fill by deadline)) - the fallback term
|
||||
assumes paying the ask at the deadline if the bid never filled; the ask itself could move by then,
|
||||
so this is an approximation, not a guarantee. Recommends the price minimizing expected cost, but
|
||||
shows the whole curve - pick a more conservative (higher-P) price than the cost-minimizer if a
|
||||
stockout would be expensive in ways this doesn't price in (e.g. the whole base's workforce idling).
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio, market
|
||||
from puga.history import daily_prices, full_series, empirical_touch
|
||||
import math
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("ticker")
|
||||
ap.add_argument("qty", type=float)
|
||||
ap.add_argument("--deadline", type=float, required=True, help="days until this input runs out (tools/runway.py) - the hard constraint, not a soft discount rate")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
t = a.ticker.upper()
|
||||
ob = fio.order_book(t, a.cx)
|
||||
bids = sorted(((o["ItemCost"], o["ItemCount"] or 0) for o in ob["BuyingOrders"] if o.get("ItemCost")), reverse=True)
|
||||
best_bid = bids[0][0] if bids else None
|
||||
best_ask = ob.get("Ask")
|
||||
|
||||
hit = market.walk(t, a.cx, a.qty, "buy")
|
||||
ask_cost = hit["total"] if not hit["short"] else None
|
||||
print(f"{t}.{a.cx} best bid {best_bid} ask {best_ask} vwap7 {ob.get('PriceAverage')} deadline {a.deadline:g}d")
|
||||
if ask_cost is not None:
|
||||
print(f"instant (pay the asks now): {ask_cost:,.0f} (avg {hit['avg']:.0f}) - the fallback if nothing fills in time")
|
||||
else:
|
||||
print("WARNING: book too thin to fill this quantity at any price right now - the 'pay the ask' fallback isn't actually available at this size")
|
||||
|
||||
dp = daily_prices(t, a.cx)
|
||||
s0 = sorted(dp.items())[-1][1][0] if dp else (best_bid or ob.get("Bid") or 0)
|
||||
series = full_series(t, a.cx)
|
||||
if len(series) < 10:
|
||||
print("\nnot enough price history to estimate fill probability - fall back to paying the ask")
|
||||
return
|
||||
|
||||
candidates = sorted({p for p, _ in bids if p <= s0} | {round(s0 * m, 0) for m in (0.99, 0.97, 0.95, 0.9, 0.85, 0.8, 0.7, 0.6)})
|
||||
candidates = [p for p in candidates if p > 0 and (best_bid is None or p >= best_bid * 0.5)]
|
||||
|
||||
print(f"\nlast traded {s0:.0f}, {len(series)}d history - P(fill) is specifically BY the {a.deadline:g}d deadline, not ever:")
|
||||
print(f" {'price':>10} {'P(fill by deadline)':>20} {'cost if filled':>15} {'expected cost':>14}")
|
||||
rows = []
|
||||
for p in candidates:
|
||||
y = math.log(p / s0) if s0 else 0.0
|
||||
if y >= 0:
|
||||
p_fill = 1.0
|
||||
else:
|
||||
p_fill = empirical_touch(series, y, 0.0, horizon=a.deadline)["touched_frac"]
|
||||
cost_if_filled = p * a.qty
|
||||
fallback = ask_cost if ask_cost is not None else p * a.qty * 1.5 # crude: no real fallback price known
|
||||
expected = p_fill * cost_if_filled + (1 - p_fill) * fallback
|
||||
rows.append((p, p_fill, cost_if_filled, expected))
|
||||
|
||||
best = min(rows, key=lambda r: r[3]) if rows else None
|
||||
for p, p_fill, cost_if_filled, expected in rows:
|
||||
flag = " <- min expected cost" if (p, p_fill, cost_if_filled, expected) == best else ""
|
||||
print(f" {p:>10.0f} {100*p_fill:>19.0f}% {cost_if_filled:>15,.0f} {expected:>14,.0f}{flag}")
|
||||
|
||||
print("\nNOTE: 'expected cost' assumes paying today's ask as the fallback if the bid never fills by the "
|
||||
"deadline - the real ask could move by then, this is an estimate. Pick a price with HIGHER P(fill) "
|
||||
"than the cost-minimizer if a stockout costs more than this model sees (idle workforce, missed orders).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -3,6 +3,7 @@
|
||||
Cost to make = inputs at min(buy, make) per output unit; wages/capex excluded unless --wages.
|
||||
tools/chain.py DEC # AI1
|
||||
tools/chain.py BHP --depth 3 --qty 13
|
||||
tools/chain.py BOR --consumers # what recipes EAT this ticker as an input, with the output's market depth
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
@@ -18,6 +19,7 @@ def main():
|
||||
ap.add_argument("--qty", type=float, default=1.0, help="units/day you would make (sourcing check)")
|
||||
ap.add_argument("--wages", action="store_true", help="add wage cost per output unit (both luxuries at ask)")
|
||||
ap.add_argument("--cogc")
|
||||
ap.add_argument("--consumers", action="store_true", help="list recipes that consume this ticker as an input, with the output's market depth, instead of the make-vs-buy tree")
|
||||
a = ap.parse_args()
|
||||
|
||||
snap = market.snapshot()
|
||||
@@ -28,6 +30,24 @@ def main():
|
||||
for o in r["Outputs"]:
|
||||
by_out.setdefault(o["Ticker"], []).append(r)
|
||||
|
||||
if a.consumers:
|
||||
tk = a.ticker.upper()
|
||||
found = False
|
||||
for r in fio.recipes():
|
||||
if not any(i["Ticker"] == tk for i in r["Inputs"]):
|
||||
continue
|
||||
found = True
|
||||
ins = " ".join(f"{i['Amount']}{i['Ticker']}" for i in r["Inputs"])
|
||||
outs = " ".join(f"{o['Amount']}{o['Ticker']}" for o in r["Outputs"])
|
||||
print(f"{r['BuildingTicker']:4} {ins} -> {outs}")
|
||||
for o in r["Outputs"]:
|
||||
q = Q(o["Ticker"])
|
||||
mk = f"ask {q.ask:.0f} bid {q.bid:.0f} sup {q.supply:.0f} dem {q.demand:.0f} flow {sat.tref(q.traded7, q.traded30):.1f}/d" if q and q.ask and q.bid else "no market"
|
||||
print(f" {o['Ticker']:5} {mk}")
|
||||
if not found:
|
||||
print(f"nothing consumes {tk} as an input")
|
||||
return
|
||||
|
||||
def wage_per_day(b):
|
||||
tot = 0.0
|
||||
for t in econ.TIERS:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""List this account's OPEN CONTD contract offers (the NPC logistics-officer pool shown in APEX's
|
||||
CONTD panel - usually 3 at a time, only one acceptable) with payment, materials received/supplied,
|
||||
freight legs the player must personally fly, and net (see puga/contd.py's docstring for exactly
|
||||
which condition types are costs vs rewards vs the player's own job). Judging the actual best deal
|
||||
is NOT this tool's job for anything it flags as unpriced (EXPLORATION, REPAIR_SHIP, etc.) or for
|
||||
a freight leg's real fuel cost (flagged with weight/volume, price via puga.shipping yourself) - it
|
||||
reports the breakdown, the caller reasons about context.
|
||||
|
||||
puga contd
|
||||
puga contd --cx AI1
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, contd
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
contracts = contd.open_contracts()
|
||||
if not contracts:
|
||||
print("no OPEN contract offers right now")
|
||||
return
|
||||
|
||||
for c in contracts:
|
||||
r = contd.evaluate(c, a.cx)
|
||||
print(f"\n{r['id']} partner={r['partner']} deadline {r['deadline_days']:.1f}d"
|
||||
+ (" +reputation" if r["reputation"] else ""))
|
||||
print(f" payment: {r['payment']:,.2f} AIC")
|
||||
for rew in r["rewards"]:
|
||||
print(f" receives: {rew['ticker']} x{rew['qty']:g} @ {rew['address']} market value {rew['value']:,.0f}")
|
||||
for cost in r["costs"]:
|
||||
flag = " SHORT: book can't fill this qty" if cost["short"] else ""
|
||||
print(f" must supply: {cost['ticker']} x{cost['qty']:g} @ {cost['address']} buy-fresh cost {cost['value']:,.0f}{flag}")
|
||||
for ltype, addr, wgt, vol in r["freight_legs"]:
|
||||
print(f" YOUR FREIGHT LEG: {ltype} @ {addr} {wgt:g}t / {vol:g}m3 - price via puga.shipping, not included in net")
|
||||
for ftype, addr in r["flags"]:
|
||||
print(f" UNPRICED CONDITION: {ftype}" + (f" @ {addr}" if addr else "") + " - context-dependent, judge separately")
|
||||
print(f" reward value: {r['reward_value']:,.0f} cost value: {r['cost_value']:,.0f} -> net (payment + reward - cost): {r['net']:,.0f}")
|
||||
|
||||
priceable = [c for c in contracts if not contd.evaluate(c, a.cx)["flags"]]
|
||||
if len(priceable) == len(contracts):
|
||||
best = max(contracts, key=lambda c: contd.evaluate(c, a.cx)["net"])
|
||||
print(f"\nby payment+reward net alone, best priced: {best['ContractLocalId']}"
|
||||
" - unpriced/flagged conditions (freight legs, exploration, etc.) still need judgment")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+2
-9
@@ -4,18 +4,11 @@ Daily price = value traded / units traded (VWAP), forward-filled over days witho
|
||||
tools/history.py KV # AI1, the recipe producing KV
|
||||
tools/history.py BHP --cx AI1 --eff 1.18 --overhead 3200 --capex 94000 --months 12
|
||||
Building/day = batches/day at --eff; profit/day = batches/day * margin_per_batch - overhead (wages etc, --overhead)."""
|
||||
import argparse, datetime, statistics, sys
|
||||
import argparse, statistics, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio
|
||||
|
||||
|
||||
def daily_prices(tk, cx):
|
||||
out = {}
|
||||
for e in fio.cxpc(tk, cx):
|
||||
if e.get("Interval") == "DAY_ONE" and e.get("Traded"):
|
||||
out[datetime.datetime.fromtimestamp(e["DateEpochMs"] / 1000, datetime.timezone.utc).date()] = (e["Volume"] / e["Traded"], e["Traded"])
|
||||
return out
|
||||
from puga.history import daily_prices
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scan live Local Market hauling ads (real player-posted freight jobs, FIO
|
||||
/localmarket/shipping/*) and rank by margin after real fuel cost (puga.shipping). One-way cost
|
||||
only (margin assumes you pick up the next job near the destination, not an empty flight home).
|
||||
|
||||
tools/lmscan.py ANT # ads picking up at Antares Station
|
||||
tools/lmscan.py ANT --direction destination # ads dropping off at Antares Station
|
||||
tools/lmscan.py ZV-759c --min-margin 0 # only profitable ones, from Deimos
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, contracts, market
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("planet", help="station/planet natural id to scan ads at, e.g. ANT, ZV-759c")
|
||||
ap.add_argument("--direction", choices=["source", "destination"], default="source",
|
||||
help="source = ads picking up here (default); destination = ads dropping off here")
|
||||
ap.add_argument("--v0", type=float, default=1.0)
|
||||
ap.add_argument("--v1", type=float, default=1.0)
|
||||
ap.add_argument("--min-margin", type=float, help="only show ads with at least this AIC margin")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
snap = market.snapshot()
|
||||
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||
|
||||
rows = contracts.scan(a.planet, a.direction, sf_px, ff_px, a.v0, a.v1)
|
||||
priced = [r for r in rows if r["margin_aic"] is not None]
|
||||
unpriceable = [r for r in rows if r["margin_aic"] is None]
|
||||
priced.sort(key=lambda r: r["margin_aic"], reverse=True)
|
||||
if a.min_margin is not None:
|
||||
priced = [r for r in priced if r["margin_aic"] >= a.min_margin]
|
||||
|
||||
print(f"{len(rows)} ads ({a.direction} = {a.planet}), {len(priced)} priceable at v0={a.v0} v1={a.v1}\n")
|
||||
print(f"{'route':16} {'jump':4} {'t':>6} {'m3':>6} {'payout':>9} {'fuel/fee':>9} {'margin':>9} {'margin/day':>11}")
|
||||
for r in priced:
|
||||
print(f"{r['OriginPlanetNaturalId']}->{r['DestinationPlanetNaturalId']:11} {r['JumpDistance']:4} "
|
||||
f"{r['CargoWeight']:6.0f} {r['CargoVolume']:6.0f} {r['PayoutPrice']:9,.0f} "
|
||||
f"{r['cost']['aic']:9,.0f} {r['margin_aic']:9,.0f} {r['margin_per_day']:11,.0f}")
|
||||
|
||||
if unpriceable:
|
||||
print(f"\n{len(unpriceable)} ad(s) not priced (over-capacity cargo, non-AIC payout, or an unmeasured gateway route):")
|
||||
for r in unpriceable:
|
||||
reason = "cargo exceeds 500t/500m3 (needs multiple trips, not modelled)" if r["over_capacity"] else \
|
||||
("non-AIC payout" if r["PayoutCurrency"] != "AIC" else "no known route (unmeasured gateway?)")
|
||||
print(f" {r['OriginPlanetNaturalId']}->{r['DestinationPlanetNaturalId']} {r['PayoutPrice']:,.0f} {r['PayoutCurrency']} [{reason}]")
|
||||
|
||||
print("\nCAVEATS: one-way cost only, assumes a return cargo lined up at the destination (no empty flight home "
|
||||
"priced in) - see puga/contracts.py. margin/day divides by the ad's DeliveryTime DEADLINE, not real "
|
||||
"transit time (we don't model trip duration, only fuel) - treat it as a floor, not the real rate. "
|
||||
"Fuel model itself is scoped to this account's one hull/reactor; see puga/shipping.py for open gaps.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+29
-9
@@ -9,7 +9,7 @@ import argparse, sys
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import ROOT, config, market, prunplanner as pp
|
||||
from puga import ROOT, config, market, prunplanner as pp, shipping
|
||||
from puga.network import BaseNode, Transfer, combine
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
@@ -56,18 +56,35 @@ def main():
|
||||
built["CM"] = 1
|
||||
bases[key] = BaseNode(key, plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built)
|
||||
|
||||
transfers = [Transfer(**t) for t in net.get("transfers", [])]
|
||||
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||
transfers, cost_notes = [], []
|
||||
for raw in net.get("transfers", []):
|
||||
t = dict(raw)
|
||||
if "trip_cost" not in t and t["src"] in bases and t["dst"] in bases:
|
||||
real = shipping.round_trip_cost(bases[t["src"]].plan["planet_natural_id"], bases[t["dst"]].plan["planet_natural_id"],
|
||||
sf_px, ff_px)
|
||||
if real is not None:
|
||||
t["trip_cost"] = real
|
||||
cost_notes.append(f" {t['material']} {t['src']}->{t['dst']}: real round-trip cost {real:,.0f} AIC (puga.shipping)")
|
||||
else:
|
||||
cost_notes.append(f" {t['material']} {t['src']}->{t['dst']}: no direct-jump route (gateway?) - using placeholder {Transfer.__dataclass_fields__['trip_cost'].default:,.0f} AIC, check SFC in-game")
|
||||
transfers.append(Transfer(**t))
|
||||
r = combine(bases, transfers)
|
||||
|
||||
print(f"{net.get('name', a.spec)} ({a.basis} prices)\n")
|
||||
for key, res in r["results"].items():
|
||||
line = f"[{key}] area {res['area']:.0f} profit/day {res['profit']:,.0f} new capex {res['new_capex']:,.0f}"
|
||||
if res["new_capex"] > 0:
|
||||
line += f" ({100*res['profit']/res['new_capex']:.1f}%/day)"
|
||||
line += f" (payback {res['new_capex']/res['profit']:.1f} d)"
|
||||
print(line)
|
||||
for b in res["buildings"]:
|
||||
print(f" {b['amount']:2} x {b['building']:4} eff {b['efficiency']*100:6.1f}%")
|
||||
|
||||
if cost_notes:
|
||||
print("\nFREIGHT COST")
|
||||
print("\n".join(cost_notes))
|
||||
|
||||
print("\nTRANSFERS")
|
||||
for t in r["ledger"]:
|
||||
note = f"SHORTFALL {t['shortfall']:.1f}/d bought at market by {t['dst']}" if t["shortfall"] > 0.01 else \
|
||||
@@ -77,13 +94,16 @@ def main():
|
||||
|
||||
total_new_capex = sum(res["new_capex"] for res in r["results"].values())
|
||||
print(f"\nCOMBINED profit/day {r['total_profit']:,.0f} new capex {total_new_capex:,.0f}"
|
||||
+ (f" {100*r['total_profit']/total_new_capex:.1f}%/day" if total_new_capex > 0 else ""))
|
||||
+ (f" payback {total_new_capex/r['total_profit']:.1f} d" if total_new_capex > 0 else ""))
|
||||
print("CAUTION: a base's 'profit/day' here is its WHOLE plan (existing buildings included), not just the new "
|
||||
"addition, so its %/day overstates the marginal return where new_capex is small relative to an existing "
|
||||
"base. For the true marginal ROI, also simulate the base's plan WITHOUT the new building/transfer and "
|
||||
"diff the profit; see docs/library.md.")
|
||||
print("NOTE: trip_cost/cargo are placeholders (default 9250 AIC, 500 t/m3, same as the AI1 route) until a real "
|
||||
"inter-base fuel model exists (docs/roadmap.md tools/route.py) -- check SFC in-game for the real cost.")
|
||||
"addition, so its payback here understates the marginal payback where new_capex is small relative to an "
|
||||
"existing base. For the true marginal payback, also simulate the base's plan WITHOUT the new "
|
||||
"building/transfer and diff the profit; see docs/library.md.")
|
||||
print("NOTE: trip_cost is computed from the real fuel model (puga.shipping, max sliders) for direct-jump routes "
|
||||
"between two bases in this chain (see FREIGHT COST above); a gateway route, or a transfer with an "
|
||||
"explicit trip_cost in the YAML, uses that value instead (9250 AIC if neither applies). cargo defaults "
|
||||
"to 500 t/m3 (the account's ship hold size, confirmed via FIO) - override per-transfer if a different "
|
||||
"ship is used.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Where to park idle cash as a buy-low/sell-high position while ships are busy or cash has no
|
||||
better immediate use. Scans every ticker for a big spread AND real trading liquidity, scored by
|
||||
an EMPIRICAL round-trip estimate from the ticker's own price history (no random-walk assumption -
|
||||
see puga/parkcash.py's docstring for the method and open gaps).
|
||||
|
||||
tools/parkcash.py # AI1, default filters, top 25 by pessimistic daily %
|
||||
tools/parkcash.py --min-trade-days 15 # require real liquidity (half the window trading)
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, parkcash
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
ap.add_argument("--min-spread", type=float, default=20.0, help="minimum bid/ask spread %% to consider")
|
||||
ap.add_argument("--min-trade-days", type=int, default=10, help="minimum trading days out of the window - filters stale-quote traps")
|
||||
ap.add_argument("--days", type=int, default=30, help="calendar-day window for liquidity stats (the empirical round-trip model itself uses full history)")
|
||||
ap.add_argument("--rate", type=float, default=0.0, help="opportunity cost of waiting on this cash - default 0.0 matches this tool's premise (idle cash, no better use right now); pass your realized capital growth rate (e.g. 0.05, see tools/sell.py --rate) if this money IS earmarked for something and waiting has a real cost")
|
||||
ap.add_argument("--max-wait", type=float, help="drop anything with a combined round-trip median wait above this many days")
|
||||
ap.add_argument("--top", type=int, default=25)
|
||||
a = ap.parse_args()
|
||||
|
||||
rows = parkcash.scan(a.cx, a.min_spread, a.days, a.rate)
|
||||
rows = [r for r in rows if r["trade_days"] >= a.min_trade_days]
|
||||
if a.max_wait is not None:
|
||||
rows = [r for r in rows if r["wait_days"] <= a.max_wait]
|
||||
rows.sort(key=lambda r: -r["daily_pct"])
|
||||
|
||||
print(f"# {a.cx} spread>={a.min_spread:.0f}% trade_days>={a.min_trade_days}/{a.days}d rate={100*a.rate:.1f}%/day "
|
||||
f"(round trip = empirical buy-dip + sell-recovery from real history, see puga/parkcash.py)")
|
||||
print(f"{'daily%':>7} {'disc%':>6} {'margin%':>8} {'spread%':>8} {'days':>5} {'buy%':>5} {'sell%':>5} {'wait(d)':>7} {'bid':>9} {'ask':>9} tk")
|
||||
for r in rows[:a.top]:
|
||||
print(f"{r['daily_pct']:7.1f} {r['discounted_pct']:6.1f} {r['margin_pct']:8.1f} {r['spread_pct']:8.0f} {r['trade_days']:5d} "
|
||||
f"{100*r['buy_touch']:5.0f} {100*r['sell_touch']:5.0f} {r['wait_days']:7.1f} {r['bid']:9.0f} {r['ask']:9.0f} {r['tk']}")
|
||||
|
||||
print("\nNOTE: disc% = margin% x real odds both legs ever happen (at --rate; a big gap from daily% "
|
||||
"means the speed number is flattering a trade that may never clear). buy%/sell% are each leg's "
|
||||
"real historical frequency. Not a compoundable rate - see docs/decisions.md. See puga/parkcash.py's "
|
||||
"OPEN GAPS (no fee data; legs treated as independent).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rank planets for a resource, with founding cost (environment extras straight from FIO's
|
||||
BuildRequirements - real game data, not guessed thresholds) and optional jump distance from
|
||||
a base you already have.
|
||||
|
||||
tools/planet.py FEO --top 10
|
||||
tools/planet.py LST --min-factor 0.5 --from ZV-759c --top 5
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, market, planet, route
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("resource", help="raw resource ticker, e.g. LST, FEO, SEA")
|
||||
ap.add_argument("--min-factor", type=float, default=0.0)
|
||||
ap.add_argument("--top", type=int, default=10)
|
||||
ap.add_argument("--from", dest="from_", help="planet/system to measure jump distance from (e.g. an existing base)")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
rows = planet.candidates(a.resource, a.min_factor)
|
||||
if not rows:
|
||||
print(f"no planets found with {a.resource.upper()} (factor >= {a.min_factor})")
|
||||
return
|
||||
rows = rows[:a.top]
|
||||
|
||||
src = route.resolve_system(a.from_) if a.from_ else None
|
||||
graph = route.load_graph() if src else None
|
||||
|
||||
for p in rows:
|
||||
env_cost = 0.0
|
||||
env_items = []
|
||||
for br in p["build_requirements"]:
|
||||
w = market.walk(br["MaterialTicker"], a.cx, br["MaterialAmount"], "buy")
|
||||
env_cost += w["total"]
|
||||
env_items.append(f"{br['MaterialAmount']}{br['MaterialTicker']}")
|
||||
dist = ""
|
||||
if src:
|
||||
r = route.shortest_path(src, p["system_id"], graph=graph) if p["system_id"] != src else {"jumps": 0, "distance_ly": 0.0}
|
||||
dist = f" {r['jumps']} jumps ({r['distance_ly']:.0f} ly)" if r else " unreachable"
|
||||
print(f"{p['natural_id']:8} {p['name']:16} factor {p['factor']:.3f} T {p['temperature']:6.1f}C P {p['pressure']:.2f}bar "
|
||||
f"G {p['gravity']:.2f} fert {p['fertility']:5.2f} faction {p['faction'] or '-':4} env-cost {env_cost:8,.0f} AIC ({', '.join(env_items) or 'none'}){dist}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Jump-distance route between two planets/systems, from FIO's system graph (not PRUNplanner,
|
||||
which doesn't model travel). Straight-line ly is the Dijkstra weight (scales with FTL fuel/time);
|
||||
jump count shown alongside.
|
||||
|
||||
tools/route.py ZV-759c ZV-194a # Deimos -> Nike
|
||||
tools/route.py Deimos "Ironforge" # names also work
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import route
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
sys.exit("usage: tools/route.py <from planet/system> <to planet/system>")
|
||||
a, b = sys.argv[1], sys.argv[2]
|
||||
src = route.resolve_system(a)
|
||||
dst = route.resolve_system(b)
|
||||
if src == dst:
|
||||
print(f"{a} and {b} are in the same system - 0 jumps")
|
||||
return
|
||||
r = route.shortest_path(src, dst)
|
||||
if r is None:
|
||||
print(f"no connected route found between {a} and {b}")
|
||||
return
|
||||
print(f"{a} -> {b}: {r['jumps']} jumps, {r['distance_ly']:.1f} ly (straight-line sum along the jump path)")
|
||||
print("path: " + " -> ".join(r["path"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+56
-25
@@ -1,9 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Depth-aware single-step recipe scan at one exchange (saturation model v1, see docs/saturation-design.md).
|
||||
For each recipe: buildings the market can absorb (N*), and ROI/day at N=1 and N* using a patient sell price
|
||||
(not top-of-book) and ask-walked inputs. Excludes thin markets by default.
|
||||
For each recipe: buildings the market can absorb (N*), and payback/yield at N=1 and N* using a patient sell
|
||||
price (not top-of-book) and ask-walked inputs. Excludes thin markets by default. yld/d is profit/day over
|
||||
capex as a %, NOT a compoundable rate - it's 1/payback; see docs/decisions.md's "Drop ROI/day %" entry.
|
||||
|
||||
tools/scan.py # AI1, all tiers, top 30 by ROI at N*
|
||||
tools/scan.py # AI1, all tiers, top 30 by yield at N*
|
||||
tools/scan.py --cogc METALLURGY --tier S # e.g. a Metallurgy-COGC base, up to settlers
|
||||
tools/scan.py --sort total --min-n 3 # rank by absorbable profit/day
|
||||
"""
|
||||
@@ -12,6 +13,7 @@ from pathlib import Path
|
||||
import yaml
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import ROOT, config, econ, fio, market, prunplanner as pp, saturation as sat
|
||||
from puga import planet as pl
|
||||
|
||||
TIER_CODE = {"pioneer": "P", "settler": "S", "technician": "T", "engineer": "E", "scientist": "Sc"}
|
||||
TIER_RANK = {"P": 0, "S": 1, "T": 2, "E": 3, "Sc": 4}
|
||||
@@ -32,10 +34,12 @@ def main():
|
||||
ap.add_argument("--cargo", type=float, default=500.0, help="t and m3 per trip (starter ship)")
|
||||
ap.add_argument("--no-hq", action="store_true", help="ignore HQ from state (new base without the HQ)")
|
||||
ap.add_argument("--permits-used", type=int, help="override permits used (affects faction bonus multiplier), e.g. 2 for a second base")
|
||||
ap.add_argument("--deprec", type=float, default=0, help="demolish-later mode: building value decays linearly to 0 over this many days (game: ~60); subtracts capex/deprec per day")
|
||||
ap.add_argument("--deprec", type=float, default=0, help="demolish-later mode: assumed holding days before demolition; amortizes the UNRECLAIMED portion of capex (capex x (1 - --reclaim-frac)) over that period, NOT full capex - real FIO reclaimables data (this account's own buildings, 2026-10-10) showed ~50-86%% returned even at near-100%% condition, contradicting a 100%%->0 time-decay story. See docs/decisions.md.")
|
||||
ap.add_argument("--reclaim-frac", type=float, default=0.65, help="fraction of capex recovered on demolition - real observed range 50-86%% across 7 owned building types (CM a low outlier at ~7%%, excluded); single base/age, small sample, treat as a rough placeholder not a calibrated curve")
|
||||
ap.add_argument("--max-impact", type=float, default=10.0, help="max %% the realized price may degrade below vwap7/bid when walking the LIVE bid book for your planned daily output (puga.saturation.max_units_at_impact) - feeds the [exit-thin] warning flag: can you instantly DUMP a day of output into resting bids if you needed cash now, not whether your patient asks clear (that's the market/lim columns). See docs/decisions.md")
|
||||
ap.add_argument("--input", help="only recipes consuming this ticker as an input, e.g. --input AL for recipes built on top of your own AL chain")
|
||||
ap.add_argument("--planet", help="planet natural id: adds extraction (EXT/COL/RIG) from its resources, uses its fertility and active COGC; new base (not in state) => no HQ, permits+1")
|
||||
ap.add_argument("--own", type=int, default=1, help="how many buildings WE would run; ROI is measured at this size (default 1). --min-n is only a market-size filter")
|
||||
ap.add_argument("--own", type=int, default=1, help="how many buildings WE would run; yield/payback is measured at this size (default 1). --min-n is only a market-size filter")
|
||||
ap.add_argument("--skip", default="", help="tiers left unstaffed, e.g. technician (no housing/wages; efficiency = staffed headcount share)")
|
||||
ap.add_argument("--experts", default="", help="expert counts, e.g. METALLURGY=2 (bonus x1.0306..1.284 for 1..5)")
|
||||
ap.add_argument("--hq", action="store_true", help="corp HQ bonus x1.1")
|
||||
@@ -44,7 +48,7 @@ def main():
|
||||
ap.add_argument("--max-n", type=int, default=50, help="cap N* (capital/attention limit)")
|
||||
ap.add_argument("--budget", type=float, help="capital limit in AIC: caps N and drops recipes whose single-building capex exceeds it")
|
||||
ap.add_argument("--mcg", type=float, default=4.0, help="MCG per area (4 on normal planets)")
|
||||
ap.add_argument("--sort", default="roi", choices=["roi", "total", "roi1"])
|
||||
ap.add_argument("--sort", default="roi", choices=["roi", "total", "roi1", "area"])
|
||||
ap.add_argument("--top", type=int, default=30)
|
||||
ap.add_argument("--k", type=int, default=80, help="candidates refined with order books")
|
||||
ap.add_argument("--show-thin", action="store_true")
|
||||
@@ -80,12 +84,20 @@ def main():
|
||||
parts = [(x["Amount"], ask(x["CommodityTicker"])) for x in b["BuildingCosts"]]
|
||||
if any(p is None for _, p in parts):
|
||||
return None
|
||||
return sum(n * p for n, p in parts) + a.mcg * b["AreaCost"] * mcg
|
||||
cost = sum(n * p for n, p in parts) + a.mcg * b["AreaCost"] * mcg
|
||||
if planet is not None:
|
||||
extras = pl.environment_extras(planet, b["AreaCost"])
|
||||
prices = {etk: ask(etk) for etk in extras}
|
||||
if any(p is None for p in prices.values()):
|
||||
return None
|
||||
cost += sum(qty * prices[etk] for etk, qty in extras.items())
|
||||
return cost
|
||||
|
||||
hab_head = {}
|
||||
hab_head, hab_area = {}, {}
|
||||
for tier, hab in (("pioneer", "HB1"), ("settler", "HB2"), ("technician", "HB3"), ("engineer", "HB4"), ("scientist", "HB5")):
|
||||
c = bcost(hab)
|
||||
hab_head[tier] = None if c is None else c / econ.HAB_CAP[hab][tier]
|
||||
hab_area[tier] = econ.HAB_AREA[hab] / econ.HAB_CAP[hab][tier]
|
||||
|
||||
def wage(tier): # per worker per day, both luxuries supplied, at ask
|
||||
tot = 0.0
|
||||
@@ -155,7 +167,7 @@ def main():
|
||||
mm[t] = x.mm_buy # market maker floor: unlimited depth at mm_buy
|
||||
continue
|
||||
thin |= sat.is_thin(tr, x.demand, qo)
|
||||
n = sat.n_out(tr, 0, x.demand, qo) # stage 1: flow + demand only; queue penalty applied in stage 2 with the book
|
||||
n = sat.n_out(tr, 0, qo) # stage 1: flow only; queue penalty applied in stage 2 with the book
|
||||
if n < n_lim:
|
||||
n_lim, lim = n, t
|
||||
if n_lim == float("inf"):
|
||||
@@ -169,7 +181,8 @@ def main():
|
||||
rough = sum(io["out"][t] * price0[t] for t in io["out"]) - sum(io["in"][t] * ask(t) for t in io["in"]) - wcost
|
||||
staff = "".join(TIER_CODE[t] for t in keep) + ("" if len(keep) == len(need) else "-")
|
||||
cands.append(dict(rec=rec, b=b, io=io, eff=eff, capex=capex, wcost=wcost, n_lim=n_lim, lim=lim, thin=thin, mm=mm,
|
||||
rough_roi=100 * rough / capex, top=top, staff=staff, ins=ins, outs=outs))
|
||||
rough_roi=100 * rough / capex, top=top, staff=staff, ins=ins, outs=outs,
|
||||
hab_area_per_bld=sum(heads[t] * hab_area[t] for t in keep)))
|
||||
|
||||
cands.sort(key=lambda c: c["rough_roi"], reverse=True)
|
||||
rows = []
|
||||
@@ -183,6 +196,9 @@ def main():
|
||||
def asks_of(t):
|
||||
return sorted((o["ItemCost"], (o["ItemCount"] or 0)) for o in raw_book(t)["SellingOrders"])
|
||||
|
||||
def bids_of(t):
|
||||
return [(o["ItemCost"], (o["ItemCount"] or 0)) for o in raw_book(t)["BuyingOrders"] if o.get("ItemCost")]
|
||||
|
||||
def band_of(t):
|
||||
if t not in bandcache:
|
||||
ob = raw_book(t)
|
||||
@@ -191,21 +207,29 @@ def main():
|
||||
bandcache[t] = (lo, hi)
|
||||
return bandcache[t]
|
||||
|
||||
def demand_of(t):
|
||||
bids = ((o["ItemCost"], o["ItemCount"] or 0) for o in raw_book(t)["BuyingOrders"])
|
||||
return sat.effective_demand(bids, band_of(t))
|
||||
|
||||
for c in cands[:a.k]:
|
||||
io, mm = c["io"], c["mm"]
|
||||
# stage 2: queue penalty from competing asks near market price only, and demand within the tradeable band
|
||||
n2 = float("inf")
|
||||
# stage 2: queue penalty from competing asks near market price, flow from REAL daily-volume
|
||||
# variance (tref_precise) now that we're down to a bounded candidate set worth the extra fetch
|
||||
n2, bid_thin = float("inf"), False
|
||||
for t, qo in io["out"].items():
|
||||
if t in mm:
|
||||
continue
|
||||
x = Q(t)
|
||||
se = sat.effective_supply(asks_of(t), x.vwap7 or x.ask, band=band_of(t))
|
||||
n2 = min(n2, sat.n_out(sat.tref(x.traded7, x.traded30), se, demand_of(t), qo))
|
||||
n2 = min(n2, sat.n_out(sat.tref_precise(t, a.cx, x.traded7, x.traded30), se, qo))
|
||||
# Bid-book depth is a single LIVE SNAPSHOT (orders get added/withdrawn constantly) -
|
||||
# not reliable enough to use as a hard cap like the flow-based n_out above, which
|
||||
# aggregates real traded volume over 30 days. Surfaced as a warning flag instead, and
|
||||
# measures a DIFFERENT thing than market/lim: not "can my patient asks clear" (that's
|
||||
# p_patient()/n_out, ask-side, the real production-selling mechanism), but "could I
|
||||
# instantly dump a day of output into resting BIDS right now if I needed cash" - panic-
|
||||
# exit liquidity, not production price impact. A "yes" here doesn't guarantee it holds
|
||||
# up over time, and a "no" might just be an unlucky instant - re-check before acting.
|
||||
depth_units = sat.max_units_at_impact(bids_of(t), x.vwap7 or x.bid, a.max_impact)
|
||||
bid_thin |= depth_units < qo
|
||||
c["n_lim"] = float(a.max_n) if n2 == float("inf") else n2
|
||||
c["bid_thin"] = bid_thin
|
||||
if c["n_lim"] < a.min_n and not a.show_thin:
|
||||
continue
|
||||
|
||||
@@ -216,7 +240,7 @@ def main():
|
||||
if t in mm:
|
||||
p = mm[t]
|
||||
else:
|
||||
p = sat.p_patient(asks_of(t), sat.tref(x.traded7, x.traded30), N * qo, x.bid, x.vwap7, x.vwap30, x.ask, band_of(t)[1])
|
||||
p = sat.p_patient(asks_of(t), sat.tref_precise(t, a.cx, x.traded7, x.traded30), N * qo, x.bid, x.vwap7, x.vwap30, x.ask, band_of(t)[1])
|
||||
rev += N * qo * p
|
||||
cost = 0.0
|
||||
for t, qi in io["in"].items():
|
||||
@@ -231,7 +255,7 @@ def main():
|
||||
c["tons"] = max(wi, wo)
|
||||
frt = max(wi, wo, vi, vo) / a.cargo * a.trip_cost
|
||||
c["frt"] = frt
|
||||
dep = N * c["capex"] / a.deprec if a.deprec else 0.0 # value lost per day if demolished after holding
|
||||
dep = N * c["capex"] * (1 - a.reclaim_frac) / a.deprec if a.deprec else 0.0 # unreclaimed capex lost per day if demolished after holding
|
||||
return rev - cost - N * c["wcost"] - frt - dep
|
||||
|
||||
if a.budget and c["capex"] > a.budget:
|
||||
@@ -246,21 +270,28 @@ def main():
|
||||
netN = evaluate(n_star)
|
||||
if netN is None:
|
||||
continue
|
||||
area = n_star * ((c["b"].get("AreaCost") or 0) + c.get("hab_area_per_bld", 0.0))
|
||||
rows.append(dict(roi1=100 * net1 / c["capex"], roiN=100 * netN / n_star / c["capex"], total=netN, n=n_star,
|
||||
n_lim=c["n_lim"], lim=c["lim"], capex=c["capex"] * n_star, eff=c["eff"], bld=c["b"]["Ticker"],
|
||||
top=c["top"], staff=c["staff"], tons=c.get("tons", 0), frt=c.get("frt", 0), h=c["rec"]["TimeMs"] / 3.6e6, thin=c["thin"],
|
||||
top=c["top"], staff=c["staff"], tons=c.get("tons", 0), frt=c.get("frt", 0), h=c["rec"]["TimeMs"] / 3.6e6,
|
||||
thin=c["thin"], bid_thin=c.get("bid_thin", False),
|
||||
area=area, profit_area=netN / area if area else 0.0,
|
||||
rec=" ".join(f"{v:g}{k}" for k, v in c["ins"].items()) + " -> " + " ".join(f"{v:g}{k}" for k, v in c["outs"].items())))
|
||||
key = {"roi": "roiN", "roi1": "roi1", "total": "total"}[a.sort]
|
||||
key = {"roi": "roiN", "roi1": "roi1", "total": "total", "area": "profit_area"}[a.sort]
|
||||
rows.sort(key=lambda r: r[key], reverse=True)
|
||||
if a.json:
|
||||
import json
|
||||
Path(a.json).write_text(json.dumps(rows))
|
||||
print(f"# {a.cx} tier<={a.tier or 'any'} cogc={a.cogc or '-'} faction={faction or '-'} ({pu}/{pt} permits) min-n>={a.min_n} sorted by {a.sort}")
|
||||
print("# ROI/day is for OUR size (--own buildings, default 1) incl. our own price impact; market = buildings the market could absorb (--min-n filters on it, nothing else). Net of freight. Patient asks near VWAP, inputs ask-walked; all estimates")
|
||||
print(f"{'ROI/d':>6} {'own':>3} {'market':>6} {'lim':4} {'profit/d':>11} {'capex':>9} {'eff':>4} {'bld':4} {'staff':5} {'t/d':>5} {'frt/d':>6} {'h':>5} recipe")
|
||||
print("# yld/d is profit/day / capex as a %, for OUR size (--own buildings, default 1) incl. our own price impact; this is NOT a compoundable rate (1/payback, see docs/decisions.md) - pback is the number to actually reason about. market = buildings the market could absorb (--min-n filters on it, nothing else). Net of freight. Patient asks near VWAP, inputs ask-walked; all estimates")
|
||||
print("# profit/area ranks by AIC/day per tile of TOTAL footprint - production building AreaCost PLUS the single-tier hab area its own workforce drags along (heads/100 x hab area, e.g. a 100-head pioneer building pulls a full HB1) - once a base's area cap binds (not cash), this is the real allocation criterion, not yld/d. --sort area to rank by it.")
|
||||
print("# [exit-thin] = INSTANT-DUMP liquidity check, not production price impact: right now, the LIVE bid book can't absorb even 1 day of 1 building's output within --max-impact%% if you needed to sell immediately. A single snapshot (orders change constantly), NOT folded into market/lim (which measures patient ask-side selling via real 30d flow, the actual production mechanism). Re-check before acting on it.")
|
||||
print(f"{'yld/d':>6} {'pback':>6} {'own':>3} {'market':>6} {'lim':4} {'profit/d':>11} {'capex':>9} {'area':>5} {'$/area':>7} {'eff':>4} {'bld':4} {'staff':5} {'t/d':>5} {'frt/d':>6} {'h':>5} recipe")
|
||||
for r in rows[:a.top]:
|
||||
print(f"{r['roiN']:6.1f} {r['n']:3d} {r['n_lim']:6.1f} {r['lim']:4} {r['total']:11.0f} {r['capex']:9.0f} {r['eff']*100:4.0f} {r['bld']:4} {r['staff']:5} {r['tons']:5.0f} {r['frt']:6.0f} "
|
||||
f"{r['h']:5.1f} {r['rec']}{' [thin]' if r['thin'] else ''}")
|
||||
pback = f"{100/r['roiN']:6.1f}" if r['roiN'] > 0 else " inf"
|
||||
flags = (' [thin]' if r['thin'] else '') + (' [exit-thin]' if r['bid_thin'] else '')
|
||||
print(f"{r['roiN']:6.1f} {pback} {r['n']:3d} {r['n_lim']:6.1f} {r['lim']:4} {r['total']:11.0f} {r['capex']:9.0f} {r['area']:5.0f} {r['profit_area']:7.1f} {r['eff']*100:4.0f} {r['bld']:4} {r['staff']:5} {r['tons']:5.0f} {r['frt']:6.0f} "
|
||||
f"{r['h']:5.1f} {r['rec']}{flags}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+103
-8
@@ -10,11 +10,27 @@ having cash in time) matters more than a few points of margin.
|
||||
|
||||
puga sell BHP 8 --cx AI1
|
||||
puga sell BHP 11 --tight # cash-tight: bias the split toward the aggressive tranche
|
||||
puga sell BHP 8 --tiers # is pricing above the current market ever worth the wait?
|
||||
|
||||
--tiers answers "should I price above the current market" with TWO combined mechanisms, since
|
||||
they are separate necessary conditions, not alternatives to average:
|
||||
- queue-depth days: existing resting quantity ahead of you has to actually sell, at the real
|
||||
historical trade-volume rate - valid only WITHIN the recently-traded price range (extrapolating
|
||||
it past that would make a fat-finger outlier ask look "reachable").
|
||||
- empirical first-passage probability: for a price with no resting quantity (above the whole
|
||||
book, or outside the traded range), the market's own price level has to actually move up to
|
||||
it - estimated directly from how often/how fast THIS ticker's real multi-year history has made
|
||||
moves of that size (puga.history.empirical_touch), not assumed from a random-walk formula
|
||||
(real prices mean-revert; see docs/decisions.md).
|
||||
The two combine as: hit_factor (the empirical probability-and-timing-weighted value) shifted by
|
||||
queue_days as a fixed extra delay (exp(-rho*queue_days)), since clearing the queue and waiting for
|
||||
the price move are sequential, not alternative, requirements.
|
||||
"""
|
||||
import argparse, datetime, statistics, sys
|
||||
import argparse, datetime, math, statistics, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio, market
|
||||
from puga.history import trading_days, trade_gaps_days, daily_prices, full_series, empirical_touch
|
||||
|
||||
|
||||
def quantile(xs: list[float], q: float) -> float:
|
||||
@@ -28,10 +44,24 @@ def tranche_split(qty: float, trades: list[float], tight: bool) -> tuple[float,
|
||||
return aggressive, qty - aggressive
|
||||
|
||||
|
||||
def daily_traded(tk: str, cx: str, days: int = 30) -> list[float]:
|
||||
rows = [(datetime.datetime.fromtimestamp(e["DateEpochMs"] / 1000, datetime.timezone.utc).date(), e["Traded"])
|
||||
for e in fio.cxpc(tk, cx) if e.get("Interval") == "DAY_ONE" and e.get("Traded")]
|
||||
return [t for _, t in rows[-days:]]
|
||||
def tier_table(prices: list[float], qty: float, s0: float, series: list, rate: float) -> list[dict]:
|
||||
"""Discounted value of posting at each candidate price, using the EMPIRICAL first-passage
|
||||
distribution of this ticker's own real multi-year price history (puga.history.empirical_touch),
|
||||
not an assumed random-walk formula (real prices mean-revert; see docs/decisions.md). Has no
|
||||
built-in monotonicity: if the real history shows diminishing willingness to move further, a
|
||||
genuine interior optimum can appear instead of being forced by the model's shape.
|
||||
"""
|
||||
rows = []
|
||||
for p in prices:
|
||||
y = math.log(p / s0) if s0 else 0.0
|
||||
if y <= 0:
|
||||
stats = {"hit_factor": 1.0, "touched_frac": 1.0, "median_days": 0.0, "n": len(series)}
|
||||
else:
|
||||
stats = empirical_touch(series, y, rate)
|
||||
rows.append({"price": p, "y": y, "hit_factor": stats["hit_factor"], "touch_frac": stats["touched_frac"],
|
||||
"median_days": stats["median_days"], "n": stats["n"],
|
||||
"revenue": p * qty, "discounted": p * qty * stats["hit_factor"]})
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
@@ -42,6 +72,8 @@ def main():
|
||||
ap.add_argument("--undercut", type=float, default=10, help="AIC to undercut the current best ask by")
|
||||
ap.add_argument("--tight", action="store_true", help="cash-tight: bias the tranche split toward the aggressive (undercut) tranche")
|
||||
ap.add_argument("--show-bid", action="store_true", help="also show instant-bid revenue (usually worse than the tranche split; off by default)")
|
||||
ap.add_argument("--rate", type=float, default=0.05, help="your REALIZED daily capital growth rate (opportunity cost of waiting), not a theoretical build ROI - default 0.05 matches this account's observed equity-growth curve as of 2026-10-10; pass your own if it's moved")
|
||||
ap.add_argument("--tiers", action="store_true", help="show discounted value (price*qty discounted at --rate over the implied wait) across all existing ask tiers, to check whether climbing the book is ever worth it")
|
||||
a = ap.parse_args()
|
||||
t = a.ticker.upper()
|
||||
ob = fio.order_book(t, a.cx)
|
||||
@@ -50,16 +82,28 @@ def main():
|
||||
post = round((best_ask - a.undercut) if best_ask else (ob.get("Ask") or 0))
|
||||
ahead = sum(u for p, u in asks if p < post)
|
||||
|
||||
trades = daily_traded(t, a.cx)
|
||||
days_window = 30
|
||||
td = trading_days(t, a.cx, days_window)
|
||||
trades = [v for _, v in td]
|
||||
med = statistics.median(trades) if trades else 0
|
||||
lo = sorted(trades)[int(0.2 * (len(trades) - 1))] if trades else 0
|
||||
hi = sorted(trades)[int(0.8 * (len(trades) - 1))] if trades else 0
|
||||
trade_frac = len(td) / days_window
|
||||
gaps = trade_gaps_days([d for d, _ in td])
|
||||
median_gap = statistics.median(gaps) if gaps else (days_window if len(td) <= 1 else 0)
|
||||
|
||||
print(f"{t}.{a.cx} best ask {best_ask} bid {ob.get('Bid')} vwap7 {ob.get('PriceAverage')}")
|
||||
print(f"\npost {a.qty:g} at {post:.0f} ({ahead:.0f} units ahead of you at a lower price)")
|
||||
print(f" revenue if filled: {post * a.qty:,.0f}")
|
||||
if med:
|
||||
print(f" expected clear time (last {len(trades)}d volume): busy day {24 * a.qty / hi:.1f}h | "
|
||||
print(f" trades on {len(td)}/{days_window} of the last {days_window} days ({100*trade_frac:.0f}%)"
|
||||
+ (f", median gap between trading days: {median_gap:.0f}d" if gaps else ""))
|
||||
if trade_frac < 0.5:
|
||||
print(f" SPARSE TICKER: most days see no trade at all - don't expect a same-day fill by default. "
|
||||
f"Once a trade happens, it tends to move: busy day {24 * a.qty / hi:.1f}h | median day {24 * a.qty / med:.1f}h | "
|
||||
f"slow day {24 * a.qty / max(lo, 1):.1f}h for your quantity - but you may wait ~{median_gap:.0f}d first for a trade to happen at all")
|
||||
else:
|
||||
print(f" expected clear time (last {days_window}d volume): busy day {24 * a.qty / hi:.1f}h | "
|
||||
f"median day {24 * a.qty / med:.1f}h | slow day {24 * a.qty / max(lo, 1):.1f}h")
|
||||
else:
|
||||
print(" no recent trade history to estimate clear time")
|
||||
@@ -70,12 +114,63 @@ def main():
|
||||
+ (f", SHORT: book only fills {hit['filled']:.0f}" if hit["short"] else "") + ")")
|
||||
print(f" posting patiently gains {post * a.qty - hit['total']:,.0f} over this, at the cost of waiting")
|
||||
|
||||
if a.tiers:
|
||||
dp = daily_prices(t, a.cx)
|
||||
s0 = sorted(dp.items())[-1][1][0] if dp else (best_ask or ob.get("Ask") or 0)
|
||||
series = full_series(t, a.cx)
|
||||
rho = math.log(1 + a.rate)
|
||||
tier_prices = sorted({p for p, _ in asks} | {post, s0})
|
||||
rows = tier_table(tier_prices, a.qty, s0, series, a.rate)
|
||||
|
||||
# Queue-depth days: valid ONLY within the range this ticker has genuinely traded in -
|
||||
# the mechanism it models (real buy flow eating through resting ahead-quantity) has no
|
||||
# evidence to extrapolate beyond that (this is what made a fat-finger outlier ask look
|
||||
# reachable before). Outside that range it's infinite (no constraint from this mechanism;
|
||||
# the empirical median_days alone governs).
|
||||
cutoff_date = datetime.datetime.now(datetime.timezone.utc).date() - datetime.timedelta(days=days_window)
|
||||
recent_prices = [p for d, (p, _) in dp.items() if d >= cutoff_date]
|
||||
cutoff_price = max(recent_prices + [best_ask or 0]) * 1.1 if recent_prices else float("inf")
|
||||
med_vol = med or 1
|
||||
for r in rows:
|
||||
# p <= (not <): a resting order AT the same price was posted first and has time
|
||||
# priority over yours - it's ahead of you too, not a free pass to the front of the queue.
|
||||
ahead = sum(u for p, u in asks if p <= r["price"])
|
||||
# Outside the recent-traded range the queue mechanism doesn't meaningfully apply (no
|
||||
# real evidence that cumulative ahead-quantity, much of it itself unreachable junk
|
||||
# asks, clears at the normal rate) - that means "not a binding constraint" (0), NOT
|
||||
# "infinite constraint".
|
||||
r["queue_days"] = (ahead + a.qty) / med_vol if r["price"] <= cutoff_price else 0.0
|
||||
# Rank by hit_factor (the real empirical E[e^-rho*tau] from tier_table), with
|
||||
# queue_days folded in as a FIXED, deterministic shift of tau: shifting a random delay
|
||||
# by a constant multiplies its Laplace transform by exp(-rho*shift), which is exactly
|
||||
# right when "clear the real resting queue, THEN wait for price to reach this tier"
|
||||
# are sequential, not alternative, constraints. median_days (shown separately below)
|
||||
# is not used for the value itself - plugging a point estimate into (1+rate)^-days
|
||||
# would be biased by Jensen's inequality, and None (<50% touched) would wrongly zero
|
||||
# out a tier that hit_factor still values smoothly.
|
||||
r["combined_hit"] = r["hit_factor"] * math.exp(-rho * r["queue_days"])
|
||||
r["discounted_combined"] = r["revenue"] * r["combined_hit"]
|
||||
|
||||
best = max(rows, key=lambda r: r["discounted_combined"]) if rows else None
|
||||
print(f"\nTIER TABLE (last traded {s0:.0f}, {len(series)}d history, rate {100*a.rate:.1f}%/day - see --help):")
|
||||
print(f" {'price':>10} {'queue(d)':>9} {'touched':>8} {'median(d)':>10} {'hit%':>6} {'revenue':>10} {'discounted':>11}")
|
||||
for r in rows:
|
||||
flag = " <- best" if best is r else ""
|
||||
qd = f"{r['queue_days']:.1f}" if r["queue_days"] != float("inf") else "n/a"
|
||||
md = f"{r['median_days']:.1f}" if r["median_days"] is not None else "never"
|
||||
print(f" {r['price']:>10.0f} {qd:>9} {100*r['touch_frac']:>7.0f}% {md:>10} {100*r['combined_hit']:>5.1f}% "
|
||||
f"{r['revenue']:>10,.0f} {r['discounted_combined']:>11,.0f}{flag}")
|
||||
if best and best["price"] > s0:
|
||||
print(f" climbing to {best['price']:.0f} beats selling now")
|
||||
else:
|
||||
print(f" selling at/near the current price ({s0:.0f}) dominates")
|
||||
|
||||
aggr_qty, patient_qty = tranche_split(a.qty, trades, a.tight)
|
||||
if patient_qty > 0.01:
|
||||
tiers_above = sorted({p for p, u in asks if p > post})
|
||||
patient_price = round(tiers_above[0] - 1) if tiers_above else round(post + 2 * a.undercut)
|
||||
q_label = "80th pct (tight)" if a.tight else "median"
|
||||
print(f"\nTRANCHE SPLIT ({q_label} volume quantile, {len(trades)}d):")
|
||||
print(f"\nTRANCHE SPLIT ({q_label} volume quantile, {len(trades)} trading days in the last {days_window}d):")
|
||||
print(f" aggressive: {aggr_qty:.1f} @ {post:.0f} (confident to clear today)")
|
||||
print(f" patient: {patient_qty:.1f} @ {patient_price:.0f} (waits behind the next tier, higher margin)")
|
||||
print(f" vs posting all {a.qty:g} at {post:.0f}: gains {patient_qty*(patient_price-post):,.0f} extra if the patient tranche fills")
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fuel/AIC cost for a ship trip FROM EXPLICIT PARAMETERS (jumps, sliders, gateways) - for when
|
||||
you already know the trip's physics breakdown (e.g. from tools/route.py, or copying a known
|
||||
route). If you just want "ship X from A to B, what's it cost", use tools/shiptrip.py instead -
|
||||
it works all of this out for you. SCOPED TO the account's one hull/reactor (blueprint
|
||||
BP-STRT-0000, stock reactor), shared by both ships (AVI-07JFB, AVI-07JFC). See puga/shipping.py's
|
||||
module docstring for exactly what's confirmed vs still open (generalization to a different
|
||||
hull/reactor is untested; gravity vs distance on landing fuel is confounded; v0's meaning is
|
||||
relative to current fuel load, not an absolute unit).
|
||||
|
||||
tools/shipcost.py --v0 0.5 --v1 0.65 --jumps 1 --to ZV-759c # one direct jump to Deimos
|
||||
tools/shipcost.py --v0 1.0 --jumps 2 --charges 1 --to ZV-194a # two-jump route to Nike
|
||||
tools/shipcost.py --v0 1.0 --gateways 3 --lock-fee 6000:AIC --lock-fee 6000:AIC --lock-fee 4000:CIS # Benten-style - fees read off the live APEX LOCK segment, not formulaic/lookupable
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, market, shipping
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--v0", type=float, default=1.0, help="fuel-usage slider, 0..1 (relative to current STL tank level, not absolute)")
|
||||
ap.add_argument("--v1", type=float, default=1.0, help="reactor-usage slider, 0..1")
|
||||
ap.add_argument("--jumps", type=int, default=0, help="number of direct FTL jumps (JMP segments)")
|
||||
ap.add_argument("--charges", type=int, default=0, help="number of FTL recharges (CHRG) between consecutive jumps")
|
||||
ap.add_argument("--cruise-legs", type=int, default=2, help="number of STL cruise legs (DEP+APP=2 for a simple direct route)")
|
||||
ap.add_argument("--gateways", type=int, default=0, help="number of gateway hops (each: free GTW + a LOCK fee you supply)")
|
||||
ap.add_argument("--lock-fee", action="append", default=[], help="AMOUNT:CURRENCY per gateway hop, repeatable, matched in order to --gateways - read the fee off the live APEX LOCK segment, there's no API/formula for it")
|
||||
ap.add_argument("--to", help="destination planet natural id, for a looked-up (not predicted) landing fuel cost")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.gateways and len(a.lock_fee) != a.gateways:
|
||||
print(f"warning: {a.gateways} gateways but {len(a.lock_fee)} --lock-fee given - fees you didn't supply are unknown, not zero", file=sys.stderr)
|
||||
lock_fees = [(float(amt), cur) for amt, cur in (lf.split(":") for lf in a.lock_fee)]
|
||||
|
||||
result = shipping.trip_fuel(a.v0, a.v1, a.jumps, a.charges, a.cruise_legs, a.to, lock_fees)
|
||||
if a.to and result["landing_fuel_included"] is None:
|
||||
print(f"note: landing fuel for {a.to} hasn't been measured - not included in total, see puga/shipping.py LANDING_FUEL", file=sys.stderr)
|
||||
|
||||
snap = market.snapshot()
|
||||
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||
stl, ftl, fees = result["stl_fuel"], result["ftl_fuel"], result["lock_fees"]
|
||||
|
||||
lnd = result["landing_fuel_included"]
|
||||
print(f"jumps {a.jumps} charges {a.charges} cruise legs {a.cruise_legs}" + (f" landing +{lnd:.0f} STL" if lnd else ""))
|
||||
print(f"STL fuel: {stl:.1f} units -> {stl*sf_px:,.0f} AIC")
|
||||
print(f"FTL fuel: {ftl:.1f} units -> {ftl*ff_px:,.0f} AIC")
|
||||
if fees:
|
||||
print("Gateway LOCK fees: " + ", ".join(f"{amt:,.0f} {cur}" for amt, cur in fees))
|
||||
total_aic_fuel = stl * sf_px + ftl * ff_px
|
||||
aic_fees = sum(amt for amt, cur in fees if cur == "AIC")
|
||||
print(f"\nTotal (fuel, AIC-denominated fees only): {total_aic_fuel + aic_fees:,.0f} AIC" + (" + non-AIC fees above" if any(cur != "AIC" for _, cur in fees) else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Simplest possible ship-trip cost: give it a ship, a start and a stop, done - it works out
|
||||
jumps/charges/sliders/landing fuel itself. For when you don't know (and shouldn't need to know)
|
||||
the physics breakdown - if you already have jump counts/slider values/gateway fees in hand, use
|
||||
the lower-level tools/shipcost.py instead.
|
||||
|
||||
tools/shiptrip.py AVI-07JFB ZV-307 ZV-759c # Antares -> Deimos
|
||||
tools/shiptrip.py AVI-07JFC "Antares Station" Nike # names/planets/systems all work
|
||||
|
||||
Defaults to max sliders (v0=v1=1.0, fastest) since that's the common case; pass --v0/--v1 to
|
||||
model a slower/cheaper trip. Covers direct-jump routes (puga/route.py's FTL jump graph) and the
|
||||
handful of gateway chains with a measured LOCK fee (puga.shipping.KNOWN_GATEWAY_ROUTES) - for
|
||||
any other gateway route, the LOCK fee genuinely cannot be looked up (no FIO/PRUNplanner endpoint
|
||||
has it), and this tool tells you exactly where to read it live and what to run afterward.
|
||||
"""
|
||||
import argparse, math, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, fio, market, shipping
|
||||
|
||||
|
||||
def check_ship(reg: str):
|
||||
"""Warn (don't fail) if the given ship's live specs don't match what this model is
|
||||
calibrated against - see shipping.CALIBRATED_SPEC."""
|
||||
try:
|
||||
ships = fio.own(f"/ship/ships/{fio.me()}")
|
||||
except Exception:
|
||||
return None
|
||||
ship = next((s for s in ships if s.get("Registration") == reg), None)
|
||||
if ship is None:
|
||||
print(f"warning: {reg!r} isn't a ship on this account (known: "
|
||||
+ ", ".join(s.get("Registration", "?") for s in ships) + ") - proceeding anyway", file=sys.stderr)
|
||||
return None
|
||||
spec = shipping.CALIBRATED_SPEC
|
||||
|
||||
def differs(k, v):
|
||||
return v != spec[k] if isinstance(spec[k], str) else not math.isclose(v or 0, spec[k], rel_tol=1e-6)
|
||||
|
||||
mismatches = [k for k, v in {"blueprint": ship.get("BlueprintNaturalId"), "acceleration": ship.get("Acceleration"),
|
||||
"thrust": ship.get("Thrust"), "reactor_power": ship.get("ReactorPower"),
|
||||
"emitter_power": ship.get("EmitterPower")}.items()
|
||||
if differs(k, v)]
|
||||
if mismatches:
|
||||
print(f"warning: {reg} differs from the calibrated hull/reactor on {', '.join(mismatches)} - "
|
||||
f"this model (puga/shipping.py) has NOT been validated for this ship, numbers may be wrong", file=sys.stderr)
|
||||
return ship
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("ship", help="ship registration, e.g. AVI-07JFB")
|
||||
ap.add_argument("src", help="start: planet natural id, system natural id, or name")
|
||||
ap.add_argument("dst", help="stop: planet natural id, system natural id, or name")
|
||||
ap.add_argument("--v0", type=float, default=1.0, help="fuel-usage slider, 0..1 (default 1.0 = fastest)")
|
||||
ap.add_argument("--v1", type=float, default=1.0, help="reactor-usage slider, 0..1 (default 1.0 = fastest)")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
a = ap.parse_args()
|
||||
|
||||
check_ship(a.ship)
|
||||
|
||||
snap = market.snapshot()
|
||||
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||
|
||||
result = shipping.leg_cost(a.src, a.dst, sf_px, ff_px, a.v0, a.v1)
|
||||
if result is None:
|
||||
sys.exit(f"no priceable route between {a.src} and {a.dst} - not a direct-jump route, and not a measured "
|
||||
f"gateway chain (puga.shipping.KNOWN_GATEWAY_ROUTES). The LOCK fee can't be looked up (no "
|
||||
f"FIO/PRUNplanner endpoint has it) - open the Ship Flight Control screen in APEX for this exact "
|
||||
f"route, read each LOCK segment's fee, then run:\n"
|
||||
f" tools/shipcost.py --v0 {a.v0} --gateways N --lock-fee AMOUNT:CURRENCY [--lock-fee ...]")
|
||||
|
||||
lnd = result["landing_fuel_included"]
|
||||
print(f"{a.src} -> {a.dst}" + (" (landing fuel not measured for this destination - not included)" if lnd is None else ""))
|
||||
print(f"STL fuel: {result['stl_fuel']:.1f} units -> {result['stl_fuel']*sf_px:,.0f} AIC")
|
||||
print(f"FTL fuel: {result['ftl_fuel']:.1f} units -> {result['ftl_fuel']*ff_px:,.0f} AIC")
|
||||
if result["non_aic_fees"]:
|
||||
print("Gateway LOCK fees (non-AIC): " + ", ".join(f"{amt:,.0f} {cur}" for amt, cur in result["non_aic_fees"]))
|
||||
print(f"\nTotal (AIC): {result['aic']:,.0f}" + (" + non-AIC fees above" if result["non_aic_fees"] else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+1
-1
@@ -70,7 +70,7 @@ def main():
|
||||
print(f"{plan['plan_name']} {plan['planet_natural_id']} COGC {plan.get('plan_cogc')} prices: {a.cx} {a.basis}")
|
||||
print(f"Area {r['area']:.0f}/500 Profit/day {r['profit']:,.0f} gross {r['gross']:,.0f} degradation {r['degradation']:,.0f} plan cost {r['plan_cost']:,.0f} ROI {r['roi_days'] and round(r['roi_days'], 2)} d")
|
||||
nc = r["new_capex"]
|
||||
print(f"NEW CAPEX = planned minus already built ({built or 'nothing built'}): {nc:,.0f} -> payback {nc / r['profit']:.2f} d = {100 * r['profit'] / nc:.1f}%/day" if r["profit"] > 0 and nc > 0 else ("NEW CAPEX: nothing to build" if nc <= 0 else "NEW CAPEX: profit <= 0"))
|
||||
print(f"NEW CAPEX = planned minus already built ({built or 'nothing built'}): {nc:,.0f} -> payback {nc / r['profit']:.2f} d" if r["profit"] > 0 and nc > 0 else ("NEW CAPEX: nothing to build" if nc <= 0 else "NEW CAPEX: profit <= 0"))
|
||||
print("\nWORKFORCE need supply open eff%")
|
||||
for t, w in r["workforce"].items():
|
||||
if w["need"] or w["supply"]:
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Manufactured goods currently selling below their implied production cost (output price minus
|
||||
live input cost) - candidates to buy and hold for a price-reversion bounce, not to build.
|
||||
|
||||
EXPECTED ROI IS MUCH LOWER THAN THIS PROJECT'S PRODUCTION BUILDS. Backtest (2026-10-09, 326
|
||||
output tickers, 287 independent dip-onset episodes across 112 distinct tickers, >=10 units/day
|
||||
volume): +3 months forward price return mean +21.3%, median +8.9%, 73.2% of episodes positive.
|
||||
That's ~0.10-0.24%/day, or very roughly ~41%/year if you could always immediately redeploy into
|
||||
a new dip (optimistic) - versus 14-29%/day marginal ROI on the production buildings this toolkit
|
||||
has been recommending. Gross price return only, no spread/freight/storage-fee/capital-lockup cost
|
||||
subtracted. Only deploy EXCESS capital here once better-yielding builds are exhausted - this is
|
||||
not a primary strategy.
|
||||
|
||||
tools/undervalued.py # AI1, min 5 units/day traded
|
||||
tools/undervalued.py --cx AI1 --min-vol 10 --top 10
|
||||
"""
|
||||
import argparse, sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, undervalued
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
ap.add_argument("--min-vol", type=float, default=5.0, help="min units/day traded (noise filter, thin markets won't revert reliably)")
|
||||
ap.add_argument("--top", type=int, default=20)
|
||||
a = ap.parse_args()
|
||||
|
||||
rows = undervalued.scan_current(a.cx, a.min_vol)
|
||||
if not rows:
|
||||
print(f"nothing currently priced below production cost at {a.cx} with volume >= {a.min_vol}/day")
|
||||
return
|
||||
print(f"# {a.cx} min-vol>={a.min_vol}/day (gross price return only - see docstring for backtest caveats)")
|
||||
print(f"{'ticker':6} {'margin%':>8} {'price':>10} {'vol/d':>7} bld")
|
||||
for r in rows[:a.top]:
|
||||
print(f"{r['ticker']:6} {r['margin_pct']:8.1f} {r['price']:10.1f} {r['volume']:7.1f} {r['building']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+244
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Marginal ROI of adding to a base you already run: whole-plan-with-addition minus whole-plan-
|
||||
without, per docs/library.md's diffing rule (NOT the plan-level ROI simulate.py/PRUNplanner print,
|
||||
which divides whole-plan profit by only the new capex and badly overstates once a base exists).
|
||||
Also flags any workforce tier the addition pushes over capacity (the recurring surprise this
|
||||
session - e.g. PP2 overloading pioneer housing after POL+CHP already maxed it).
|
||||
|
||||
tools/whatif.py plans/examples/deimos_base.yaml --add CHP:1:MG,S,CU=>IND --infra HB1:+1
|
||||
tools/whatif.py before.yaml --after after.yaml # two explicit full-base specs instead
|
||||
tools/whatif.py before.yaml --add POL:1 # reuses POL's existing recipe in before.yaml
|
||||
"""
|
||||
import argparse, copy, sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
from puga import config, contracts, fio, market, prunplanner as pp, shipping
|
||||
from puga.simulate import simulate
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import plan_push
|
||||
|
||||
|
||||
def apply_add(spec: dict, add: str):
|
||||
"""BUILDING:AMOUNT[:RECIPE[|RECIPE...]] - amount is a delta; recipe reuses an existing
|
||||
entry of the same building ticker in spec if omitted."""
|
||||
parts = add.split(":", 2)
|
||||
if len(parts) < 2:
|
||||
sys.exit(f"--add needs BUILDING:AMOUNT[:RECIPE], got {add!r}")
|
||||
ticker, amount = parts[0], int(parts[1])
|
||||
recipes = parts[2].split("|") if len(parts) == 3 else None
|
||||
for b in spec.setdefault("buildings", []):
|
||||
if b["building"] == ticker and (recipes is None or b["recipes"] == recipes):
|
||||
b["amount"] += amount
|
||||
return
|
||||
if recipes is None:
|
||||
sys.exit(f"no existing {ticker} in the plan to infer a recipe from - give one: {ticker}:{amount}:RECIPE")
|
||||
spec["buildings"].append({"building": ticker, "amount": amount, "recipes": recipes})
|
||||
|
||||
|
||||
def apply_remove(spec: dict, remove: str):
|
||||
"""BUILDING[:AMOUNT] - a teardown scenario: removes AMOUNT (default: all) of that building
|
||||
from the plan. For "should we demolish this" questions - pass the current full base as
|
||||
--after and the --remove result as the plain positional arg (or vice versa; whatif always
|
||||
reports AFTER minus BEFORE, so order which one is which by what you want the sign to mean)."""
|
||||
parts = remove.split(":", 1)
|
||||
ticker = parts[0]
|
||||
amount = int(parts[1]) if len(parts) == 2 else None
|
||||
for b in spec.get("buildings", []):
|
||||
if b["building"] == ticker:
|
||||
b["amount"] = max(0, b["amount"] - amount) if amount else 0
|
||||
spec["buildings"] = [b for b in spec.get("buildings", []) if b["amount"] > 0]
|
||||
|
||||
|
||||
def apply_infra(spec: dict, infra: str):
|
||||
"""HB1:+1,HB2:+2 - deltas added to spec['infrastructure']."""
|
||||
inf = spec.setdefault("infrastructure", {})
|
||||
for part in infra.split(","):
|
||||
ticker, amount = part.split(":")
|
||||
inf[ticker] = inf.get(ticker, 0) + int(amount)
|
||||
|
||||
|
||||
def reclaim_value(ticker: str, qty: int, built_count: int, cx: str):
|
||||
"""Sell value of the materials you'd actually get back demolishing `qty` of a building you
|
||||
already own `built_count` of - real per-site data from FIO's own reclaimables endpoint
|
||||
(demolition is NOT a dead loss: observed ~50-90%% of original materials back, varies by
|
||||
material, not a fixed fraction - don't approximate it, look it up). None if you don't
|
||||
actually own one (can't reclaim a hypothetical building)."""
|
||||
if built_count <= 0 or qty <= 0:
|
||||
return None
|
||||
u = fio.me()
|
||||
rec = fio.own(f"/rain/userplanetbuildingreclaimables/{u}", ttl=3600)
|
||||
totals = Counter()
|
||||
for x in rec:
|
||||
if x["BuildingId"].startswith(f"{ticker}-"):
|
||||
totals[x["Material"]] += x["Amount"]
|
||||
if not totals:
|
||||
return None
|
||||
value = 0.0
|
||||
items = {}
|
||||
for mat, amt in totals.items():
|
||||
q = round(amt / built_count * min(qty, built_count)) # amt is already summed over all built_count units
|
||||
if q <= 0:
|
||||
continue
|
||||
w = market.walk(mat, cx, q, "sell")
|
||||
items[mat] = q
|
||||
value += w["total"]
|
||||
return {"value": value, "items": items}
|
||||
|
||||
|
||||
def trip_tonnage(flows: dict, mats: dict):
|
||||
"""Total t/m3 the base needs to haul IN (net importers) and ship OUT (net exporters) per day -
|
||||
same accounting scan.py already uses for its own trip-cost estimate (max of the four, since
|
||||
imports and exports share the same round trips)."""
|
||||
w_in = w_out = v_in = v_out = 0.0
|
||||
for t, f in flows.items():
|
||||
net = f["inp"] - f["out"]
|
||||
m = mats.get(t)
|
||||
if not m or abs(net) < 1e-6:
|
||||
continue
|
||||
if net > 0:
|
||||
w_in += net * m["Weight"]; v_in += net * m["Volume"]
|
||||
else:
|
||||
w_out += -net * m["Weight"]; v_out += -net * m["Volume"]
|
||||
return w_in, w_out, v_in, v_out
|
||||
|
||||
|
||||
def marginal_freight(r_b, r_a, planet_id, cx, sf_price, ff_price, mats):
|
||||
"""AIC/day freight for the EXTRA trips this addition requires - not the base's whole freight
|
||||
bill. Continuous amortized rate (extra tonnage/cargo-hold x round-trip cost), proportional to
|
||||
the addition's own tonnage, not a step function - a small addition gets a small freight charge,
|
||||
not exactly zero (that would need a real per-trip ceiling/rounding this doesn't model). Still
|
||||
catches a recipe whose ROI looks great only because its freight cost was left out. Returns
|
||||
(freight_aic_per_day, note)."""
|
||||
origin = shipping.cx_system(cx)
|
||||
if origin is None:
|
||||
return 0.0, f"no station found for CX {cx!r} - freight not modelled"
|
||||
rt = shipping.round_trip_cost(origin, planet_id, sf_price, ff_price)
|
||||
if rt is None:
|
||||
return 0.0, "no priceable route (gateway without a measured LOCK fee?) - freight not modelled"
|
||||
trips_b = max(trip_tonnage(r_b["flows"], mats)) / contracts.SHIP_CARGO
|
||||
trips_a = max(trip_tonnage(r_a["flows"], mats)) / contracts.SHIP_CARGO
|
||||
extra_trips = trips_a - trips_b
|
||||
return extra_trips * rt, f"{extra_trips:+.3f} extra round trips/day x {rt:,.0f} AIC/trip"
|
||||
|
||||
|
||||
def run(spec, recipes, blds, price, faction, perm, built):
|
||||
plan = plan_push.build_payload(spec, recipes, {b["building_ticker"] for b in blds})
|
||||
planet = pp._g(f"/data/planet/{plan['planet_natural_id']}/", 3600)
|
||||
return plan, simulate(plan, recipes, blds, planet["resources"], planet["fertility"], price, faction, perm, built=built, planet=planet)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("before", help="full-base plan spec as it stands (or as a baseline you want to compare from)")
|
||||
ap.add_argument("--after", help="full-base plan spec with the addition already in it; skips --add/--infra")
|
||||
ap.add_argument("--add", action="append", default=[], help="BUILDING:AMOUNT[:RECIPE[|RECIPE]], repeatable")
|
||||
ap.add_argument("--remove", action="append", default=[], help="BUILDING[:AMOUNT] - teardown scenario, removes AMOUNT (default: all), repeatable")
|
||||
ap.add_argument("--infra", action="append", default=[], help="HB1:+1,HB2:+2, repeatable")
|
||||
ap.add_argument("--cx", default=config.DEFAULT_CX)
|
||||
ap.add_argument("--basis", default="uni30", choices=["real", "uni30", "vwap30", "vwap7", "ask", "bid", "mid"])
|
||||
ap.add_argument("--no-faction", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
before_spec = yaml.safe_load(Path(a.before).read_text())
|
||||
if a.after:
|
||||
after_spec = yaml.safe_load(Path(a.after).read_text())
|
||||
else:
|
||||
if not a.add and not a.remove and not a.infra:
|
||||
sys.exit("give --after, or at least one --add/--remove/--infra")
|
||||
after_spec = copy.deepcopy(before_spec)
|
||||
for add in a.add:
|
||||
apply_add(after_spec, add)
|
||||
for remove in a.remove:
|
||||
apply_remove(after_spec, remove)
|
||||
for infra in a.infra:
|
||||
apply_infra(after_spec, infra)
|
||||
|
||||
recipes, blds = pp.recipes(), pp.buildings()
|
||||
snap = market.snapshot()
|
||||
|
||||
def price(t, side="buy"):
|
||||
if a.basis == "uni30":
|
||||
v = market.uni30(snap, t)
|
||||
if v:
|
||||
return v
|
||||
q = snap.get((t, a.cx))
|
||||
return q.ask if q else None
|
||||
q = snap.get((t, a.cx))
|
||||
if not q:
|
||||
return None
|
||||
return {"real": q.ask if side == "buy" else (q.vwap7 or q.vwap30 or q.bid),
|
||||
"vwap30": q.vwap30 or q.vwap7 or q.ask, "vwap7": q.vwap7 or q.vwap30 or q.ask,
|
||||
"ask": q.ask, "bid": q.bid, "mid": (q.ask + q.bid) / 2 if q.ask and q.bid else None}[a.basis]
|
||||
|
||||
st = yaml.safe_load(config.state_path().read_text())
|
||||
faction = None if a.no_faction else (st.get("company") or {}).get("faction")
|
||||
perm = (st.get("permits", {}).get("used", 1), st.get("permits", {}).get("total", 2))
|
||||
planet_id = before_spec["planet"]
|
||||
built = next((b.get("buildings", {}) for b in st.get("bases", []) if b.get("planet") == planet_id), {})
|
||||
|
||||
# hq comes from each spec file's own "hq:" field (plan_push.build_payload reads it directly) -
|
||||
# keep both before/after specs' hq set explicitly rather than relying on state here.
|
||||
plan_b, r_b = run(before_spec, recipes, blds, price, faction, perm, built)
|
||||
plan_a, r_a = run(after_spec, recipes, blds, price, faction, perm, built)
|
||||
|
||||
d_profit = r_a["profit"] - r_b["profit"]
|
||||
d_capex = r_a["new_capex"] - r_b["new_capex"]
|
||||
|
||||
mats = {m["Ticker"]: m for m in fio.materials()}
|
||||
sf_px = (snap.get(("SF", a.cx)) or market.Quote("SF", a.cx)).ask or 0
|
||||
ff_px = (snap.get(("FF", a.cx)) or market.Quote("FF", a.cx)).ask or 0
|
||||
freight, freight_note = marginal_freight(r_b, r_a, planet_id, a.cx, sf_px, ff_px, mats)
|
||||
d_profit -= freight
|
||||
|
||||
before_counts = Counter(b["building"] for b in before_spec.get("buildings", []) for _ in range(b["amount"]))
|
||||
after_counts = Counter(b["building"] for b in after_spec.get("buildings", []) for _ in range(b["amount"]))
|
||||
reclaim_total = 0.0
|
||||
reclaim_lines = []
|
||||
for ticker in before_counts:
|
||||
removed_qty = before_counts[ticker] - after_counts.get(ticker, 0)
|
||||
if removed_qty > 0:
|
||||
r = reclaim_value(ticker, removed_qty, built.get(ticker, 0), a.cx)
|
||||
if r:
|
||||
reclaim_total += r["value"]
|
||||
items = ", ".join(f"{q}{m}" for m, q in r["items"].items())
|
||||
reclaim_lines.append(f" {ticker} x{removed_qty}: {r['value']:,.0f} AIC ({items})")
|
||||
|
||||
print(f"BEFORE profit/day {r_b['profit']:,.0f} new_capex {r_b['new_capex']:,.0f}")
|
||||
print(f"AFTER profit/day {r_a['profit']:,.0f} new_capex {r_a['new_capex']:,.0f}")
|
||||
print(f"FREIGHT {freight:+,.0f} AIC/day marginal ({freight_note})")
|
||||
if reclaim_lines:
|
||||
print("\nRECLAIMED MATERIALS (demolishing what's removed, sell value, real FIO data):")
|
||||
for line in reclaim_lines:
|
||||
print(line)
|
||||
print(f" total: {reclaim_total:,.0f} AIC")
|
||||
net_capex = d_capex - reclaim_total
|
||||
net_label = f" net cash GAINED {-net_capex:,.0f}" if net_capex < 0 and reclaim_total else (f" net new capex {net_capex:,.0f}" if reclaim_total else "")
|
||||
print(f"\nMARGINAL profit/day {d_profit:,.0f} new_capex {d_capex:,.0f}" + net_label, end="")
|
||||
if net_capex > 0 and d_profit > 0:
|
||||
print(f" payback {net_capex/d_profit:.1f} d (simple, non-compounding - a one-time capex paying itself off; not a reinvestable rate, see docs/decisions.md)")
|
||||
elif net_capex <= 0 and d_profit > 0:
|
||||
print(" (no net new capex after reclaim)" if reclaim_total else " (no new capex)")
|
||||
else:
|
||||
print(" (marginal profit <= 0 - not worth it, regardless of reclaim)")
|
||||
|
||||
print("\nWORKFORCE (after) need supply open eff%")
|
||||
newly_overloaded = []
|
||||
for t, w in r_a["workforce"].items():
|
||||
if w["need"] or w["supply"]:
|
||||
was_already_overloaded = r_b["workforce"].get(t, {}).get("open", 0) < 0
|
||||
flag = ""
|
||||
if w["open"] < 0 and not was_already_overloaded:
|
||||
flag = " <- NEWLY OVERLOADED by this addition, drags every building's efficiency down"
|
||||
newly_overloaded.append(t)
|
||||
elif w["open"] < 0:
|
||||
flag = " (already overloaded before this addition too - not new)"
|
||||
print(f" {t:10} {w['need']:5.0f} {w['supply']:6.0f} {w['open']:5.0f} {w['eff']*100:7.2f}{flag}")
|
||||
if newly_overloaded:
|
||||
print(f"\nFix before building: more housing for {', '.join(newly_overloaded)} (see which HB covers each tier).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user