Spaces:
Configuration error

DevAtomicRelease commited on
Commit
f898792
·
0 Parent(s):

Initial clean commit

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyd
5
+ *.exe
6
+ .env
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # Install dependencies
6
+ COPY requirements.txt .
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ # Copy project files
10
+ COPY . .
11
+
12
+ # Expose HF Spaces default port
13
+ EXPOSE 7860
14
+
15
+ # Health check
16
+ HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
17
+ CMD python -c "import requests; requests.get('http://localhost:7860/health').raise_for_status()" || exit 1
18
+
19
+ # Run the server
20
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
Financial_hack ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit aea3946240fbe94e7c387e597059eaf2613b6532
README.md ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <<<<<<< HEAD
2
+ # Financial Statement Anomaly Detection
3
+
4
+ An OpenEnv environment that simulates forensic financial auditing. The agent receives quarterly financial statements and must identify anomalies ranging from arithmetic errors to coordinated fraud patterns.
5
+
6
+ ## Motivation
7
+
8
+ Financial auditing is a $15B+ global industry. Every public company undergoes quarterly audits by firms like Deloitte, KPMG, EY, and PwC. The SEC uses anomaly detection for enforcement actions. This environment provides a standardized benchmark for training and evaluating AI agents on financial compliance tasks.
9
+
10
+ ## Environment Overview
11
+
12
+ The agent receives structured financial data (balance sheet, income statement, cash flow statement) for a fictional company across multiple quarters. It must:
13
+
14
+ - Analyze the data for errors, inconsistencies, and suspicious patterns
15
+ - Flag anomalies with type, location, severity, and explanation
16
+ - Submit a final audit report for grading
17
+
18
+ ## Action Space
19
+
20
+ | Action | Parameters | Effect |
21
+ |--------|-----------|--------|
22
+ | `flag_anomaly` | line_item, quarter, severity (1-5), anomaly_type, explanation | Records a suspected anomaly |
23
+ | `request_detail` | line_item, quarter | Returns sub-ledger breakdown (-0.1 reward) |
24
+ | `submit_report` | none | Ends episode, triggers grading |
25
+
26
+ ### Anomaly Types
27
+
28
+ **Easy**: `arithmetic_error`, `duplicate_entry`, `negative_value`, `impossible_change`, `percentage_error`
29
+
30
+ **Medium**: `receivables_divergence`, `inventory_turnover`, `cashflow_mismatch`, `margin_shift`, `dso_spike`
31
+
32
+ **Hard**: `channel_stuffing`, `cookie_jar`, `round_tripping`, `early_revenue`, `benfords_law`
33
+
34
+ ## Observation Space
35
+
36
+ Each observation contains:
37
+
38
+ - **company**: Industry, size, quarter count, fiscal year
39
+ - **quarters**: List of quarterly data with balance sheet, income statement, and cash flow (all amounts in integer cents)
40
+ - **footnotes**: Contextual notes about accounting policies
41
+ - **prior_flags**: Anomalies already flagged this episode
42
+ - **detail_response**: Sub-ledger data if requested
43
+ - **step_number / max_steps**: Episode progress
44
+
45
+ ## Task Descriptions
46
+
47
+ | Task | Quarters | Anomalies | Difficulty |
48
+ |------|----------|-----------|------------|
49
+ | **Easy** | 4 | 3-5 arithmetic/surface errors | Detectable via basic math checks |
50
+ | **Medium** | 6 | 4-7 ratio/trend anomalies | Requires cross-statement analysis |
51
+ | **Hard** | 8 | 5-10 coordinated fraud patterns | Requires multi-quarter temporal reasoning |
52
+
53
+ ## Reward Function
54
+
55
+ - `+1.0` per correctly flagged anomaly (exact type + location match)
56
+ - `+0.5` per partial match (correct location, wrong type)
57
+ - `-0.3` per false positive
58
+ - `-0.1` per `request_detail` call
59
+ - `1.2x` multiplier for flagging root cause before dependent anomaly
60
+ - `-0.5` penalty if max steps reached without submitting
61
+
62
+ ## Grading Formula
63
+
64
+ ```
65
+ Score = (Precision * 0.4) + (Recall * 0.4) + (Severity Accuracy * 0.2) + Dependency Bonus
66
+ ```
67
+
68
+ Score range: 0.0 to 1.0. Graders are fully deterministic.
69
+
70
+ ## Baseline Scores
71
+
72
+ | Task | GPT-4o | GPT-3.5 | Random |
73
+ |------|--------|---------|--------|
74
+ | Easy | 0.85-0.95 | 0.60-0.75 | 0.05-0.15 |
75
+ | Medium | 0.55-0.70 | 0.30-0.45 | 0.02-0.10 |
76
+ | Hard | 0.25-0.40 | 0.10-0.20 | 0.01-0.05 |
77
+
78
+ ## Setup & Usage
79
+
80
+ ### Local Development
81
+
82
+ ```bash
83
+ # Clone the repo
84
+ git clone <repo-url>
85
+ cd financial-anomaly-env
86
+
87
+ # Install dependencies
88
+ pip install -r requirements.txt
89
+
90
+ # Run tests
91
+ python tests/test_env.py
92
+
93
+ # Start the server
94
+ python server.py
95
+ ```
96
+
97
+ ### Docker
98
+
99
+ ```bash
100
+ # Build
101
+ docker build -t financial-anomaly-env .
102
+
103
+ # Run
104
+ docker run -p 7860:7860 financial-anomaly-env
105
+ ```
106
+
107
+ ### API Endpoints
108
+
109
+ - `GET /` - Environment info
110
+ - `GET /health` - Health check
111
+ - `POST /reset` - Reset environment (`{"task_id": "easy", "session_id": "my_session"}`)
112
+ - `POST /step` - Take action (`{"session_id": "my_session", "action": {...}}`)
113
+ - `POST /state` - Get current state (`{"session_id": "my_session"}`)
114
+ - `POST /score` - Get final score (`{"session_id": "my_session"}`)
115
+
116
+ ### Running the Baseline
117
+
118
+ ```bash
119
+ export OPENAI_API_KEY=your_key_here
120
+ python -m baseline.inference --url http://localhost:7860 --verbose
121
+ ```
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ financial-anomaly-env/
127
+ openenv.yaml # OpenEnv metadata
128
+ Dockerfile # Container config
129
+ server.py # FastAPI server
130
+ requirements.txt # Dependencies
131
+ src/
132
+ __init__.py
133
+ models.py # Pydantic models (Observation, Action, Reward, State)
134
+ environment.py # Core OpenEnv environment (step/reset/state)
135
+ generator.py # Synthetic financial data generator
136
+ anomaly_injector.py # Anomaly injection across 3 difficulty tiers
137
+ grader.py # Deterministic precision/recall grader
138
+ utils.py # Benford's Law, ratio calculators, validators
139
+ tasks/
140
+ task_easy.json # Easy task config + ground truth
141
+ task_medium.json # Medium task config
142
+ task_hard.json # Hard task config
143
+ baseline/
144
+ inference.py # OpenAI API baseline agent
145
+ tests/
146
+ test_env.py # Full test suite
147
+ ```
148
+
149
+ ## Deployment to Hugging Face Spaces
150
+
151
+ 1. Create a new Space on huggingface.co (Docker SDK)
152
+ 2. Tag the Space with `openenv`
153
+ 3. Push the project files
154
+ 4. The Space will build and serve the API on port 7860
155
+
156
+ ## License
157
+
158
+ MIT
159
+ =======
160
+ ---
161
+ title: Financial Hack
162
+ emoji: 🚀
163
+ colorFrom: gray
164
+ colorTo: pink
165
+ sdk: gradio
166
+ sdk_version: 6.11.0
167
+ app_file: app.py
168
+ pinned: false
169
+ ---
170
+
171
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
172
+ >>>>>>> aea3946240fbe94e7c387e597059eaf2613b6532
SETUP_GUIDE.md ADDED
@@ -0,0 +1,328 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Setup & Deployment Guide
2
+
3
+ Complete step-by-step instructions for running the Financial Statement Anomaly Detection environment locally, in Docker, and on Hugging Face Spaces.
4
+
5
+ ---
6
+
7
+ ## Prerequisites
8
+
9
+ - Python 3.11 or higher
10
+ - pip (Python package manager)
11
+ - Docker (for containerized deployment)
12
+ - Git (for version control and HF Spaces deployment)
13
+ - A Hugging Face account (for cloud deployment)
14
+ - An OpenAI API key (for running the baseline agent only)
15
+
16
+ ---
17
+
18
+ ## 1. Local Development Setup
19
+
20
+ ### 1.1 Clone and Install
21
+
22
+ ```bash
23
+ git clone <your-repo-url>
24
+ cd financial-anomaly-env
25
+
26
+ # Create virtual environment (recommended)
27
+ python -m venv venv
28
+ source venv/bin/activate # Linux/Mac
29
+ # venv\Scripts\activate # Windows
30
+
31
+ # Install dependencies
32
+ pip install -r requirements.txt
33
+ ```
34
+
35
+ ### 1.2 Verify Installation
36
+
37
+ ```bash
38
+ # Run the test suite (19 tests)
39
+ python tests/test_env.py
40
+ ```
41
+
42
+ Expected output:
43
+ ```
44
+ ============================================================
45
+ Financial Anomaly Detection - Test Suite
46
+ ============================================================
47
+
48
+ PASS: test_generator_produces_valid_data
49
+ PASS: test_generator_deterministic
50
+ PASS: test_anomaly_injection_easy
51
+ PASS: test_anomaly_injection_medium
52
+ PASS: test_anomaly_injection_hard
53
+ PASS: test_grader_perfect_score
54
+ PASS: test_grader_partial_credit
55
+ PASS: test_grader_false_positives
56
+ PASS: test_grader_empty_flags
57
+ PASS: test_grader_determinism (100 runs)
58
+ PASS: test_env_reset
59
+ PASS: test_env_step_flag
60
+ PASS: test_env_step_submit
61
+ PASS: test_env_step_request_detail
62
+ PASS: test_env_state
63
+ PASS: test_env_max_steps
64
+ PASS: test_env_full_episode (score=1.0)
65
+ PASS: test_utils_benfords
66
+ PASS: test_utils_leading_digit
67
+
68
+ Results: 19 passed, 0 failed, 19 total
69
+ All tests passed!
70
+ ```
71
+
72
+ ### 1.3 Start the API Server
73
+
74
+ ```bash
75
+ python server.py
76
+ ```
77
+
78
+ Server runs at `http://localhost:7860`. Verify with:
79
+
80
+ ```bash
81
+ curl http://localhost:7860/
82
+ # Returns: {"name":"financial-anomaly-detection","version":"1.0.0","status":"running","tasks":["easy","medium","hard"]}
83
+
84
+ curl http://localhost:7860/health
85
+ # Returns: {"status":"ok"}
86
+ ```
87
+
88
+ ### 1.4 Quick API Test
89
+
90
+ ```bash
91
+ # Reset with easy task
92
+ curl -X POST http://localhost:7860/reset \
93
+ -H "Content-Type: application/json" \
94
+ -d '{"task_id": "easy", "session_id": "demo"}'
95
+
96
+ # Flag an anomaly
97
+ curl -X POST http://localhost:7860/step \
98
+ -H "Content-Type: application/json" \
99
+ -d '{"session_id": "demo", "action": {"action_type": "flag_anomaly", "flag": {"line_item": "revenue", "quarter": "Q1 2022", "severity": 3, "anomaly_type": "arithmetic_error", "explanation": "Totals mismatch"}}}'
100
+
101
+ # Submit report
102
+ curl -X POST http://localhost:7860/step \
103
+ -H "Content-Type: application/json" \
104
+ -d '{"session_id": "demo", "action": {"action_type": "submit_report"}}'
105
+
106
+ # Get score
107
+ curl -X POST http://localhost:7860/score \
108
+ -H "Content-Type: application/json" \
109
+ -d '{"session_id": "demo"}'
110
+ ```
111
+
112
+ ---
113
+
114
+ ## 2. Docker Deployment
115
+
116
+ ### 2.1 Build the Image
117
+
118
+ ```bash
119
+ docker build -t financial-anomaly-env .
120
+ ```
121
+
122
+ ### 2.2 Run the Container
123
+
124
+ ```bash
125
+ docker run -p 7860:7860 financial-anomaly-env
126
+ ```
127
+
128
+ ### 2.3 Verify
129
+
130
+ ```bash
131
+ curl http://localhost:7860/health
132
+ # Returns: {"status":"ok"}
133
+ ```
134
+
135
+ ### 2.4 Run Tests Inside Container
136
+
137
+ ```bash
138
+ docker run financial-anomaly-env python tests/test_env.py
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 3. Hugging Face Spaces Deployment
144
+
145
+ ### 3.1 Create a New Space
146
+
147
+ 1. Go to https://huggingface.co/new-space
148
+ 2. Enter a space name (e.g., `financial-anomaly-detection`)
149
+ 3. Select **Docker** as the SDK
150
+ 4. Set visibility to **Public**
151
+ 5. Click **Create Space**
152
+
153
+ ### 3.2 Push Code to the Space
154
+
155
+ ```bash
156
+ # Add the HF Space as a remote
157
+ git remote add hf https://huggingface.co/spaces/<your-username>/financial-anomaly-detection
158
+
159
+ # Push
160
+ git push hf main
161
+ ```
162
+
163
+ ### 3.3 Add the OpenEnv Tag
164
+
165
+ Edit the Space's `README.md` metadata to include:
166
+
167
+ ```yaml
168
+ ---
169
+ title: Financial Statement Anomaly Detection
170
+ emoji: 📊
171
+ colorFrom: blue
172
+ colorTo: green
173
+ sdk: docker
174
+ app_port: 7860
175
+ tags:
176
+ - openenv
177
+ ---
178
+ ```
179
+
180
+ ### 3.4 Verify Deployment
181
+
182
+ Once the Space shows status **Running**:
183
+
184
+ ```bash
185
+ curl https://<your-username>-financial-anomaly-detection.hf.space/health
186
+ # Returns: {"status":"ok"}
187
+ ```
188
+
189
+ ---
190
+
191
+ ## 4. Running the Baseline Agent
192
+
193
+ ### 4.1 Set API Key
194
+
195
+ ```bash
196
+ export OPENAI_API_KEY=your_openai_api_key_here
197
+ ```
198
+
199
+ ### 4.2 Run Against Local Server
200
+
201
+ ```bash
202
+ # Start server first
203
+ python server.py &
204
+
205
+ # Run baseline
206
+ python -m baseline.inference --url http://localhost:7860 --verbose
207
+ ```
208
+
209
+ ### 4.3 Run Against HF Space
210
+
211
+ ```bash
212
+ python -m baseline.inference \
213
+ --url https://<your-username>-financial-anomaly-detection.hf.space \
214
+ --verbose
215
+ ```
216
+
217
+ ### 4.4 Output
218
+
219
+ Results are saved to `baseline_results.json`:
220
+
221
+ ```json
222
+ {
223
+ "model": "gpt-4o",
224
+ "timestamp": "2025-01-15T12:00:00Z",
225
+ "results": [
226
+ {"task_id": "easy", "score": 0.92, "precision": 0.85, "recall": 1.0, ...},
227
+ {"task_id": "medium", "score": 0.61, "precision": 0.70, "recall": 0.57, ...},
228
+ {"task_id": "hard", "score": 0.33, "precision": 0.45, "recall": 0.30, ...}
229
+ ]
230
+ }
231
+ ```
232
+
233
+ ### 4.5 Customize the Model
234
+
235
+ ```bash
236
+ # Use a different model
237
+ python -m baseline.inference --model gpt-4o-mini --url http://localhost:7860
238
+
239
+ # Run only specific tasks
240
+ python -m baseline.inference --tasks easy medium --url http://localhost:7860
241
+ ```
242
+
243
+ ---
244
+
245
+ ## 5. Using the Environment Programmatically
246
+
247
+ ### 5.1 Direct Python Usage (No Server)
248
+
249
+ ```python
250
+ from src import FinancialAnomalyEnv, Action, ActionType, AnomalyFlag, AnomalyType
251
+
252
+ # Create environment
253
+ env = FinancialAnomalyEnv(task_id="easy")
254
+
255
+ # Reset
256
+ obs = env.reset()
257
+ print(f"Company: {obs.company.name}")
258
+ print(f"Quarters: {len(obs.quarters)}")
259
+
260
+ # Flag an anomaly
261
+ action = Action(
262
+ action_type=ActionType.FLAG_ANOMALY,
263
+ flag=AnomalyFlag(
264
+ line_item="revenue",
265
+ quarter="Q1 2022",
266
+ severity=3,
267
+ anomaly_type=AnomalyType.ARITHMETIC_ERROR,
268
+ explanation="Column totals mismatch",
269
+ ),
270
+ )
271
+ obs, reward, done, info = env.step(action)
272
+ print(f"Reward: {reward.step_reward}")
273
+
274
+ # Submit report
275
+ obs, reward, done, info = env.step(
276
+ Action(action_type=ActionType.SUBMIT_REPORT)
277
+ )
278
+
279
+ # Get final score
280
+ score = env.get_final_score()
281
+ print(f"Score: {score['score']}")
282
+ ```
283
+
284
+ ### 5.2 Via HTTP API
285
+
286
+ ```python
287
+ import requests
288
+
289
+ BASE = "http://localhost:7860"
290
+
291
+ # Reset
292
+ r = requests.post(f"{BASE}/reset", json={"task_id": "medium", "session_id": "s1"})
293
+ obs = r.json()["observation"]
294
+
295
+ # Step
296
+ r = requests.post(f"{BASE}/step", json={
297
+ "session_id": "s1",
298
+ "action": {
299
+ "action_type": "flag_anomaly",
300
+ "flag": {
301
+ "line_item": "receivables",
302
+ "quarter": "Q3 2022",
303
+ "severity": 3,
304
+ "anomaly_type": "receivables_divergence",
305
+ "explanation": "Receivables growing faster than revenue"
306
+ }
307
+ }
308
+ })
309
+ print(r.json()["reward"])
310
+
311
+ # Score
312
+ r = requests.post(f"{BASE}/score", json={"session_id": "s1"})
313
+ print(r.json()["result"])
314
+ ```
315
+
316
+ ---
317
+
318
+ ## 6. Troubleshooting
319
+
320
+ | Issue | Solution |
321
+ |-------|----------|
322
+ | `ModuleNotFoundError: No module named 'src'` | Run from the project root directory (`financial-anomaly-env/`) |
323
+ | Server won't start on port 7860 | Check if another process uses port 7860: `lsof -i :7860` |
324
+ | Docker build fails | Verify Docker is running and you have internet access for pip |
325
+ | HF Space stuck on "Building" | Check the Space logs for build errors. Verify Dockerfile syntax. |
326
+ | Baseline script errors with "OPENAI_API_KEY not set" | Run `export OPENAI_API_KEY=your_key` before running the script |
327
+ | Tests fail on `test_generator_produces_valid_data` | Verify Python 3.11+. Run `python --version`. |
328
+ | Score always 0.0 | You're flagging the wrong line_item/quarter. Check ground truth with `env.get_ground_truth()` |
baseline/__init__.py ADDED
File without changes
baseline/inference.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Baseline inference script for the Financial Anomaly Detection environment.
3
+ Uses the OpenAI API to run a model against all 3 tasks and produce
4
+ reproducible baseline scores.
5
+
6
+ Usage:
7
+ export OPENAI_API_KEY=your_key_here
8
+ python -m baseline.inference --url http://localhost:7860
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ from typing import Any, Dict, List
19
+
20
+ try:
21
+ import openai
22
+ import requests
23
+ except ImportError:
24
+ print("Install dependencies: pip install openai requests")
25
+ sys.exit(1)
26
+
27
+
28
+ SYSTEM_PROMPT = """You are a forensic financial auditor. You will receive quarterly financial statements (balance sheet, income statement, cash flow statement) for a company.
29
+
30
+ Your task:
31
+ 1. Analyze the financial data for anomalies, errors, and suspicious patterns.
32
+ 2. Flag each anomaly you find with: line_item, quarter, severity (1-5), anomaly_type, and explanation.
33
+ 3. When done analyzing, submit your report.
34
+
35
+ Anomaly types you can flag:
36
+ - arithmetic_error: Column totals don't add up
37
+ - duplicate_entry: Identical values across quarters (statistically improbable)
38
+ - negative_value: Values that should be positive are negative
39
+ - impossible_change: Changes exceeding physically possible bounds
40
+ - percentage_error: Computed ratios don't match component values
41
+ - receivables_divergence: Receivables growing much faster than revenue
42
+ - inventory_turnover: Inventory changes without matching COGS movement
43
+ - cashflow_mismatch: Operating cash flow contradicts net income direction
44
+ - margin_shift: Gross margin shifts dramatically without explanation
45
+ - dso_spike: Days Sales Outstanding spikes while revenue stays flat
46
+ - channel_stuffing: Revenue spike + receivables balloon + next quarter drop
47
+ - cookie_jar: Expenses over-accrued in good quarters, released in bad ones
48
+ - round_tripping: Matching cash flows between investing and operating
49
+ - early_revenue: Revenue spike followed by multi-quarter decline
50
+ - benfords_law: Leading digit distribution of expenses violates Benford's Law
51
+
52
+ Respond ONLY with valid JSON. Each response should be one action:
53
+ - To flag an anomaly: {"action_type": "flag_anomaly", "flag": {"line_item": "...", "quarter": "...", "severity": N, "anomaly_type": "...", "explanation": "..."}}
54
+ - To request detail: {"action_type": "request_detail", "detail_line_item": "...", "detail_quarter": "..."}
55
+ - To submit report: {"action_type": "submit_report"}
56
+
57
+ Flag all anomalies you find, then submit your report."""
58
+
59
+
60
+ def format_financial_data(obs: Dict) -> str:
61
+ """Format observation data into readable text for the LLM."""
62
+ company = obs["company"]
63
+ lines = [
64
+ f"Company: {company['name']}",
65
+ f"Industry: {company['industry']}",
66
+ f"Size: {company['size']}",
67
+ f"Quarters: {company['num_quarters']}",
68
+ "",
69
+ ]
70
+
71
+ for q in obs["quarters"]:
72
+ lines.append(f"=== {q['quarter_label']} ===")
73
+ lines.append("BALANCE SHEET:")
74
+ lines.append(f" Cash: ${q['cash']/100:,.2f}")
75
+ lines.append(f" Receivables: ${q['receivables']/100:,.2f}")
76
+ lines.append(f" Inventory: ${q['inventory']/100:,.2f}")
77
+ lines.append(f" Other Current Assets: ${q['other_current_assets']/100:,.2f}")
78
+ lines.append(f" Total Current Assets: ${q['total_current_assets']/100:,.2f}")
79
+ lines.append(f" Fixed Assets: ${q['fixed_assets']/100:,.2f}")
80
+ lines.append(f" Total Assets: ${q['total_assets']/100:,.2f}")
81
+ lines.append(f" Payables: ${q['payables']/100:,.2f}")
82
+ lines.append(f" Short-term Debt: ${q['short_term_debt']/100:,.2f}")
83
+ lines.append(f" Total Current Liabilities: ${q['total_current_liabilities']/100:,.2f}")
84
+ lines.append(f" Long-term Debt: ${q['long_term_debt']/100:,.2f}")
85
+ lines.append(f" Total Liabilities: ${q['total_liabilities']/100:,.2f}")
86
+ lines.append(f" Equity: ${q['equity']/100:,.2f}")
87
+ lines.append("INCOME STATEMENT:")
88
+ lines.append(f" Revenue: ${q['revenue']/100:,.2f}")
89
+ lines.append(f" COGS: ${q['cogs']/100:,.2f}")
90
+ lines.append(f" Gross Profit: ${q['gross_profit']/100:,.2f}")
91
+ lines.append(f" Operating Expenses: ${q['operating_expenses']/100:,.2f}")
92
+ lines.append(f" Operating Income: ${q['operating_income']/100:,.2f}")
93
+ lines.append(f" Interest Expense: ${q['interest_expense']/100:,.2f}")
94
+ lines.append(f" Tax Expense: ${q['tax_expense']/100:,.2f}")
95
+ lines.append(f" Net Income: ${q['net_income']/100:,.2f}")
96
+ lines.append("CASH FLOW:")
97
+ lines.append(f" Operating: ${q['cf_operating']/100:,.2f}")
98
+ lines.append(f" Investing: ${q['cf_investing']/100:,.2f}")
99
+ lines.append(f" Financing: ${q['cf_financing']/100:,.2f}")
100
+ lines.append(f" Net Cash Change: ${q['net_cash_change']/100:,.2f}")
101
+ lines.append("")
102
+
103
+ if obs.get("footnotes"):
104
+ lines.append("FOOTNOTES:")
105
+ for fn in obs["footnotes"]:
106
+ lines.append(f" - {fn}")
107
+
108
+ return "\n".join(lines)
109
+
110
+
111
+ def run_baseline(
112
+ base_url: str,
113
+ task_id: str,
114
+ model: str = "gpt-4o",
115
+ verbose: bool = False,
116
+ ) -> Dict:
117
+ """
118
+ Run the baseline agent against one task.
119
+
120
+ Args:
121
+ base_url: URL of the environment API.
122
+ task_id: One of 'easy', 'medium', 'hard'.
123
+ model: OpenAI model to use.
124
+ verbose: Print step-by-step output.
125
+
126
+ Returns:
127
+ Dict with task_id, score, steps, flags.
128
+ """
129
+ client = openai.OpenAI()
130
+
131
+ # Reset environment
132
+ reset_resp = requests.post(
133
+ f"{base_url}/reset",
134
+ json={"task_id": task_id, "session_id": f"baseline_{task_id}"},
135
+ )
136
+ reset_resp.raise_for_status()
137
+ reset_data = reset_resp.json()
138
+ obs = reset_data["observation"]
139
+
140
+ # Format initial data
141
+ financial_text = format_financial_data(obs)
142
+ messages = [
143
+ {"role": "system", "content": SYSTEM_PROMPT},
144
+ {"role": "user", "content": f"Analyze these financial statements and flag all anomalies:\n\n{financial_text}"},
145
+ ]
146
+
147
+ step_count = 0
148
+ max_steps = obs.get("max_steps", 20)
149
+ all_flags = []
150
+
151
+ while step_count < max_steps:
152
+ # Call OpenAI
153
+ try:
154
+ response = client.chat.completions.create(
155
+ model=model,
156
+ messages=messages,
157
+ temperature=0.0, # deterministic
158
+ max_tokens=500,
159
+ )
160
+ except Exception as e:
161
+ print(f" OpenAI API error: {e}")
162
+ break
163
+
164
+ assistant_msg = response.choices[0].message.content.strip()
165
+ messages.append({"role": "assistant", "content": assistant_msg})
166
+
167
+ # Parse action
168
+ try:
169
+ # Handle markdown code blocks
170
+ clean = assistant_msg
171
+ if clean.startswith("```"):
172
+ clean = clean.split("\n", 1)[1] if "\n" in clean else clean[3:]
173
+ if clean.endswith("```"):
174
+ clean = clean[:-3]
175
+ action_data = json.loads(clean.strip())
176
+ except json.JSONDecodeError:
177
+ if verbose:
178
+ print(f" Step {step_count}: Failed to parse JSON, submitting report")
179
+ action_data = {"action_type": "submit_report"}
180
+
181
+ # Send to environment
182
+ step_resp = requests.post(
183
+ f"{base_url}/step",
184
+ json={"session_id": f"baseline_{task_id}", "action": action_data},
185
+ )
186
+ step_resp.raise_for_status()
187
+ step_data = step_resp.json()
188
+
189
+ step_count += 1
190
+ done = step_data["done"]
191
+
192
+ if verbose:
193
+ reward = step_data["reward"]["step_reward"]
194
+ info_msg = step_data["info"]["message"]
195
+ print(f" Step {step_count}: {action_data.get('action_type')} | reward={reward} | {info_msg}")
196
+
197
+ if action_data.get("action_type") == "flag_anomaly" and action_data.get("flag"):
198
+ all_flags.append(action_data["flag"])
199
+
200
+ if done:
201
+ break
202
+
203
+ # Add environment feedback to messages
204
+ feedback = f"Step reward: {step_data['reward']['step_reward']}. {step_data['info']['message']}. Steps remaining: {step_data['info']['steps_remaining']}."
205
+ if step_data["observation"].get("detail_response"):
206
+ feedback += f"\nDetail: {json.dumps(step_data['observation']['detail_response'])}"
207
+ messages.append({"role": "user", "content": feedback + "\n\nContinue analyzing or submit your report if done."})
208
+
209
+ # Get final score
210
+ score_resp = requests.post(
211
+ f"{base_url}/score",
212
+ json={"session_id": f"baseline_{task_id}"},
213
+ )
214
+ score_resp.raise_for_status()
215
+ result = score_resp.json()["result"]
216
+
217
+ return {
218
+ "task_id": task_id,
219
+ "steps": step_count,
220
+ "flags_submitted": len(all_flags),
221
+ "score": result["score"],
222
+ "precision": result["precision"],
223
+ "recall": result["recall"],
224
+ "severity_accuracy": result.get("severity_accuracy", 0),
225
+ "total_anomalies": result.get("total_anomalies", 0),
226
+ "false_positives": result.get("false_positives", 0),
227
+ }
228
+
229
+
230
+ def main():
231
+ parser = argparse.ArgumentParser(description="Baseline inference for Financial Anomaly Detection")
232
+ parser.add_argument("--url", default="http://localhost:7860", help="Environment API URL")
233
+ parser.add_argument("--model", default="gpt-4o", help="OpenAI model to use")
234
+ parser.add_argument("--tasks", nargs="+", default=["easy", "medium", "hard"], help="Tasks to run")
235
+ parser.add_argument("--verbose", action="store_true", help="Print step-by-step output")
236
+ parser.add_argument("--output", default="baseline_results.json", help="Output file for results")
237
+ args = parser.parse_args()
238
+
239
+ api_key = os.environ.get("OPENAI_API_KEY")
240
+ if not api_key:
241
+ print("ERROR: OPENAI_API_KEY environment variable not set.")
242
+ sys.exit(1)
243
+
244
+ results = []
245
+ for task_id in args.tasks:
246
+ print(f"\nRunning baseline on task: {task_id}")
247
+ print("-" * 40)
248
+ result = run_baseline(
249
+ base_url=args.url,
250
+ task_id=task_id,
251
+ model=args.model,
252
+ verbose=args.verbose,
253
+ )
254
+ results.append(result)
255
+ print(f" Score: {result['score']}")
256
+ print(f" Precision: {result['precision']}")
257
+ print(f" Recall: {result['recall']}")
258
+ print(f" Flags: {result['flags_submitted']} | Anomalies: {result['total_anomalies']} | FP: {result['false_positives']}")
259
+
260
+ # Save results
261
+ output = {
262
+ "model": args.model,
263
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ"),
264
+ "results": results,
265
+ }
266
+ with open(args.output, "w") as f:
267
+ json.dump(output, f, indent=2)
268
+ print(f"\nResults saved to {args.output}")
269
+
270
+
271
+ if __name__ == "__main__":
272
+ main()
openenv.yaml ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: financial-anomaly-detection
2
+ version: "1.0.0"
3
+ description: >
4
+ Financial Statement Anomaly Detection environment. The agent receives
5
+ quarterly financial statements (balance sheet, income statement, cash flow)
6
+ and must identify injected anomalies ranging from arithmetic errors to
7
+ coordinated fraud schemes (channel stuffing, cookie jar reserves,
8
+ round-tripping). Simulates real-world forensic accounting and audit tasks.
9
+
10
+ tags:
11
+ - openenv
12
+ - finance
13
+ - auditing
14
+ - anomaly-detection
15
+
16
+ author: OpenEnv Hackathon Submission
17
+
18
+ environment:
19
+ entry_point: src.environment:FinancialAnomalyEnv
20
+ api_server: server:app
21
+
22
+ observation_space:
23
+ type: structured
24
+ model: src.models:Observation
25
+ description: >
26
+ Company metadata, quarterly financial data (balance sheet, income statement,
27
+ cash flow), footnotes, prior flags, and optional sub-ledger detail responses.
28
+
29
+ action_space:
30
+ type: structured
31
+ model: src.models:Action
32
+ actions:
33
+ - flag_anomaly: Flag a suspected anomaly with line_item, quarter, severity, type, explanation
34
+ - request_detail: Request sub-ledger breakdown of a specific line item (costs -0.1 reward)
35
+ - submit_report: Finalize the audit and trigger grading
36
+
37
+ reward:
38
+ type: continuous
39
+ range: [-0.5, 1.2]
40
+ description: >
41
+ Per-step rewards: +1.0 correct flag, +0.5 partial match, -0.3 false positive,
42
+ -0.1 per detail request. Dependency ordering bonus (1.2x). Max steps penalty (-0.5).
43
+
44
+ tasks:
45
+ - id: easy
46
+ description: >
47
+ Detect arithmetic errors, duplicate entries, and obvious misstatements
48
+ in 4 quarters of financial data. 3-5 surface-level anomalies.
49
+ difficulty: easy
50
+ expected_score_range: [0.05, 0.95]
51
+
52
+ - id: medium
53
+ description: >
54
+ Detect ratio anomalies, trend deviations, and cross-statement
55
+ inconsistencies across 6 quarters. 4-7 anomalies including receivables
56
+ divergence, inventory turnover spikes, and cash flow mismatches.
57
+ difficulty: medium
58
+ expected_score_range: [0.02, 0.70]
59
+
60
+ - id: hard
61
+ description: >
62
+ Detect coordinated manipulation patterns including channel stuffing,
63
+ cookie jar reserves, round-tripping, early revenue recognition, and
64
+ Benford's Law violations across 8 quarters. 5-10 anomalies with
65
+ causal dependencies.
66
+ difficulty: hard
67
+ expected_score_range: [0.01, 0.40]
68
+
69
+ baseline:
70
+ script: baseline/inference.py
71
+ model: gpt-4o
72
+ credentials:
73
+ - OPENAI_API_KEY
74
+
75
+ deployment:
76
+ platform: huggingface-spaces
77
+ sdk: docker
78
+ port: 7860
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi==0.115.6
2
+ uvicorn==0.34.0
3
+ pydantic==2.10.4
4
+ requests==2.32.3
5
+ openai==1.58.1
server.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI server exposing the Financial Anomaly Detection environment
3
+ via REST API endpoints matching the OpenEnv specification.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Dict
9
+
10
+ from fastapi import FastAPI, HTTPException
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from pydantic import BaseModel
13
+
14
+ from src.environment import FinancialAnomalyEnv
15
+ from src.models import Action, Observation, Reward, Info, State
16
+
17
+ app = FastAPI(
18
+ title="Financial Statement Anomaly Detection",
19
+ description="OpenEnv environment for training agents to audit financial statements",
20
+ version="1.0.0",
21
+ )
22
+
23
+ app.add_middleware(
24
+ CORSMiddleware,
25
+ allow_origins=["*"],
26
+ allow_methods=["*"],
27
+ allow_headers=["*"],
28
+ )
29
+
30
+ # Active environment instances keyed by session_id
31
+ _envs: Dict[str, FinancialAnomalyEnv] = {}
32
+
33
+
34
+ class ResetRequest(BaseModel):
35
+ task_id: str = "easy"
36
+ session_id: str = "default"
37
+ max_steps: int = 20
38
+
39
+
40
+ class StepRequest(BaseModel):
41
+ session_id: str = "default"
42
+ action: Action
43
+
44
+
45
+ class StateRequest(BaseModel):
46
+ session_id: str = "default"
47
+
48
+
49
+ class ScoreRequest(BaseModel):
50
+ session_id: str = "default"
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Health & info
55
+ # ---------------------------------------------------------------------------
56
+
57
+ @app.get("/")
58
+ def root():
59
+ return {
60
+ "name": "financial-anomaly-detection",
61
+ "version": "1.0.0",
62
+ "status": "running",
63
+ "tasks": ["easy", "medium", "hard"],
64
+ }
65
+
66
+
67
+ @app.get("/health")
68
+ def health():
69
+ return {"status": "ok"}
70
+
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # OpenEnv API
74
+ # ---------------------------------------------------------------------------
75
+
76
+ @app.post("/reset")
77
+ def reset(req: ResetRequest) -> Dict:
78
+ """Create or reset an environment instance and return the initial observation."""
79
+ if req.task_id not in ("easy", "medium", "hard"):
80
+ raise HTTPException(status_code=400, detail=f"Invalid task_id: {req.task_id}")
81
+
82
+ env = FinancialAnomalyEnv(task_id=req.task_id, max_steps=req.max_steps)
83
+ obs = env.reset()
84
+ _envs[req.session_id] = env
85
+
86
+ return {"observation": obs.model_dump(), "done": False}
87
+
88
+
89
+ @app.post("/step")
90
+ def step(req: StepRequest) -> Dict:
91
+ """Process one agent action and return the result."""
92
+ env = _envs.get(req.session_id)
93
+ if env is None:
94
+ raise HTTPException(
95
+ status_code=404,
96
+ detail=f"No active session '{req.session_id}'. Call /reset first.",
97
+ )
98
+
99
+ obs, reward, done, info = env.step(req.action)
100
+ return {
101
+ "observation": obs.model_dump(),
102
+ "reward": reward.model_dump(),
103
+ "done": done,
104
+ "info": info.model_dump(),
105
+ }
106
+
107
+
108
+ @app.post("/state")
109
+ def get_state(req: StateRequest) -> Dict:
110
+ """Return the current internal state of the episode."""
111
+ env = _envs.get(req.session_id)
112
+ if env is None:
113
+ raise HTTPException(
114
+ status_code=404,
115
+ detail=f"No active session '{req.session_id}'. Call /reset first.",
116
+ )
117
+ return {"state": env.state().model_dump()}
118
+
119
+
120
+ @app.post("/score")
121
+ def get_score(req: ScoreRequest) -> Dict:
122
+ """Get the final grader score for the current episode."""
123
+ env = _envs.get(req.session_id)
124
+ if env is None:
125
+ raise HTTPException(
126
+ status_code=404,
127
+ detail=f"No active session '{req.session_id}'. Call /reset first.",
128
+ )
129
+ return {"result": env.get_final_score()}
130
+
131
+
132
+ if __name__ == "__main__":
133
+ import uvicorn
134
+ uvicorn.run(app, host="0.0.0.0", port=7860)
src/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Financial Statement Anomaly Detection - OpenEnv Environment."""
2
+
3
+ from .environment import FinancialAnomalyEnv
4
+ from .models import (
5
+ Action,
6
+ ActionType,
7
+ AnomalyFlag,
8
+ AnomalyType,
9
+ Observation,
10
+ Reward,
11
+ State,
12
+ )
13
+
14
+ __all__ = [
15
+ "FinancialAnomalyEnv",
16
+ "Action",
17
+ "ActionType",
18
+ "AnomalyFlag",
19
+ "AnomalyType",
20
+ "Observation",
21
+ "Reward",
22
+ "State",
23
+ ]
src/anomaly_injector.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Anomaly injection module. Takes clean financial data and injects specific
3
+ anomaly types at configurable difficulty levels. Records ground truth for
4
+ the grader.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import random
10
+ from typing import List, Tuple
11
+
12
+ from .models import (
13
+ AnomalyType,
14
+ GroundTruthAnomaly,
15
+ QuarterData,
16
+ )
17
+
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # Easy tier injectors
21
+ # ---------------------------------------------------------------------------
22
+
23
+ def _inject_arithmetic_error(
24
+ quarters: List[QuarterData], rng: random.Random
25
+ ) -> List[GroundTruthAnomaly]:
26
+ """Make total_current_assets != sum of components."""
27
+ idx = rng.randint(0, len(quarters) - 1)
28
+ q = quarters[idx]
29
+ offset = rng.choice([1, -1]) * rng.randint(50000, 500000)
30
+ q.total_current_assets += offset
31
+ q.total_assets += offset # propagate so balance sheet still "looks" valid
32
+ q.equity += offset
33
+ return [GroundTruthAnomaly(
34
+ anomaly_id=f"arith_{idx}",
35
+ line_item="total_current_assets",
36
+ quarter=q.quarter_label,
37
+ severity=2,
38
+ anomaly_type=AnomalyType.ARITHMETIC_ERROR,
39
+ description="total_current_assets does not equal sum of cash + receivables + inventory + other_current_assets",
40
+ )]
41
+
42
+
43
+ def _inject_duplicate_entry(
44
+ quarters: List[QuarterData], rng: random.Random
45
+ ) -> List[GroundTruthAnomaly]:
46
+ """Make two consecutive quarters have identical revenue (statistically improbable)."""
47
+ if len(quarters) < 2:
48
+ return []
49
+ idx = rng.randint(0, len(quarters) - 2)
50
+ quarters[idx + 1].revenue = quarters[idx].revenue
51
+ quarters[idx + 1].gross_profit = quarters[idx + 1].revenue - quarters[idx + 1].cogs
52
+ return [GroundTruthAnomaly(
53
+ anomaly_id=f"dup_{idx}",
54
+ line_item="revenue",
55
+ quarter=quarters[idx + 1].quarter_label,
56
+ severity=2,
57
+ anomaly_type=AnomalyType.DUPLICATE_ENTRY,
58
+ description="Revenue is identical to prior quarter (statistically improbable)",
59
+ )]
60
+
61
+
62
+ def _inject_negative_value(
63
+ quarters: List[QuarterData], rng: random.Random
64
+ ) -> List[GroundTruthAnomaly]:
65
+ """Make inventory or receivables negative."""
66
+ idx = rng.randint(0, len(quarters) - 1)
67
+ q = quarters[idx]
68
+ field = rng.choice(["inventory", "receivables"])
69
+ current_val = getattr(q, field)
70
+ setattr(q, field, -abs(current_val))
71
+ return [GroundTruthAnomaly(
72
+ anomaly_id=f"neg_{idx}",
73
+ line_item=field,
74
+ quarter=q.quarter_label,
75
+ severity=1,
76
+ anomaly_type=AnomalyType.NEGATIVE_VALUE,
77
+ description=f"{field} has a negative value which is not possible",
78
+ )]
79
+
80
+
81
+ def _inject_impossible_change(
82
+ quarters: List[QuarterData], rng: random.Random
83
+ ) -> List[GroundTruthAnomaly]:
84
+ """Revenue jumps 500%+ in one quarter."""
85
+ if len(quarters) < 2:
86
+ return []
87
+ idx = rng.randint(1, len(quarters) - 1)
88
+ q = quarters[idx]
89
+ q.revenue = q.revenue * rng.randint(5, 10)
90
+ q.gross_profit = q.revenue - q.cogs
91
+ q.operating_income = q.gross_profit - q.operating_expenses
92
+ return [GroundTruthAnomaly(
93
+ anomaly_id=f"imp_{idx}",
94
+ line_item="revenue",
95
+ quarter=q.quarter_label,
96
+ severity=3,
97
+ anomaly_type=AnomalyType.IMPOSSIBLE_CHANGE,
98
+ description="Revenue increased by 500%+ in a single quarter without explanation",
99
+ )]
100
+
101
+
102
+ def _inject_percentage_error(
103
+ quarters: List[QuarterData], rng: random.Random
104
+ ) -> List[GroundTruthAnomaly]:
105
+ """gross_profit != revenue - cogs."""
106
+ idx = rng.randint(0, len(quarters) - 1)
107
+ q = quarters[idx]
108
+ error = rng.choice([1, -1]) * rng.randint(100000, 800000)
109
+ q.gross_profit += error
110
+ q.operating_income = q.gross_profit - q.operating_expenses
111
+ return [GroundTruthAnomaly(
112
+ anomaly_id=f"pct_{idx}",
113
+ line_item="gross_profit",
114
+ quarter=q.quarter_label,
115
+ severity=2,
116
+ anomaly_type=AnomalyType.PERCENTAGE_ERROR,
117
+ description="gross_profit does not equal revenue minus cogs",
118
+ )]
119
+
120
+
121
+ # ---------------------------------------------------------------------------
122
+ # Medium tier injectors
123
+ # ---------------------------------------------------------------------------
124
+
125
+ def _inject_receivables_divergence(
126
+ quarters: List[QuarterData], rng: random.Random
127
+ ) -> List[GroundTruthAnomaly]:
128
+ """Receivables grow 3x faster than revenue over several quarters."""
129
+ if len(quarters) < 3:
130
+ return []
131
+ anomalies = []
132
+ start = rng.randint(0, max(0, len(quarters) - 3))
133
+ for i in range(start + 1, min(start + 3, len(quarters))):
134
+ q = quarters[i]
135
+ q.receivables = int(q.receivables * rng.uniform(2.5, 3.5))
136
+ q.total_current_assets = q.cash + q.receivables + q.inventory + q.other_current_assets
137
+ q.total_assets = q.total_current_assets + q.fixed_assets
138
+ q.equity = q.total_assets - q.total_liabilities
139
+ anomalies.append(GroundTruthAnomaly(
140
+ anomaly_id=f"recv_{i}",
141
+ line_item="receivables",
142
+ quarter=q.quarter_label,
143
+ severity=3,
144
+ anomaly_type=AnomalyType.RECEIVABLES_DIVERGENCE,
145
+ description="Receivables growing 3x faster than revenue trend",
146
+ ))
147
+ return anomalies
148
+
149
+
150
+ def _inject_inventory_turnover(
151
+ quarters: List[QuarterData], rng: random.Random
152
+ ) -> List[GroundTruthAnomaly]:
153
+ """Inventory spikes without corresponding COGS change."""
154
+ idx = rng.randint(1, len(quarters) - 1)
155
+ q = quarters[idx]
156
+ q.inventory = int(q.inventory * rng.uniform(3.0, 5.0))
157
+ q.total_current_assets = q.cash + q.receivables + q.inventory + q.other_current_assets
158
+ q.total_assets = q.total_current_assets + q.fixed_assets
159
+ q.equity = q.total_assets - q.total_liabilities
160
+ return [GroundTruthAnomaly(
161
+ anomaly_id=f"invt_{idx}",
162
+ line_item="inventory",
163
+ quarter=q.quarter_label,
164
+ severity=3,
165
+ anomaly_type=AnomalyType.INVENTORY_TURNOVER,
166
+ description="Inventory spiked without matching COGS movement",
167
+ )]
168
+
169
+
170
+ def _inject_cashflow_mismatch(
171
+ quarters: List[QuarterData], rng: random.Random
172
+ ) -> List[GroundTruthAnomaly]:
173
+ """Operating cash flow moves opposite to net income for 2+ quarters."""
174
+ anomalies = []
175
+ start = rng.randint(0, max(0, len(quarters) - 2))
176
+ for i in range(start, min(start + 2, len(quarters))):
177
+ q = quarters[i]
178
+ if q.net_income > 0:
179
+ q.cf_operating = -abs(q.cf_operating)
180
+ else:
181
+ q.cf_operating = abs(q.cf_operating) if q.cf_operating < 0 else q.cf_operating * 2
182
+ q.net_cash_change = q.cf_operating + q.cf_investing + q.cf_financing
183
+ anomalies.append(GroundTruthAnomaly(
184
+ anomaly_id=f"cfm_{i}",
185
+ line_item="cf_operating",
186
+ quarter=q.quarter_label,
187
+ severity=4,
188
+ anomaly_type=AnomalyType.CASHFLOW_MISMATCH,
189
+ description="Operating cash flow direction contradicts net income",
190
+ ))
191
+ return anomalies
192
+
193
+
194
+ def _inject_margin_shift(
195
+ quarters: List[QuarterData], rng: random.Random
196
+ ) -> List[GroundTruthAnomaly]:
197
+ """Gross margin shifts >10% in one quarter without footnote."""
198
+ if len(quarters) < 2:
199
+ return []
200
+ idx = rng.randint(1, len(quarters) - 1)
201
+ q = quarters[idx]
202
+ # Slash COGS to inflate margin dramatically
203
+ q.cogs = int(q.cogs * rng.uniform(0.4, 0.6))
204
+ q.gross_profit = q.revenue - q.cogs
205
+ q.operating_income = q.gross_profit - q.operating_expenses
206
+ return [GroundTruthAnomaly(
207
+ anomaly_id=f"marg_{idx}",
208
+ line_item="gross_profit",
209
+ quarter=q.quarter_label,
210
+ severity=3,
211
+ anomaly_type=AnomalyType.MARGIN_SHIFT,
212
+ description="Gross margin shifted >10% from prior quarter without explanation",
213
+ )]
214
+
215
+
216
+ def _inject_dso_spike(
217
+ quarters: List[QuarterData], rng: random.Random
218
+ ) -> List[GroundTruthAnomaly]:
219
+ """DSO increases 40%+ while revenue stays flat."""
220
+ if len(quarters) < 2:
221
+ return []
222
+ idx = rng.randint(1, len(quarters) - 1)
223
+ q = quarters[idx]
224
+ q.receivables = int(q.receivables * rng.uniform(1.8, 2.5))
225
+ q.total_current_assets = q.cash + q.receivables + q.inventory + q.other_current_assets
226
+ q.total_assets = q.total_current_assets + q.fixed_assets
227
+ q.equity = q.total_assets - q.total_liabilities
228
+ return [GroundTruthAnomaly(
229
+ anomaly_id=f"dso_{idx}",
230
+ line_item="receivables",
231
+ quarter=q.quarter_label,
232
+ severity=3,
233
+ anomaly_type=AnomalyType.DSO_SPIKE,
234
+ description="DSO spiked 40%+ while revenue remained flat",
235
+ )]
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # Hard tier injectors
240
+ # ---------------------------------------------------------------------------
241
+
242
+ def _inject_channel_stuffing(
243
+ quarters: List[QuarterData], rng: random.Random
244
+ ) -> List[GroundTruthAnomaly]:
245
+ """Q4 revenue spike + receivables balloon + next Q1 implied returns."""
246
+ if len(quarters) < 4:
247
+ return []
248
+ # Find a Q4 or use last-2 quarters
249
+ q4_idx = len(quarters) - 2
250
+ q1_idx = len(quarters) - 1
251
+ q4 = quarters[q4_idx]
252
+ q1 = quarters[q1_idx]
253
+
254
+ # Inflate Q4 revenue
255
+ q4.revenue = int(q4.revenue * rng.uniform(1.6, 2.0))
256
+ q4.gross_profit = q4.revenue - q4.cogs
257
+ q4.operating_income = q4.gross_profit - q4.operating_expenses
258
+ q4.receivables = int(q4.receivables * rng.uniform(2.5, 3.5))
259
+ q4.total_current_assets = q4.cash + q4.receivables + q4.inventory + q4.other_current_assets
260
+ q4.total_assets = q4.total_current_assets + q4.fixed_assets
261
+ q4.equity = q4.total_assets - q4.total_liabilities
262
+
263
+ # Q1 revenue drops + receivables stay elevated
264
+ q1.revenue = int(q1.revenue * rng.uniform(0.5, 0.7))
265
+ q1.gross_profit = q1.revenue - q1.cogs
266
+ q1.operating_income = q1.gross_profit - q1.operating_expenses
267
+
268
+ return [
269
+ GroundTruthAnomaly(
270
+ anomaly_id=f"chstf_rev_{q4_idx}",
271
+ line_item="revenue",
272
+ quarter=q4.quarter_label,
273
+ severity=5,
274
+ anomaly_type=AnomalyType.CHANNEL_STUFFING,
275
+ description="Revenue spike with matching receivables balloon (channel stuffing pattern)",
276
+ ),
277
+ GroundTruthAnomaly(
278
+ anomaly_id=f"chstf_recv_{q4_idx}",
279
+ line_item="receivables",
280
+ quarter=q4.quarter_label,
281
+ severity=5,
282
+ anomaly_type=AnomalyType.CHANNEL_STUFFING,
283
+ description="Receivables ballooned alongside revenue spike",
284
+ depends_on=f"chstf_rev_{q4_idx}",
285
+ ),
286
+ GroundTruthAnomaly(
287
+ anomaly_id=f"chstf_drop_{q1_idx}",
288
+ line_item="revenue",
289
+ quarter=q1.quarter_label,
290
+ severity=4,
291
+ anomaly_type=AnomalyType.CHANNEL_STUFFING,
292
+ description="Revenue collapse following prior quarter spike (returns/reversal)",
293
+ depends_on=f"chstf_rev_{q4_idx}",
294
+ ),
295
+ ]
296
+
297
+
298
+ def _inject_cookie_jar(
299
+ quarters: List[QuarterData], rng: random.Random
300
+ ) -> List[GroundTruthAnomaly]:
301
+ """Over-accrue expenses in good quarters, release in bad quarters."""
302
+ if len(quarters) < 4:
303
+ return []
304
+ anomalies = []
305
+ # Find highest and lowest NI quarters
306
+ sorted_idx = sorted(range(len(quarters)), key=lambda i: quarters[i].net_income, reverse=True)
307
+ good_q = sorted_idx[0]
308
+ bad_q = sorted_idx[-1]
309
+
310
+ # Over-accrue in good quarter
311
+ quarters[good_q].operating_expenses = int(quarters[good_q].operating_expenses * 1.4)
312
+ quarters[good_q].operating_income = quarters[good_q].gross_profit - quarters[good_q].operating_expenses
313
+ quarters[good_q].net_income = int(quarters[good_q].net_income * 0.7)
314
+ anomalies.append(GroundTruthAnomaly(
315
+ anomaly_id=f"cj_over_{good_q}",
316
+ line_item="operating_expenses",
317
+ quarter=quarters[good_q].quarter_label,
318
+ severity=5,
319
+ anomaly_type=AnomalyType.COOKIE_JAR,
320
+ description="Operating expenses over-accrued in strong quarter (cookie jar reserve)",
321
+ ))
322
+
323
+ # Release in bad quarter
324
+ quarters[bad_q].operating_expenses = int(quarters[bad_q].operating_expenses * 0.5)
325
+ quarters[bad_q].operating_income = quarters[bad_q].gross_profit - quarters[bad_q].operating_expenses
326
+ quarters[bad_q].net_income = int(quarters[bad_q].net_income * 1.5)
327
+ anomalies.append(GroundTruthAnomaly(
328
+ anomaly_id=f"cj_release_{bad_q}",
329
+ line_item="operating_expenses",
330
+ quarter=quarters[bad_q].quarter_label,
331
+ severity=5,
332
+ anomaly_type=AnomalyType.COOKIE_JAR,
333
+ description="Operating expenses released in weak quarter to smooth earnings",
334
+ depends_on=f"cj_over_{good_q}",
335
+ ))
336
+ return anomalies
337
+
338
+
339
+ def _inject_round_tripping(
340
+ quarters: List[QuarterData], rng: random.Random
341
+ ) -> List[GroundTruthAnomaly]:
342
+ """Cash outflow in investing + matching inflow in operating."""
343
+ idx = rng.randint(0, len(quarters) - 1)
344
+ q = quarters[idx]
345
+ amount = abs(q.cf_operating) // 2
346
+ q.cf_investing -= amount
347
+ q.cf_operating += amount
348
+ q.net_cash_change = q.cf_operating + q.cf_investing + q.cf_financing
349
+ return [GroundTruthAnomaly(
350
+ anomaly_id=f"rt_{idx}",
351
+ line_item="cf_operating",
352
+ quarter=q.quarter_label,
353
+ severity=5,
354
+ anomaly_type=AnomalyType.ROUND_TRIPPING,
355
+ description="Suspicious matching cash flows: outflow in investing mirrors inflow in operating",
356
+ )]
357
+
358
+
359
+ def _inject_early_revenue(
360
+ quarters: List[QuarterData], rng: random.Random
361
+ ) -> List[GroundTruthAnomaly]:
362
+ """Revenue recognized upfront from multi-year contract."""
363
+ if len(quarters) < 3:
364
+ return []
365
+ idx = rng.randint(0, len(quarters) - 3)
366
+ q = quarters[idx]
367
+ # Triple revenue in one quarter
368
+ boost = int(q.revenue * rng.uniform(1.5, 2.5))
369
+ q.revenue += boost
370
+ q.gross_profit = q.revenue - q.cogs
371
+ q.operating_income = q.gross_profit - q.operating_expenses
372
+ # But next quarters drop
373
+ for j in range(idx + 1, min(idx + 3, len(quarters))):
374
+ quarters[j].revenue = int(quarters[j].revenue * rng.uniform(0.5, 0.7))
375
+ quarters[j].gross_profit = quarters[j].revenue - quarters[j].cogs
376
+ quarters[j].operating_income = quarters[j].gross_profit - quarters[j].operating_expenses
377
+ return [GroundTruthAnomaly(
378
+ anomaly_id=f"erev_{idx}",
379
+ line_item="revenue",
380
+ quarter=q.quarter_label,
381
+ severity=5,
382
+ anomaly_type=AnomalyType.EARLY_REVENUE,
383
+ description="Revenue spike followed by multi-quarter decline (possible early recognition)",
384
+ )]
385
+
386
+
387
+ def _inject_benfords_violation(
388
+ quarters: List[QuarterData], rng: random.Random
389
+ ) -> List[GroundTruthAnomaly]:
390
+ """Make expense line items violate Benford's Law by forcing leading digits."""
391
+ anomalies = []
392
+ for idx in range(len(quarters)):
393
+ q = quarters[idx]
394
+ # Force all expenses to start with 5 or 6 (unlikely under Benford's)
395
+ for field in ["operating_expenses", "cogs"]:
396
+ val = getattr(q, field)
397
+ if val > 0:
398
+ s = str(val)
399
+ forced_digit = str(rng.choice([5, 6]))
400
+ new_val = int(forced_digit + s[1:])
401
+ setattr(q, field, new_val)
402
+ q.gross_profit = q.revenue - q.cogs
403
+ q.operating_income = q.gross_profit - q.operating_expenses
404
+ # Single anomaly covering the pattern
405
+ anomalies.append(GroundTruthAnomaly(
406
+ anomaly_id="benford_all",
407
+ line_item="operating_expenses",
408
+ quarter="ALL",
409
+ severity=4,
410
+ anomaly_type=AnomalyType.BENFORDS_LAW,
411
+ description="Expense line items violate Benford's Law distribution across all quarters",
412
+ ))
413
+ return anomalies
414
+
415
+
416
+ # ---------------------------------------------------------------------------
417
+ # Injection dispatcher
418
+ # ---------------------------------------------------------------------------
419
+
420
+ EASY_INJECTORS = [
421
+ _inject_arithmetic_error,
422
+ _inject_duplicate_entry,
423
+ _inject_negative_value,
424
+ _inject_impossible_change,
425
+ _inject_percentage_error,
426
+ ]
427
+
428
+ MEDIUM_INJECTORS = [
429
+ _inject_receivables_divergence,
430
+ _inject_inventory_turnover,
431
+ _inject_cashflow_mismatch,
432
+ _inject_margin_shift,
433
+ _inject_dso_spike,
434
+ ]
435
+
436
+ HARD_INJECTORS = [
437
+ _inject_channel_stuffing,
438
+ _inject_cookie_jar,
439
+ _inject_round_tripping,
440
+ _inject_early_revenue,
441
+ _inject_benfords_violation,
442
+ ]
443
+
444
+
445
+ def inject_anomalies(
446
+ quarters: List[QuarterData],
447
+ difficulty: str,
448
+ seed: int,
449
+ count: int | None = None,
450
+ ) -> Tuple[List[QuarterData], List[GroundTruthAnomaly]]:
451
+ """
452
+ Inject anomalies into a copy of the quarterly data.
453
+
454
+ Args:
455
+ quarters: List of clean QuarterData.
456
+ difficulty: One of 'easy', 'medium', 'hard'.
457
+ seed: RNG seed for reproducibility.
458
+ count: Override number of anomaly types to inject.
459
+
460
+ Returns:
461
+ (modified quarters, list of ground truth anomalies)
462
+ """
463
+ rng = random.Random(seed)
464
+ all_anomalies: List[GroundTruthAnomaly] = []
465
+
466
+ if difficulty == "easy":
467
+ pool = EASY_INJECTORS
468
+ n = count or rng.randint(3, 4)
469
+ elif difficulty == "medium":
470
+ pool = EASY_INJECTORS + MEDIUM_INJECTORS
471
+ n = count or rng.randint(4, 6)
472
+ elif difficulty == "hard":
473
+ pool = EASY_INJECTORS + MEDIUM_INJECTORS + HARD_INJECTORS
474
+ n = count or rng.randint(5, 8)
475
+ else:
476
+ raise ValueError(f"Unknown difficulty: {difficulty}")
477
+
478
+ chosen = rng.sample(pool, min(n, len(pool)))
479
+ for injector in chosen:
480
+ result = injector(quarters, rng)
481
+ all_anomalies.extend(result)
482
+
483
+ return quarters, all_anomalies
src/environment.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core OpenEnv environment for Financial Statement Anomaly Detection.
3
+ Implements step(), reset(), state() per the OpenEnv specification.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import json
10
+ import random
11
+ from pathlib import Path
12
+ from typing import Any, Dict, List, Optional, Tuple
13
+
14
+ from .anomaly_injector import inject_anomalies
15
+ from .generator import generate_company_data
16
+ from .grader import grade
17
+ from .models import (
18
+ Action,
19
+ ActionType,
20
+ AnomalyFlag,
21
+ CompanyMetadata,
22
+ GroundTruthAnomaly,
23
+ Info,
24
+ Observation,
25
+ QuarterData,
26
+ Reward,
27
+ State,
28
+ )
29
+
30
+
31
+ TASKS_DIR = Path(__file__).parent.parent / "tasks"
32
+
33
+
34
+ class FinancialAnomalyEnv:
35
+ """
36
+ Financial Statement Anomaly Detection environment.
37
+
38
+ The agent receives quarterly financial statements and must identify
39
+ injected anomalies by flagging them with type, location, severity,
40
+ and explanation.
41
+ """
42
+
43
+ def __init__(self, task_id: str = "easy", max_steps: int = 20):
44
+ self.task_id = task_id
45
+ self.max_steps = max_steps
46
+
47
+ # Episode state
48
+ self._metadata: Optional[CompanyMetadata] = None
49
+ self._quarters: List[QuarterData] = []
50
+ self._ground_truth: List[GroundTruthAnomaly] = []
51
+ self._flags: List[AnomalyFlag] = []
52
+ self._step_number: int = 0
53
+ self._cumulative_reward: float = 0.0
54
+ self._done: bool = False
55
+ self._task_config: Dict[str, Any] = {}
56
+
57
+ # Load task config
58
+ self._load_task(task_id)
59
+
60
+ def _load_task(self, task_id: str) -> None:
61
+ """Load task configuration from JSON file."""
62
+ task_file = TASKS_DIR / f"task_{task_id}.json"
63
+ if task_file.exists():
64
+ with open(task_file, "r") as f:
65
+ self._task_config = json.load(f)
66
+ else:
67
+ # Default configs
68
+ defaults = {
69
+ "easy": {"seed": 42, "num_quarters": 4, "difficulty": "easy"},
70
+ "medium": {"seed": 137, "num_quarters": 6, "difficulty": "medium"},
71
+ "hard": {"seed": 256, "num_quarters": 8, "difficulty": "hard"},
72
+ }
73
+ self._task_config = defaults.get(task_id, defaults["easy"])
74
+
75
+ def reset(self) -> Observation:
76
+ """
77
+ Generate a fresh company with anomalies and return the initial observation.
78
+ Clears all episode state.
79
+ """
80
+ seed = self._task_config.get("seed", 42)
81
+ num_q = self._task_config.get("num_quarters", 6)
82
+ difficulty = self._task_config.get("difficulty", "easy")
83
+
84
+ # Generate clean data
85
+ self._metadata, clean_quarters = generate_company_data(
86
+ seed=seed,
87
+ num_quarters=num_q,
88
+ )
89
+
90
+ # Inject anomalies
91
+ self._quarters, self._ground_truth = inject_anomalies(
92
+ quarters=clean_quarters,
93
+ difficulty=difficulty,
94
+ seed=seed + 1000, # separate seed for injection
95
+ )
96
+
97
+ # Reset episode state
98
+ self._flags = []
99
+ self._step_number = 0
100
+ self._cumulative_reward = 0.0
101
+ self._done = False
102
+
103
+ return self._build_observation()
104
+
105
+ def step(self, action: Action) -> Tuple[Observation, Reward, bool, Info]:
106
+ """
107
+ Process one agent action.
108
+
109
+ Args:
110
+ action: The agent's action (flag_anomaly, request_detail, or submit_report).
111
+
112
+ Returns:
113
+ Tuple of (observation, reward, done, info).
114
+ """
115
+ if self._done:
116
+ return (
117
+ self._build_observation(),
118
+ Reward(step_reward=0.0, cumulative_reward=self._cumulative_reward),
119
+ True,
120
+ Info(message="Episode already finished.", done_reason="already_done"),
121
+ )
122
+
123
+ self._step_number += 1
124
+ step_reward = 0.0
125
+ info_msg = ""
126
+ done_reason = None
127
+ detail_response = None
128
+
129
+ if action.action_type == ActionType.FLAG_ANOMALY and action.flag:
130
+ flag = action.flag
131
+ self._flags.append(flag)
132
+
133
+ # Compute immediate reward
134
+ matched = False
135
+ matched_gt = None
136
+ for gt in self._ground_truth:
137
+ loc_match = (
138
+ flag.line_item == gt.line_item
139
+ and (flag.quarter == gt.quarter or gt.quarter == "ALL")
140
+ )
141
+ if loc_match:
142
+ if flag.anomaly_type.value == gt.anomaly_type.value:
143
+ step_reward = 1.0
144
+ matched = True
145
+ matched_gt = gt
146
+ else:
147
+ step_reward = 0.5
148
+ matched = True
149
+ matched_gt = gt
150
+ break
151
+
152
+ if not matched:
153
+ step_reward = -0.3 # false positive
154
+
155
+ info_msg = f"Flag recorded: {flag.line_item} @ {flag.quarter}"
156
+
157
+ elif action.action_type == ActionType.REQUEST_DETAIL:
158
+ step_reward = -0.1 # exploration cost
159
+ # Return a synthetic sub-ledger breakdown
160
+ if action.detail_line_item and action.detail_quarter:
161
+ detail_response = self._generate_detail(
162
+ action.detail_line_item, action.detail_quarter
163
+ )
164
+ info_msg = f"Detail returned for {action.detail_line_item} @ {action.detail_quarter}"
165
+ else:
166
+ info_msg = "request_detail requires detail_line_item and detail_quarter"
167
+
168
+ elif action.action_type == ActionType.SUBMIT_REPORT:
169
+ self._done = True
170
+ done_reason = "submitted"
171
+ # Final grading
172
+ grade_result = grade(self._flags, self._ground_truth)
173
+ step_reward = 0.0
174
+ info_msg = f"Report submitted. Final score: {grade_result['score']}"
175
+
176
+ # Check max steps
177
+ if self._step_number >= self.max_steps and not self._done:
178
+ self._done = True
179
+ done_reason = "max_steps"
180
+ step_reward -= 0.5
181
+ info_msg = "Max steps reached. Episode ended with penalty."
182
+
183
+ self._cumulative_reward += step_reward
184
+
185
+ obs = self._build_observation(detail_response=detail_response)
186
+ reward = Reward(
187
+ step_reward=round(step_reward, 4),
188
+ cumulative_reward=round(self._cumulative_reward, 4),
189
+ breakdown={"step": round(step_reward, 4)},
190
+ )
191
+ info = Info(
192
+ message=info_msg,
193
+ flags_so_far=len(self._flags),
194
+ steps_remaining=self.max_steps - self._step_number,
195
+ done_reason=done_reason,
196
+ )
197
+
198
+ return obs, reward, self._done, info
199
+
200
+ def state(self) -> State:
201
+ """Return the current internal state of the episode."""
202
+ return State(
203
+ step_number=self._step_number,
204
+ max_steps=self.max_steps,
205
+ flags_submitted=list(self._flags),
206
+ cumulative_reward=round(self._cumulative_reward, 4),
207
+ done=self._done,
208
+ task_id=self.task_id,
209
+ )
210
+
211
+ def get_final_score(self) -> Dict:
212
+ """Run the grader on all submitted flags and return the full result."""
213
+ return grade(self._flags, self._ground_truth)
214
+
215
+ def get_ground_truth(self) -> List[GroundTruthAnomaly]:
216
+ """Return ground truth anomalies (for testing/debugging only)."""
217
+ return self._ground_truth
218
+
219
+ def _build_observation(
220
+ self, detail_response: Optional[Dict] = None
221
+ ) -> Observation:
222
+ """Build the current observation for the agent."""
223
+ return Observation(
224
+ company=self._metadata,
225
+ quarters=self._quarters,
226
+ footnotes=self._task_config.get("footnotes", []),
227
+ prior_flags=list(self._flags),
228
+ detail_response=detail_response,
229
+ step_number=self._step_number,
230
+ max_steps=self.max_steps,
231
+ )
232
+
233
+ def _generate_detail(self, line_item: str, quarter: str) -> Dict:
234
+ """Generate a synthetic sub-ledger breakdown for a line item."""
235
+ rng = random.Random(hash(f"{line_item}_{quarter}"))
236
+ target_q = None
237
+ for q in self._quarters:
238
+ if q.quarter_label == quarter:
239
+ target_q = q
240
+ break
241
+ if target_q is None:
242
+ return {"error": f"Quarter {quarter} not found"}
243
+
244
+ total = getattr(target_q, line_item, None)
245
+ if total is None:
246
+ return {"error": f"Line item {line_item} not found"}
247
+
248
+ # Generate 3-5 sub-components
249
+ n_subs = rng.randint(3, 5)
250
+ sub_labels = [f"{line_item}_component_{i+1}" for i in range(n_subs)]
251
+ weights = [rng.random() for _ in range(n_subs)]
252
+ weight_sum = sum(weights)
253
+ components = {}
254
+ running = 0
255
+ for i, label in enumerate(sub_labels):
256
+ if i == n_subs - 1:
257
+ components[label] = total - running
258
+ else:
259
+ val = int(total * weights[i] / weight_sum)
260
+ components[label] = val
261
+ running += val
262
+
263
+ return {
264
+ "line_item": line_item,
265
+ "quarter": quarter,
266
+ "total": total,
267
+ "components": components,
268
+ }
src/generator.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generates synthetic but realistic financial statements for fictional companies.
3
+ Uses industry baselines from public financial databases and applies controlled
4
+ random variation to produce 4-8 quarters of clean data.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import random
10
+ from typing import List, Tuple
11
+
12
+ from .models import (
13
+ CompanyMetadata,
14
+ CompanySize,
15
+ Industry,
16
+ QuarterData,
17
+ )
18
+ from .utils import dollars_to_cents
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Industry baseline profiles (ratios sourced from Damodaran Online aggregates)
22
+ # ---------------------------------------------------------------------------
23
+
24
+ INDUSTRY_PROFILES = {
25
+ Industry.TECHNOLOGY: {
26
+ "gross_margin": (0.65, 0.75),
27
+ "opex_ratio": (0.35, 0.45), # opex / revenue
28
+ "current_ratio": (2.5, 4.0),
29
+ "dso_days": (45, 75),
30
+ "inventory_ratio": (0.02, 0.08), # inventory / revenue
31
+ "debt_equity": (0.2, 0.6),
32
+ "ocf_ni": (1.2, 1.8),
33
+ "capex_ratio": (0.05, 0.12),
34
+ "seasonal_q4_boost": 0.08,
35
+ },
36
+ Industry.MANUFACTURING: {
37
+ "gross_margin": (0.25, 0.35),
38
+ "opex_ratio": (0.12, 0.20),
39
+ "current_ratio": (1.5, 2.5),
40
+ "dso_days": (35, 55),
41
+ "inventory_ratio": (0.15, 0.30),
42
+ "debt_equity": (0.5, 1.2),
43
+ "ocf_ni": (1.0, 1.5),
44
+ "capex_ratio": (0.08, 0.18),
45
+ "seasonal_q4_boost": 0.04,
46
+ },
47
+ Industry.RETAIL: {
48
+ "gross_margin": (0.30, 0.45),
49
+ "opex_ratio": (0.20, 0.30),
50
+ "current_ratio": (1.0, 1.8),
51
+ "dso_days": (5, 15),
52
+ "inventory_ratio": (0.20, 0.35),
53
+ "debt_equity": (0.6, 1.5),
54
+ "ocf_ni": (1.1, 1.6),
55
+ "capex_ratio": (0.04, 0.10),
56
+ "seasonal_q4_boost": 0.18, # holiday season
57
+ },
58
+ Industry.HEALTHCARE: {
59
+ "gross_margin": (0.55, 0.70),
60
+ "opex_ratio": (0.30, 0.40),
61
+ "current_ratio": (1.5, 3.0),
62
+ "dso_days": (40, 65),
63
+ "inventory_ratio": (0.05, 0.12),
64
+ "debt_equity": (0.3, 0.8),
65
+ "ocf_ni": (1.0, 1.4),
66
+ "capex_ratio": (0.06, 0.14),
67
+ "seasonal_q4_boost": 0.03,
68
+ },
69
+ Industry.FINANCIAL_SERVICES: {
70
+ "gross_margin": (0.50, 0.65),
71
+ "opex_ratio": (0.25, 0.38),
72
+ "current_ratio": (1.2, 2.0),
73
+ "dso_days": (30, 50),
74
+ "inventory_ratio": (0.0, 0.02),
75
+ "debt_equity": (1.0, 3.0),
76
+ "ocf_ni": (0.9, 1.3),
77
+ "capex_ratio": (0.03, 0.08),
78
+ "seasonal_q4_boost": 0.05,
79
+ },
80
+ }
81
+
82
+ REVENUE_RANGES = {
83
+ CompanySize.SMALL: (10_000_000, 50_000_000),
84
+ CompanySize.MEDIUM: (50_000_000, 500_000_000),
85
+ CompanySize.LARGE: (500_000_000, 2_000_000_000),
86
+ }
87
+
88
+ COMPANY_NAMES = [
89
+ "Apex Dynamics Corp", "Veriton Industries", "Crestline Holdings",
90
+ "NovaEdge Solutions", "Pinnacle Systems Inc", "Meridian Analytics",
91
+ "Stratos Group Ltd", "Caliber Technologies", "Summit Financial Corp",
92
+ "Prism Data Services", "BluePeak Manufacturing", "Orion Healthcare Inc",
93
+ "Trident Retail Group", "Cypher Software Ltd", "Atlas Infrastructure",
94
+ ]
95
+
96
+
97
+ def _rand_in(low: float, high: float, rng: random.Random) -> float:
98
+ return low + rng.random() * (high - low)
99
+
100
+
101
+ def generate_company_data(
102
+ seed: int,
103
+ num_quarters: int = 6,
104
+ industry: Industry | None = None,
105
+ size: CompanySize | None = None,
106
+ ) -> Tuple[CompanyMetadata, List[QuarterData]]:
107
+ """
108
+ Generate a complete set of clean financial statements for a fictional company.
109
+
110
+ Args:
111
+ seed: RNG seed for reproducibility.
112
+ num_quarters: Number of quarters to generate (4-8).
113
+ industry: Force a specific industry, or random if None.
114
+ size: Force a specific size, or random if None.
115
+
116
+ Returns:
117
+ Tuple of (CompanyMetadata, list of QuarterData).
118
+ """
119
+ rng = random.Random(seed)
120
+
121
+ # Pick industry & size
122
+ if industry is None:
123
+ industry = rng.choice(list(Industry))
124
+ if size is None:
125
+ size = rng.choice(list(CompanySize))
126
+
127
+ profile = INDUSTRY_PROFILES[industry]
128
+ company_name = rng.choice(COMPANY_NAMES)
129
+
130
+ # Base annual revenue
131
+ rev_low, rev_high = REVENUE_RANGES[size]
132
+ annual_revenue = rng.uniform(rev_low, rev_high)
133
+ quarterly_revenue_base = annual_revenue / 4
134
+
135
+ # Pick ratio targets
136
+ gm = _rand_in(*profile["gross_margin"], rng)
137
+ opex_r = _rand_in(*profile["opex_ratio"], rng)
138
+ cr = _rand_in(*profile["current_ratio"], rng)
139
+ dso = _rand_in(*profile["dso_days"], rng)
140
+ inv_r = _rand_in(*profile["inventory_ratio"], rng)
141
+ de = _rand_in(*profile["debt_equity"], rng)
142
+ ocf_ni_r = _rand_in(*profile["ocf_ni"], rng)
143
+ capex_r = _rand_in(*profile["capex_ratio"], rng)
144
+ seasonal_boost = profile["seasonal_q4_boost"]
145
+
146
+ # Growth rate per quarter
147
+ qoq_growth = rng.uniform(-0.02, 0.06)
148
+
149
+ fiscal_year_start = rng.choice([2021, 2022, 2023])
150
+ metadata = CompanyMetadata(
151
+ name=company_name,
152
+ industry=industry,
153
+ size=size,
154
+ num_quarters=num_quarters,
155
+ fiscal_year_start=fiscal_year_start,
156
+ )
157
+
158
+ quarters: List[QuarterData] = []
159
+ prev_cash = dollars_to_cents(rng.uniform(0.05, 0.15) * annual_revenue)
160
+
161
+ for i in range(num_quarters):
162
+ year = fiscal_year_start + i // 4
163
+ q_num = (i % 4) + 1
164
+ label = f"Q{q_num} {year}"
165
+
166
+ # Revenue with growth + seasonal variation
167
+ growth_factor = (1 + qoq_growth) ** i
168
+ seasonal = 1.0 + (seasonal_boost if q_num == 4 else -seasonal_boost / 3)
169
+ variation = rng.uniform(0.95, 1.05)
170
+ revenue = quarterly_revenue_base * growth_factor * seasonal * variation
171
+ revenue_c = dollars_to_cents(revenue)
172
+
173
+ # Income statement
174
+ cogs_c = dollars_to_cents(revenue * (1 - gm) * rng.uniform(0.97, 1.03))
175
+ gross_profit_c = revenue_c - cogs_c
176
+ opex_c = dollars_to_cents(revenue * opex_r * rng.uniform(0.95, 1.05))
177
+ operating_income_c = gross_profit_c - opex_c
178
+ interest_c = dollars_to_cents(revenue * rng.uniform(0.005, 0.02))
179
+ pretax = operating_income_c - interest_c
180
+ tax_c = dollars_to_cents(max(0, pretax * 0.01) * rng.uniform(0.20, 0.28))
181
+ net_income_c = pretax - tax_c
182
+
183
+ # Balance sheet
184
+ receivables_c = dollars_to_cents(revenue * (dso / 90) * rng.uniform(0.92, 1.08))
185
+ inventory_c = dollars_to_cents(revenue * inv_r * rng.uniform(0.90, 1.10))
186
+ other_ca_c = dollars_to_cents(revenue * rng.uniform(0.02, 0.06))
187
+
188
+ # Cash flow
189
+ depreciation = dollars_to_cents(revenue * rng.uniform(0.02, 0.05))
190
+ wc_change = dollars_to_cents(revenue * rng.uniform(-0.03, 0.03))
191
+ cf_operating_c = dollars_to_cents(
192
+ (net_income_c + depreciation - wc_change) * 0.01
193
+ * ocf_ni_r * rng.uniform(0.90, 1.10)
194
+ )
195
+ # Simpler: just derive from net income * ocf ratio
196
+ cf_operating_c = int(net_income_c * ocf_ni_r * rng.uniform(0.90, 1.10))
197
+
198
+ capex = dollars_to_cents(revenue * capex_r * rng.uniform(0.85, 1.15))
199
+ cf_investing_c = -capex
200
+ cf_financing_c = dollars_to_cents(revenue * rng.uniform(-0.05, 0.03))
201
+
202
+ net_cash_change_c = cf_operating_c + cf_investing_c + cf_financing_c
203
+ cash_c = prev_cash + net_cash_change_c
204
+ if cash_c < 0:
205
+ # Inject financing to keep cash positive
206
+ injection = abs(cash_c) + dollars_to_cents(revenue * 0.02)
207
+ cf_financing_c += injection
208
+ net_cash_change_c = cf_operating_c + cf_investing_c + cf_financing_c
209
+ cash_c = prev_cash + net_cash_change_c
210
+
211
+ total_ca_c = cash_c + receivables_c + inventory_c + other_ca_c
212
+ fixed_assets_c = dollars_to_cents(annual_revenue * rng.uniform(0.3, 0.8))
213
+ total_assets_c = total_ca_c + fixed_assets_c
214
+
215
+ # Liabilities
216
+ payables_c = dollars_to_cents(revenue * rng.uniform(0.05, 0.12))
217
+ short_debt_c = dollars_to_cents(revenue * rng.uniform(0.02, 0.08))
218
+ total_cl_c = payables_c + short_debt_c
219
+ long_debt_c = dollars_to_cents(total_assets_c * rng.uniform(0.10, 0.30))
220
+ total_liab_c = total_cl_c + long_debt_c
221
+
222
+ # Equity = assets - liabilities (forced balance)
223
+ equity_c = total_assets_c - total_liab_c
224
+
225
+ q = QuarterData(
226
+ quarter_label=label,
227
+ cash=cash_c,
228
+ receivables=receivables_c,
229
+ inventory=inventory_c,
230
+ other_current_assets=other_ca_c,
231
+ total_current_assets=total_ca_c,
232
+ fixed_assets=fixed_assets_c,
233
+ total_assets=total_assets_c,
234
+ payables=payables_c,
235
+ short_term_debt=short_debt_c,
236
+ total_current_liabilities=total_cl_c,
237
+ long_term_debt=long_debt_c,
238
+ total_liabilities=total_liab_c,
239
+ equity=equity_c,
240
+ revenue=revenue_c,
241
+ cogs=cogs_c,
242
+ gross_profit=gross_profit_c,
243
+ operating_expenses=opex_c,
244
+ operating_income=operating_income_c,
245
+ interest_expense=interest_c,
246
+ tax_expense=tax_c,
247
+ net_income=net_income_c,
248
+ cf_operating=cf_operating_c,
249
+ cf_investing=cf_investing_c,
250
+ cf_financing=cf_financing_c,
251
+ net_cash_change=net_cash_change_c,
252
+ )
253
+ quarters.append(q)
254
+ prev_cash = cash_c
255
+
256
+ return metadata, quarters
src/grader.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Deterministic grader for scoring agent anomaly detection performance.
3
+ Uses precision/recall with severity weighting and partial credit.
4
+ Score range: 0.0 to 1.0.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Dict, List, Set, Tuple
10
+
11
+ from .models import AnomalyFlag, GroundTruthAnomaly
12
+
13
+
14
+ def _match_flag_to_truth(
15
+ flag: AnomalyFlag,
16
+ truths: List[GroundTruthAnomaly],
17
+ already_matched: Set[str],
18
+ ) -> Tuple[str, float]:
19
+ """
20
+ Try to match an agent flag to a ground truth anomaly.
21
+
22
+ Returns:
23
+ (matched_anomaly_id, credit) where credit is 1.0 (exact), 0.5 (partial), or 0.0 (miss).
24
+ """
25
+ for gt in truths:
26
+ if gt.anomaly_id in already_matched:
27
+ continue
28
+ # Location match: same line_item AND (same quarter OR gt.quarter == "ALL")
29
+ location_match = (
30
+ flag.line_item == gt.line_item
31
+ and (flag.quarter == gt.quarter or gt.quarter == "ALL")
32
+ )
33
+ if location_match:
34
+ if flag.anomaly_type.value == gt.anomaly_type.value:
35
+ return gt.anomaly_id, 1.0 # exact match
36
+ else:
37
+ return gt.anomaly_id, 0.5 # partial: right location, wrong type
38
+ return "", 0.0
39
+
40
+
41
+ def _severity_accuracy(
42
+ flags: List[AnomalyFlag],
43
+ truths: List[GroundTruthAnomaly],
44
+ matches: Dict[str, str], # flag_idx -> anomaly_id
45
+ ) -> float:
46
+ """
47
+ Compute severity accuracy for matched flags.
48
+ Returns 1.0 - (mean absolute severity error / 4.0).
49
+ """
50
+ if not matches:
51
+ return 0.0
52
+ truth_map = {gt.anomaly_id: gt for gt in truths}
53
+ total_error = 0.0
54
+ count = 0
55
+ for flag_idx_str, anomaly_id in matches.items():
56
+ flag_idx = int(flag_idx_str)
57
+ if anomaly_id and anomaly_id in truth_map:
58
+ pred_sev = flags[flag_idx].severity
59
+ actual_sev = truth_map[anomaly_id].severity
60
+ total_error += abs(pred_sev - actual_sev)
61
+ count += 1
62
+ if count == 0:
63
+ return 0.0
64
+ mae = total_error / count
65
+ return max(0.0, 1.0 - mae / 4.0)
66
+
67
+
68
+ def _dependency_bonus(
69
+ flags: List[AnomalyFlag],
70
+ truths: List[GroundTruthAnomaly],
71
+ matches: Dict[str, str],
72
+ ) -> float:
73
+ """
74
+ Compute dependency ordering bonus. If an agent flags a root cause
75
+ BEFORE its dependent anomaly, the root cause gets a 1.2x multiplier.
76
+ Returns a bonus value added to the score.
77
+ """
78
+ truth_map = {gt.anomaly_id: gt for gt in truths}
79
+ # Build reverse map: anomaly_id -> flag index (order)
80
+ anomaly_to_flag_order: Dict[str, int] = {}
81
+ for flag_idx_str, anomaly_id in matches.items():
82
+ if anomaly_id:
83
+ anomaly_to_flag_order[anomaly_id] = int(flag_idx_str)
84
+
85
+ bonus = 0.0
86
+ for gt in truths:
87
+ if gt.depends_on and gt.depends_on in anomaly_to_flag_order:
88
+ if gt.anomaly_id in anomaly_to_flag_order:
89
+ parent_order = anomaly_to_flag_order[gt.depends_on]
90
+ child_order = anomaly_to_flag_order[gt.anomaly_id]
91
+ if parent_order < child_order:
92
+ bonus += 0.02 # small bonus per correct ordering
93
+ return bonus
94
+
95
+
96
+ def grade(
97
+ flags: List[AnomalyFlag],
98
+ ground_truth: List[GroundTruthAnomaly],
99
+ ) -> Dict:
100
+ """
101
+ Grade agent flags against ground truth anomalies.
102
+
103
+ Args:
104
+ flags: Agent-submitted anomaly flags.
105
+ ground_truth: Known injected anomalies.
106
+
107
+ Returns:
108
+ Dict with 'score' (0.0-1.0), 'precision', 'recall',
109
+ 'severity_accuracy', 'breakdown'.
110
+ """
111
+ if not ground_truth:
112
+ # No anomalies to find; penalize any flags as false positives
113
+ score = 1.0 if not flags else max(0.0, 1.0 - len(flags) * 0.3)
114
+ return {
115
+ "score": round(score, 4),
116
+ "precision": 1.0 if not flags else 0.0,
117
+ "recall": 1.0,
118
+ "severity_accuracy": 1.0,
119
+ "details": "No anomalies to detect.",
120
+ }
121
+
122
+ already_matched: Set[str] = set()
123
+ matches: Dict[str, str] = {} # str(flag_idx) -> anomaly_id
124
+ credits: List[float] = []
125
+
126
+ for i, flag in enumerate(flags):
127
+ anomaly_id, credit = _match_flag_to_truth(flag, ground_truth, already_matched)
128
+ if anomaly_id:
129
+ already_matched.add(anomaly_id)
130
+ matches[str(i)] = anomaly_id
131
+ else:
132
+ matches[str(i)] = ""
133
+ credits.append(credit)
134
+
135
+ # Precision: weighted correct / total flags
136
+ total_flags = len(flags)
137
+ if total_flags == 0:
138
+ precision = 0.0
139
+ else:
140
+ precision = sum(credits) / total_flags
141
+
142
+ # Recall: matched anomalies / total anomalies
143
+ total_anomalies = len(ground_truth)
144
+ matched_count = sum(1 for c in credits if c > 0)
145
+ recall = matched_count / total_anomalies if total_anomalies > 0 else 0.0
146
+
147
+ # Severity accuracy
148
+ sev_acc = _severity_accuracy(flags, ground_truth, matches)
149
+
150
+ # Dependency bonus
151
+ dep_bonus = _dependency_bonus(flags, ground_truth, matches)
152
+
153
+ # Final score: weighted combination
154
+ raw_score = (precision * 0.4) + (recall * 0.4) + (sev_acc * 0.2) + dep_bonus
155
+ score = min(1.0, max(0.0, raw_score))
156
+
157
+ return {
158
+ "score": round(score, 4),
159
+ "precision": round(precision, 4),
160
+ "recall": round(recall, 4),
161
+ "severity_accuracy": round(sev_acc, 4),
162
+ "dependency_bonus": round(dep_bonus, 4),
163
+ "flags_submitted": total_flags,
164
+ "anomalies_found": matched_count,
165
+ "total_anomalies": total_anomalies,
166
+ "false_positives": total_flags - matched_count,
167
+ }
src/models.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Typed Pydantic models for the Financial Statement Anomaly Detection environment.
3
+ Defines Observation, Action, Reward, and State schemas used across the OpenEnv API.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from enum import Enum
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ from pydantic import BaseModel, Field
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Enums
16
+ # ---------------------------------------------------------------------------
17
+
18
+ class AnomalyType(str, Enum):
19
+ """All anomaly categories the agent can flag."""
20
+ ARITHMETIC_ERROR = "arithmetic_error"
21
+ DUPLICATE_ENTRY = "duplicate_entry"
22
+ NEGATIVE_VALUE = "negative_value"
23
+ IMPOSSIBLE_CHANGE = "impossible_change"
24
+ PERCENTAGE_ERROR = "percentage_error"
25
+ RECEIVABLES_DIVERGENCE = "receivables_divergence"
26
+ INVENTORY_TURNOVER = "inventory_turnover"
27
+ CASHFLOW_MISMATCH = "cashflow_mismatch"
28
+ MARGIN_SHIFT = "margin_shift"
29
+ DSO_SPIKE = "dso_spike"
30
+ CHANNEL_STUFFING = "channel_stuffing"
31
+ COOKIE_JAR = "cookie_jar"
32
+ ROUND_TRIPPING = "round_tripping"
33
+ EARLY_REVENUE = "early_revenue"
34
+ BENFORDS_LAW = "benfords_law"
35
+
36
+
37
+ class ActionType(str, Enum):
38
+ """Possible agent actions per step."""
39
+ FLAG_ANOMALY = "flag_anomaly"
40
+ REQUEST_DETAIL = "request_detail"
41
+ SUBMIT_REPORT = "submit_report"
42
+
43
+
44
+ class Industry(str, Enum):
45
+ TECHNOLOGY = "technology"
46
+ MANUFACTURING = "manufacturing"
47
+ RETAIL = "retail"
48
+ HEALTHCARE = "healthcare"
49
+ FINANCIAL_SERVICES = "financial_services"
50
+
51
+
52
+ class CompanySize(str, Enum):
53
+ SMALL = "small" # $10M-50M revenue
54
+ MEDIUM = "medium" # $50M-500M
55
+ LARGE = "large" # $500M+
56
+
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Sub-models
60
+ # ---------------------------------------------------------------------------
61
+
62
+ class CompanyMetadata(BaseModel):
63
+ """Static company information for an episode."""
64
+ name: str
65
+ industry: Industry
66
+ size: CompanySize
67
+ num_quarters: int
68
+ fiscal_year_start: int = Field(description="Starting fiscal year, e.g. 2022")
69
+
70
+
71
+ class QuarterData(BaseModel):
72
+ """Financial data for a single quarter. All amounts in integer cents."""
73
+ quarter_label: str = Field(description="e.g. 'Q1 2023'")
74
+ # Balance sheet
75
+ cash: int = 0
76
+ receivables: int = 0
77
+ inventory: int = 0
78
+ other_current_assets: int = 0
79
+ total_current_assets: int = 0
80
+ fixed_assets: int = 0
81
+ total_assets: int = 0
82
+ payables: int = 0
83
+ short_term_debt: int = 0
84
+ total_current_liabilities: int = 0
85
+ long_term_debt: int = 0
86
+ total_liabilities: int = 0
87
+ equity: int = 0
88
+ # Income statement
89
+ revenue: int = 0
90
+ cogs: int = 0
91
+ gross_profit: int = 0
92
+ operating_expenses: int = 0
93
+ operating_income: int = 0
94
+ interest_expense: int = 0
95
+ tax_expense: int = 0
96
+ net_income: int = 0
97
+ # Cash flow statement
98
+ cf_operating: int = 0
99
+ cf_investing: int = 0
100
+ cf_financing: int = 0
101
+ net_cash_change: int = 0
102
+
103
+
104
+ class AnomalyFlag(BaseModel):
105
+ """An anomaly flagged by the agent."""
106
+ line_item: str
107
+ quarter: str
108
+ severity: int = Field(ge=1, le=5)
109
+ anomaly_type: AnomalyType
110
+ explanation: str = ""
111
+
112
+
113
+ class GroundTruthAnomaly(BaseModel):
114
+ """A known injected anomaly (used internally by the grader)."""
115
+ line_item: str
116
+ quarter: str
117
+ severity: int = Field(ge=1, le=5)
118
+ anomaly_type: AnomalyType
119
+ description: str = ""
120
+ depends_on: Optional[str] = Field(
121
+ default=None,
122
+ description="ID of parent anomaly this one depends on (for ordering bonus)",
123
+ )
124
+ anomaly_id: str = ""
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Top-level OpenEnv models
129
+ # ---------------------------------------------------------------------------
130
+
131
+ class Observation(BaseModel):
132
+ """What the agent sees each step."""
133
+ company: CompanyMetadata
134
+ quarters: List[QuarterData]
135
+ footnotes: List[str] = Field(default_factory=list)
136
+ prior_flags: List[AnomalyFlag] = Field(default_factory=list)
137
+ detail_response: Optional[Dict[str, Any]] = Field(
138
+ default=None,
139
+ description="Sub-ledger detail returned after a request_detail action",
140
+ )
141
+ step_number: int = 0
142
+ max_steps: int = 20
143
+
144
+
145
+ class Action(BaseModel):
146
+ """What the agent does each step."""
147
+ action_type: ActionType
148
+ # For flag_anomaly
149
+ flag: Optional[AnomalyFlag] = None
150
+ # For request_detail
151
+ detail_line_item: Optional[str] = None
152
+ detail_quarter: Optional[str] = None
153
+
154
+
155
+ class Reward(BaseModel):
156
+ """Reward signal returned after each step."""
157
+ step_reward: float = 0.0
158
+ cumulative_reward: float = 0.0
159
+ breakdown: Dict[str, float] = Field(default_factory=dict)
160
+
161
+
162
+ class Info(BaseModel):
163
+ """Extra info dict returned alongside reward."""
164
+ message: str = ""
165
+ flags_so_far: int = 0
166
+ steps_remaining: int = 0
167
+ done_reason: Optional[str] = None
168
+
169
+
170
+ class State(BaseModel):
171
+ """Full internal state returned by state()."""
172
+ step_number: int = 0
173
+ max_steps: int = 20
174
+ flags_submitted: List[AnomalyFlag] = Field(default_factory=list)
175
+ cumulative_reward: float = 0.0
176
+ done: bool = False
177
+ task_id: str = ""
src/utils.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for financial ratio calculations, Benford's Law analysis,
3
+ and cross-statement validation.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from typing import Dict, List
10
+
11
+ from .models import QuarterData
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Benford's Law
16
+ # ---------------------------------------------------------------------------
17
+
18
+ BENFORD_EXPECTED = {
19
+ 1: 0.301, 2: 0.176, 3: 0.125, 4: 0.097,
20
+ 5: 0.079, 6: 0.067, 7: 0.058, 8: 0.051, 9: 0.046,
21
+ }
22
+
23
+
24
+ def leading_digit(value: int) -> int:
25
+ """Return the leading digit of an integer (ignoring sign and zero)."""
26
+ v = abs(value)
27
+ if v == 0:
28
+ return 0
29
+ while v >= 10:
30
+ v //= 10
31
+ return v
32
+
33
+
34
+ def benfords_chi_squared(values: List[int]) -> float:
35
+ """
36
+ Compute Benford's Law chi-squared statistic for a list of integer values.
37
+ Higher values indicate more deviation from expected distribution.
38
+ """
39
+ counts: Dict[int, int] = {d: 0 for d in range(1, 10)}
40
+ total = 0
41
+ for v in values:
42
+ d = leading_digit(v)
43
+ if d >= 1:
44
+ counts[d] += 1
45
+ total += 1
46
+ if total == 0:
47
+ return 0.0
48
+ chi2 = 0.0
49
+ for digit in range(1, 10):
50
+ observed = counts[digit]
51
+ expected = BENFORD_EXPECTED[digit] * total
52
+ if expected > 0:
53
+ chi2 += (observed - expected) ** 2 / expected
54
+ return chi2
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Financial ratios
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def gross_margin(q: QuarterData) -> float:
62
+ """Gross profit / Revenue."""
63
+ if q.revenue == 0:
64
+ return 0.0
65
+ return q.gross_profit / q.revenue
66
+
67
+
68
+ def current_ratio(q: QuarterData) -> float:
69
+ """Total current assets / Total current liabilities."""
70
+ if q.total_current_liabilities == 0:
71
+ return 0.0
72
+ return q.total_current_assets / q.total_current_liabilities
73
+
74
+
75
+ def days_sales_outstanding(q: QuarterData) -> float:
76
+ """DSO = (Receivables / Revenue) * 90 (for a quarter)."""
77
+ if q.revenue == 0:
78
+ return 0.0
79
+ return (q.receivables / q.revenue) * 90
80
+
81
+
82
+ def ocf_to_ni_ratio(q: QuarterData) -> float:
83
+ """Operating cash flow / Net income."""
84
+ if q.net_income == 0:
85
+ return 0.0
86
+ return q.cf_operating / q.net_income
87
+
88
+
89
+ def inventory_turnover(q: QuarterData) -> float:
90
+ """COGS / Inventory (annualized from quarterly = multiply by 4)."""
91
+ if q.inventory == 0:
92
+ return 0.0
93
+ return (q.cogs * 4) / q.inventory
94
+
95
+
96
+ def debt_to_equity(q: QuarterData) -> float:
97
+ """Total liabilities / Equity."""
98
+ if q.equity == 0:
99
+ return 0.0
100
+ return q.total_liabilities / q.equity
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Cross-statement validation helpers
105
+ # ---------------------------------------------------------------------------
106
+
107
+ def balance_sheet_balanced(q: QuarterData) -> bool:
108
+ """Check assets == liabilities + equity."""
109
+ return q.total_assets == q.total_liabilities + q.equity
110
+
111
+
112
+ def cash_flow_reconciles(q: QuarterData) -> bool:
113
+ """Check net cash change == sum of CF components."""
114
+ return q.net_cash_change == q.cf_operating + q.cf_investing + q.cf_financing
115
+
116
+
117
+ def current_assets_sum_check(q: QuarterData) -> bool:
118
+ """Check total_current_assets == sum of components."""
119
+ expected = q.cash + q.receivables + q.inventory + q.other_current_assets
120
+ return q.total_current_assets == expected
121
+
122
+
123
+ def income_statement_check(q: QuarterData) -> bool:
124
+ """Check gross_profit == revenue - cogs."""
125
+ return q.gross_profit == q.revenue - q.cogs
126
+
127
+
128
+ def cents_to_dollars(cents: int) -> float:
129
+ """Convert integer cents to dollar float for display."""
130
+ return cents / 100.0
131
+
132
+
133
+ def dollars_to_cents(dollars: float) -> int:
134
+ """Convert dollar float to integer cents for storage."""
135
+ return int(round(dollars * 100))
tasks/task_easy.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_id": "easy",
3
+ "difficulty": "easy",
4
+ "seed": 42,
5
+ "num_quarters": 4,
6
+ "max_steps": 15,
7
+ "description": "Detect arithmetic errors, duplicate entries, and obvious misstatements in 4 quarters of financial data.",
8
+ "expected_anomalies": "3-5 surface-level anomalies (arithmetic errors, negative values, duplicates)",
9
+ "expected_score_range": {
10
+ "frontier_model": [0.85, 0.95],
11
+ "mid_model": [0.60, 0.75],
12
+ "random_agent": [0.05, 0.15]
13
+ },
14
+ "footnotes": [
15
+ "Revenue recognition follows ASC 606 standards.",
16
+ "All amounts in USD. Fiscal year ends December 31."
17
+ ]
18
+ }
tasks/task_hard.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_id": "hard",
3
+ "difficulty": "hard",
4
+ "seed": 256,
5
+ "num_quarters": 8,
6
+ "max_steps": 25,
7
+ "description": "Detect coordinated manipulation patterns including channel stuffing, cookie jar reserves, round-tripping, and Benford's Law violations across 8 quarters.",
8
+ "expected_anomalies": "5-10 anomalies including coordinated multi-quarter fraud patterns with causal dependencies",
9
+ "expected_score_range": {
10
+ "frontier_model": [0.25, 0.40],
11
+ "mid_model": [0.10, 0.20],
12
+ "random_agent": [0.01, 0.05]
13
+ },
14
+ "footnotes": [
15
+ "Revenue recognition follows ASC 606 standards.",
16
+ "Company completed a major product launch in Q4 2022.",
17
+ "Management revised Q2 2023 estimates due to market conditions.",
18
+ "All amounts in USD. Fiscal year ends December 31.",
19
+ "Auditor noted a material weakness in internal controls over financial reporting.",
20
+ "Related-party transactions disclosed in Note 14 (not shown)."
21
+ ]
22
+ }
tasks/task_medium.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "task_id": "medium",
3
+ "difficulty": "medium",
4
+ "seed": 137,
5
+ "num_quarters": 6,
6
+ "max_steps": 20,
7
+ "description": "Detect ratio anomalies, trend deviations, and cross-statement inconsistencies across 6 quarters.",
8
+ "expected_anomalies": "4-7 anomalies including receivables divergence, inventory turnover spikes, cash flow mismatches",
9
+ "expected_score_range": {
10
+ "frontier_model": [0.55, 0.70],
11
+ "mid_model": [0.30, 0.45],
12
+ "random_agent": [0.02, 0.10]
13
+ },
14
+ "footnotes": [
15
+ "Revenue recognition follows ASC 606 standards.",
16
+ "Company acquired a small subsidiary in Q3 2022 (immaterial to financials).",
17
+ "All amounts in USD. Fiscal year ends December 31.",
18
+ "No changes to accounting policies during the reported period."
19
+ ]
20
+ }
tests/test_env.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test suite for the Financial Statement Anomaly Detection environment.
3
+ Covers: data generation, anomaly injection, grading, environment API,
4
+ and determinism.
5
+ """
6
+
7
+ import json
8
+ import sys
9
+ import os
10
+
11
+ # Add project root to path
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
13
+
14
+ from src.models import (
15
+ Action, ActionType, AnomalyFlag, AnomalyType, GroundTruthAnomaly,
16
+ Observation, QuarterData, State,
17
+ )
18
+ from src.generator import generate_company_data
19
+ from src.anomaly_injector import inject_anomalies
20
+ from src.grader import grade
21
+ from src.environment import FinancialAnomalyEnv
22
+ from src.utils import (
23
+ balance_sheet_balanced, cash_flow_reconciles,
24
+ current_assets_sum_check, income_statement_check,
25
+ benfords_chi_squared, leading_digit,
26
+ )
27
+
28
+
29
+ def test_generator_produces_valid_data():
30
+ """Generated data should have internally consistent financial statements."""
31
+ metadata, quarters = generate_company_data(seed=42, num_quarters=6)
32
+ assert metadata.name != ""
33
+ assert len(quarters) == 6
34
+
35
+ for q in quarters:
36
+ # Balance sheet must balance
37
+ assert q.total_assets == q.total_liabilities + q.equity, \
38
+ f"{q.quarter_label}: assets={q.total_assets} != liab+eq={q.total_liabilities + q.equity}"
39
+ # Cash flow must reconcile
40
+ assert q.net_cash_change == q.cf_operating + q.cf_investing + q.cf_financing, \
41
+ f"{q.quarter_label}: net_cash_change mismatch"
42
+ # Revenue should be positive
43
+ assert q.revenue > 0, f"{q.quarter_label}: revenue should be positive"
44
+
45
+ print("PASS: test_generator_produces_valid_data")
46
+
47
+
48
+ def test_generator_deterministic():
49
+ """Same seed should produce identical data."""
50
+ _, q1 = generate_company_data(seed=99, num_quarters=4)
51
+ _, q2 = generate_company_data(seed=99, num_quarters=4)
52
+ for a, b in zip(q1, q2):
53
+ assert a.revenue == b.revenue
54
+ assert a.total_assets == b.total_assets
55
+ assert a.net_income == b.net_income
56
+ print("PASS: test_generator_deterministic")
57
+
58
+
59
+ def test_anomaly_injection_easy():
60
+ """Easy injection should produce 3+ anomalies."""
61
+ _, quarters = generate_company_data(seed=42, num_quarters=4)
62
+ _, anomalies = inject_anomalies(quarters, difficulty="easy", seed=1042)
63
+ assert len(anomalies) >= 2, f"Expected >=2 anomalies, got {len(anomalies)}"
64
+ for a in anomalies:
65
+ assert a.anomaly_id != ""
66
+ assert a.severity >= 1
67
+ assert a.severity <= 5
68
+ print("PASS: test_anomaly_injection_easy")
69
+
70
+
71
+ def test_anomaly_injection_medium():
72
+ """Medium injection should produce more anomalies than easy."""
73
+ _, quarters = generate_company_data(seed=137, num_quarters=6)
74
+ _, anomalies = inject_anomalies(quarters, difficulty="medium", seed=1137)
75
+ assert len(anomalies) >= 3, f"Expected >=3 anomalies, got {len(anomalies)}"
76
+ print("PASS: test_anomaly_injection_medium")
77
+
78
+
79
+ def test_anomaly_injection_hard():
80
+ """Hard injection should produce 5+ anomalies."""
81
+ _, quarters = generate_company_data(seed=256, num_quarters=8)
82
+ _, anomalies = inject_anomalies(quarters, difficulty="hard", seed=1256)
83
+ assert len(anomalies) >= 4, f"Expected >=4 anomalies, got {len(anomalies)}"
84
+ # Should have some high-severity anomalies
85
+ max_sev = max(a.severity for a in anomalies)
86
+ assert max_sev >= 4, f"Hard task should have severity >= 4, got max {max_sev}"
87
+ print("PASS: test_anomaly_injection_hard")
88
+
89
+
90
+ def test_grader_perfect_score():
91
+ """Perfect flags should score close to 1.0."""
92
+ truths = [
93
+ GroundTruthAnomaly(
94
+ anomaly_id="a1", line_item="revenue", quarter="Q1 2023",
95
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
96
+ ),
97
+ GroundTruthAnomaly(
98
+ anomaly_id="a2", line_item="inventory", quarter="Q2 2023",
99
+ severity=4, anomaly_type=AnomalyType.INVENTORY_TURNOVER,
100
+ ),
101
+ ]
102
+ flags = [
103
+ AnomalyFlag(
104
+ line_item="revenue", quarter="Q1 2023",
105
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
106
+ explanation="Totals don't add up",
107
+ ),
108
+ AnomalyFlag(
109
+ line_item="inventory", quarter="Q2 2023",
110
+ severity=4, anomaly_type=AnomalyType.INVENTORY_TURNOVER,
111
+ explanation="Inventory spike",
112
+ ),
113
+ ]
114
+ result = grade(flags, truths)
115
+ assert result["score"] >= 0.9, f"Perfect flags should score >= 0.9, got {result['score']}"
116
+ assert result["precision"] == 1.0
117
+ assert result["recall"] == 1.0
118
+ assert result["false_positives"] == 0
119
+ print("PASS: test_grader_perfect_score")
120
+
121
+
122
+ def test_grader_partial_credit():
123
+ """Right location, wrong type should get partial credit."""
124
+ truths = [
125
+ GroundTruthAnomaly(
126
+ anomaly_id="a1", line_item="revenue", quarter="Q1 2023",
127
+ severity=3, anomaly_type=AnomalyType.CHANNEL_STUFFING,
128
+ ),
129
+ ]
130
+ flags = [
131
+ AnomalyFlag(
132
+ line_item="revenue", quarter="Q1 2023",
133
+ severity=3, anomaly_type=AnomalyType.IMPOSSIBLE_CHANGE, # wrong type
134
+ explanation="Revenue jumped too much",
135
+ ),
136
+ ]
137
+ result = grade(flags, truths)
138
+ assert 0.3 < result["score"] < 0.9, f"Partial credit score unexpected: {result['score']}"
139
+ assert result["precision"] == 0.5 # partial match
140
+ print("PASS: test_grader_partial_credit")
141
+
142
+
143
+ def test_grader_false_positives():
144
+ """All wrong flags should score low."""
145
+ truths = [
146
+ GroundTruthAnomaly(
147
+ anomaly_id="a1", line_item="revenue", quarter="Q1 2023",
148
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
149
+ ),
150
+ ]
151
+ flags = [
152
+ AnomalyFlag(
153
+ line_item="cash", quarter="Q3 2023",
154
+ severity=1, anomaly_type=AnomalyType.NEGATIVE_VALUE,
155
+ explanation="Wrong guess",
156
+ ),
157
+ AnomalyFlag(
158
+ line_item="inventory", quarter="Q2 2023",
159
+ severity=2, anomaly_type=AnomalyType.DUPLICATE_ENTRY,
160
+ explanation="Another wrong guess",
161
+ ),
162
+ ]
163
+ result = grade(flags, truths)
164
+ assert result["score"] < 0.2, f"All wrong flags should score < 0.2, got {result['score']}"
165
+ assert result["false_positives"] == 2
166
+ print("PASS: test_grader_false_positives")
167
+
168
+
169
+ def test_grader_empty_flags():
170
+ """No flags submitted should score 0."""
171
+ truths = [
172
+ GroundTruthAnomaly(
173
+ anomaly_id="a1", line_item="revenue", quarter="Q1 2023",
174
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
175
+ ),
176
+ ]
177
+ result = grade([], truths)
178
+ assert result["score"] == 0.0, f"Empty flags should score 0, got {result['score']}"
179
+ print("PASS: test_grader_empty_flags")
180
+
181
+
182
+ def test_grader_determinism():
183
+ """Grader should produce identical scores across 100 runs."""
184
+ truths = [
185
+ GroundTruthAnomaly(
186
+ anomaly_id="a1", line_item="revenue", quarter="Q1 2023",
187
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
188
+ ),
189
+ GroundTruthAnomaly(
190
+ anomaly_id="a2", line_item="inventory", quarter="Q2 2023",
191
+ severity=4, anomaly_type=AnomalyType.INVENTORY_TURNOVER,
192
+ ),
193
+ ]
194
+ flags = [
195
+ AnomalyFlag(
196
+ line_item="revenue", quarter="Q1 2023",
197
+ severity=3, anomaly_type=AnomalyType.ARITHMETIC_ERROR,
198
+ explanation="test",
199
+ ),
200
+ AnomalyFlag(
201
+ line_item="cash", quarter="Q1 2023",
202
+ severity=1, anomaly_type=AnomalyType.NEGATIVE_VALUE,
203
+ explanation="false positive",
204
+ ),
205
+ ]
206
+ first_score = grade(flags, truths)["score"]
207
+ for i in range(100):
208
+ score = grade(flags, truths)["score"]
209
+ assert score == first_score, f"Run {i}: score {score} != {first_score}"
210
+ print("PASS: test_grader_determinism (100 runs)")
211
+
212
+
213
+ def test_env_reset():
214
+ """reset() should return a valid observation."""
215
+ env = FinancialAnomalyEnv(task_id="easy")
216
+ obs = env.reset()
217
+ assert obs.company is not None
218
+ assert len(obs.quarters) >= 4
219
+ assert obs.step_number == 0
220
+ assert len(obs.prior_flags) == 0
221
+ print("PASS: test_env_reset")
222
+
223
+
224
+ def test_env_step_flag():
225
+ """step() with flag_anomaly should update state."""
226
+ env = FinancialAnomalyEnv(task_id="easy")
227
+ env.reset()
228
+
229
+ action = Action(
230
+ action_type=ActionType.FLAG_ANOMALY,
231
+ flag=AnomalyFlag(
232
+ line_item="revenue",
233
+ quarter="Q1 2022",
234
+ severity=2,
235
+ anomaly_type=AnomalyType.ARITHMETIC_ERROR,
236
+ explanation="Test flag",
237
+ ),
238
+ )
239
+ obs, reward, done, info = env.step(action)
240
+ assert info.flags_so_far == 1
241
+ assert obs.step_number == 1
242
+ assert not done
243
+ print("PASS: test_env_step_flag")
244
+
245
+
246
+ def test_env_step_submit():
247
+ """step() with submit_report should end the episode."""
248
+ env = FinancialAnomalyEnv(task_id="easy")
249
+ env.reset()
250
+
251
+ action = Action(action_type=ActionType.SUBMIT_REPORT)
252
+ obs, reward, done, info = env.step(action)
253
+ assert done is True
254
+ assert info.done_reason == "submitted"
255
+ print("PASS: test_env_step_submit")
256
+
257
+
258
+ def test_env_step_request_detail():
259
+ """step() with request_detail should return detail and cost -0.1."""
260
+ env = FinancialAnomalyEnv(task_id="easy")
261
+ obs = env.reset()
262
+ quarter_label = obs.quarters[0].quarter_label
263
+
264
+ action = Action(
265
+ action_type=ActionType.REQUEST_DETAIL,
266
+ detail_line_item="revenue",
267
+ detail_quarter=quarter_label,
268
+ )
269
+ obs, reward, done, info = env.step(action)
270
+ assert reward.step_reward == -0.1
271
+ assert obs.detail_response is not None
272
+ assert "components" in obs.detail_response
273
+ print("PASS: test_env_step_request_detail")
274
+
275
+
276
+ def test_env_state():
277
+ """state() should return accurate episode info."""
278
+ env = FinancialAnomalyEnv(task_id="easy")
279
+ env.reset()
280
+ state = env.state()
281
+ assert state.step_number == 0
282
+ assert state.done is False
283
+ assert state.task_id == "easy"
284
+ print("PASS: test_env_state")
285
+
286
+
287
+ def test_env_max_steps():
288
+ """Episode should end with penalty at max steps."""
289
+ env = FinancialAnomalyEnv(task_id="easy", max_steps=3)
290
+ env.reset()
291
+
292
+ for i in range(3):
293
+ action = Action(
294
+ action_type=ActionType.FLAG_ANOMALY,
295
+ flag=AnomalyFlag(
296
+ line_item="cash", quarter="Q1 2022",
297
+ severity=1, anomaly_type=AnomalyType.NEGATIVE_VALUE,
298
+ explanation="test",
299
+ ),
300
+ )
301
+ obs, reward, done, info = env.step(action)
302
+
303
+ assert done is True
304
+ assert info.done_reason == "max_steps"
305
+ print("PASS: test_env_max_steps")
306
+
307
+
308
+ def test_env_full_episode():
309
+ """Run a complete episode: reset -> flags -> submit -> score."""
310
+ env = FinancialAnomalyEnv(task_id="easy")
311
+ obs = env.reset()
312
+ gt = env.get_ground_truth()
313
+
314
+ # Flag all known anomalies
315
+ for anomaly in gt:
316
+ action = Action(
317
+ action_type=ActionType.FLAG_ANOMALY,
318
+ flag=AnomalyFlag(
319
+ line_item=anomaly.line_item,
320
+ quarter=anomaly.quarter,
321
+ severity=anomaly.severity,
322
+ anomaly_type=anomaly.anomaly_type,
323
+ explanation="Detected anomaly",
324
+ ),
325
+ )
326
+ obs, reward, done, info = env.step(action)
327
+
328
+ # Submit
329
+ action = Action(action_type=ActionType.SUBMIT_REPORT)
330
+ obs, reward, done, info = env.step(action)
331
+ assert done is True
332
+
333
+ score = env.get_final_score()
334
+ assert score["score"] >= 0.9, f"Perfect detection should score >= 0.9, got {score['score']}"
335
+ assert score["recall"] == 1.0
336
+ print(f"PASS: test_env_full_episode (score={score['score']})")
337
+
338
+
339
+ def test_utils_benfords():
340
+ """Benford's chi-squared should detect non-natural distributions."""
341
+ # Natural-ish distribution
342
+ natural = [123, 234, 345, 156, 267, 189, 112, 298, 143, 178,
343
+ 210, 320, 145, 256, 190, 115, 225, 335, 142, 260]
344
+ chi2_natural = benfords_chi_squared(natural)
345
+
346
+ # Fabricated: all start with 5 or 6
347
+ fabricated = [500, 600, 550, 650, 520, 620, 580, 640, 510, 690,
348
+ 560, 630, 570, 610, 540, 660, 530, 670, 590, 680]
349
+ chi2_fabricated = benfords_chi_squared(fabricated)
350
+
351
+ assert chi2_fabricated > chi2_natural, \
352
+ f"Fabricated data should have higher chi2: {chi2_fabricated} vs {chi2_natural}"
353
+ print("PASS: test_utils_benfords")
354
+
355
+
356
+ def test_utils_leading_digit():
357
+ """Leading digit extraction should work correctly."""
358
+ assert leading_digit(123) == 1
359
+ assert leading_digit(9876) == 9
360
+ assert leading_digit(-456) == 4
361
+ assert leading_digit(0) == 0
362
+ assert leading_digit(7) == 7
363
+ print("PASS: test_utils_leading_digit")
364
+
365
+
366
+ # ---------------------------------------------------------------------------
367
+ # Run all tests
368
+ # ---------------------------------------------------------------------------
369
+
370
+ if __name__ == "__main__":
371
+ tests = [
372
+ test_generator_produces_valid_data,
373
+ test_generator_deterministic,
374
+ test_anomaly_injection_easy,
375
+ test_anomaly_injection_medium,
376
+ test_anomaly_injection_hard,
377
+ test_grader_perfect_score,
378
+ test_grader_partial_credit,
379
+ test_grader_false_positives,
380
+ test_grader_empty_flags,
381
+ test_grader_determinism,
382
+ test_env_reset,
383
+ test_env_step_flag,
384
+ test_env_step_submit,
385
+ test_env_step_request_detail,
386
+ test_env_state,
387
+ test_env_max_steps,
388
+ test_env_full_episode,
389
+ test_utils_benfords,
390
+ test_utils_leading_digit,
391
+ ]
392
+
393
+ passed = 0
394
+ failed = 0
395
+ errors = []
396
+
397
+ print("=" * 60)
398
+ print("Financial Anomaly Detection - Test Suite")
399
+ print("=" * 60)
400
+ print()
401
+
402
+ for test_fn in tests:
403
+ try:
404
+ test_fn()
405
+ passed += 1
406
+ except Exception as e:
407
+ failed += 1
408
+ errors.append((test_fn.__name__, str(e)))
409
+ print(f"FAIL: {test_fn.__name__}: {e}")
410
+
411
+ print()
412
+ print("=" * 60)
413
+ print(f"Results: {passed} passed, {failed} failed, {len(tests)} total")
414
+ print("=" * 60)
415
+
416
+ if errors:
417
+ print("\nFailures:")
418
+ for name, err in errors:
419
+ print(f" {name}: {err}")
420
+ sys.exit(1)
421
+ else:
422
+ print("\nAll tests passed!")
423
+ sys.exit(0)