[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-80679":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":13,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":16,"stars30d":17,"stars90d":15,"forks30d":15,"starsTrendScore":15,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":21,"hasPages":21,"topics":22,"createdAt":10,"pushedAt":10,"updatedAt":31,"readmeContent":32,"aiSummary":33,"trendingCount":15,"starSnapshotCount":15,"syncStatus":16,"lastSyncTime":34,"discoverSource":35},80679,"stata-cli","ashuiGordon\u002Fstata-cli","ashuiGordon","Stata CLI for Agent; Stata CLI Is All Reg Monkeys Need","https:\u002F\u002Fashuigordon.github.io\u002Fstata-cli\u002F",null,"Python",53,1,47,0,2,6,0.9,false,"main",true,[23,24,25,26,27,28,29,30],"ai-agent","cli","command-line-tool","data-science","econometrics","pystata","stata","statistics","2026-06-12 02:04:05","# stata-cli\n\n> **Stata CLI Is All Reg Monkeys Need**\n\n![stata-cli banner](assets\u002Fbanner.png)\n\n[![License: MIT](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-yellow.svg)](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT)\n[![Python Version](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython-%3E%3D3.9-blue.svg)](https:\u002F\u002Fwww.python.org\u002F)\n[![npm version](https:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002Fstata-cli.svg)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fstata-cli)\n\n[中文版](README.zh.md) | [English](README.md)\n\nA command-line interface for [Stata](https:\u002F\u002Fwww.stata.com\u002F) via PyStata — built for humans and AI Agents. Run Stata code, `.do` files, view data, get help, and export graphs, all from the terminal. Includes a daemon mode for sub-second execution.\n\n[Install](#installation--quick-start) · [AI Agent](#quick-start-ai-agent) · [Commands](#commands) · [Daemon](#daemon-mode) · [Advanced](#advanced-usage) · [Contributing](#contributing)\n\n## Why stata-cli?\n\n- **Agent-Native Design** — Structured JSON output, exit codes, and a [SKILL.md](SKILL.md) definition out of the box — AI Agents can operate Stata with zero extra setup\n- **Sub-Second Execution** — Daemon mode keeps PyStata alive in the background, reducing startup from ~2-3s to ~85ms (35x speedup)\n- **Full Coverage** — Run code, execute `.do` files, view data, browse help, export graphs, interrupt execution — everything you need from one binary\n- **AI-Friendly & Optimized** — Compact output mode, token limit management, structured JSON responses, and graph auto-naming — designed for Agent tool-use\n- **Open Source, Zero Barriers** — MIT license, ready to use, just `pip install`\n- **Up and Running in Seconds** — Auto-detects your Stata installation, from install to first command in 2 steps\n\n## Features\n\n| Category | Capabilities |\n|----------|-------------|\n| **Run Code** | Execute inline Stata code, multi-line blocks, or pipe from stdin |\n| **Do Files** | Run `.do` files with `\u002F\u002F\u002F` line continuation support and graph auto-naming |\n| **Data Viewer** | View current dataset as JSON with `if`-condition filtering and row limits |\n| **Variable Metadata** | Inspect variable names, types, formats, and labels via `vars` |\n| **Stored Results** | Retrieve r(), e(), s() results as structured JSON via `return` |\n| **Matrix Access** | Read Stata matrices (e.g. `e(b)`, `e(V)`) as JSON via `matrix` |\n| **Value Labels** | List and inspect value labels via `labels` |\n| **Macro Access** | Get\u002Fset Stata macros including `c()`, `e()`, `r()` system macros |\n| **Frame Management** | List Stata frames and current working frame via `frame` |\n| **Help System** | Browse Stata help topics with SMCL-to-plain-text conversion |\n| **Graph Export** | Auto-detect and export graphs as PNG\u002FSVG\u002FPDF to `~\u002F.stata-cli\u002Fgraphs\u002F` |\n| **Daemon Mode** | Persistent background process for sub-second execution; parallel sessions via `--session` |\n| **Output Control** | Compact mode, JSON output, token limit management, log file output |\n| **Interruption** | Send break signal to stop long-running commands |\n| **Skill Library** | Built-in Stata reference with 57 topics: syntax, econometrics, causal inference, packages |\n\n## Installation & Quick Start\n\n### Requirements\n\n- **Stata 17+** installed on your machine (provides the PyStata library)\n- Python 3.9+\n\n### Quick Start (Human Users)\n\n#### Install\n\nChoose **one** of the following methods:\n\n**Option 1 — From pip (recommended):**\n\n```bash\npip install stata-cli\n```\n\n**Option 2 — From npm \u002F npx (zero Python setup):**\n\n```bash\n# One-shot usage\nnpx stata-cli run \"display 1+1\"\n\n# Global install\nnpm install -g stata-cli\n```\n\nThe npm package is a thin wrapper that delegates to `uvx`, `pipx`, or `python3`.\n\n**Option 3 — From source:**\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002FashuiGordon\u002Fstata-cli.git\ncd stata-cli\npip install -e \".[data]\"\n```\n\n#### Use\n\n```bash\n# 1. Verify Stata is detected\nstata-cli detect\n\n# 2. Run your first command\nstata-cli run \"display 1+1\"\n\n# 3. Start daemon for fast execution\nstata-cli daemon start\nstata-cli run \"sysuse auto, clear\"    # ~85ms!\n```\n\n## Quick Start (AI Agent)\n\n> The following steps are for AI Agents calling `stata-cli` via the Bash tool.\n\n**Step 1 — Install**\n\n```bash\npip install stata-cli\n```\n\n**Step 2 — Verify Stata path**\n\n```bash\nstata-cli detect\n```\n\n**Step 3 — Start daemon (recommended)**\n\n```bash\nstata-cli daemon start\n```\n\n**Step 4 — Run commands**\n\n```bash\n# Inline code\nstata-cli run \"sysuse auto, clear\nregress price mpg weight\npredict yhat\"\n\n# Structured JSON output\nstata-cli --json run \"summarize price\"\n\n# View data\nstata-cli data --if \"price>10000\" --rows 50\n\n# Lookup command syntax\nstata-cli help regress\n```\n\n## Commands\n\n### `run` — Execute Stata Code\n\n```bash\nstata-cli run \"sysuse auto, clear\"\n\n# Multi-line\nstata-cli run \"sysuse auto, clear\nsummarize price mpg\nregress price mpg weight\"\n\n# Pipe from stdin\necho \"display 42\" | stata-cli run -\n```\n\n### `do` — Execute a .do File\n\n```bash\nstata-cli do analysis.do\nstata-cli --compact do long_script.do\n```\n\nDo files are preprocessed: `\u002F\u002F\u002F` line continuations are joined, and unnamed graph commands are auto-named for reliable export.\n\n### `data` — View Current Dataset\n\n```bash\nstata-cli data\nstata-cli data --if \"price>5000\" --rows 50\n```\n\nReturns the current dataset as JSON with columns, data, types, and row counts.\n\n### `help` — Browse Stata Help\n\n```bash\nstata-cli help regress\nstata-cli help summarize\n```\n\nDisplays help as plain text (SMCL markup is automatically converted).\n\n### `stop` — Interrupt Execution\n\n```bash\nstata-cli stop\n```\n\nSends a break signal to the running Stata command (daemon mode).\n\n### `detect` — Find Stata Installation\n\n```bash\nstata-cli detect\n```\n\nPrints the auto-detected Stata installation path.\n\n### `return` — Retrieve Stored Results\n\n```bash\nstata-cli return r         # r() results (after summarize, etc.)\nstata-cli return e         # e() results (after regress, etc.)\nstata-cli return s         # s() results\n```\n\nReturns r(), e(), or s() stored results as structured JSON — scalars, macros, and matrix references.\n\n### `vars` — Variable Metadata\n\n```bash\nstata-cli vars                # all variables\nstata-cli vars price mpg      # specific variables\n```\n\nReturns variable names, types, formats, and labels as JSON. More structured than `describe`.\n\n### `matrix` — Read Stata Matrices\n\n```bash\nstata-cli matrix e(b)         # coefficient vector\nstata-cli matrix e(V)         # variance-covariance matrix\n```\n\nReturns matrix data, dimensions, and row\u002Fcolumn names as JSON.\n\n### `labels` — Value Labels\n\n```bash\nstata-cli labels               # list all value label names\nstata-cli labels origin        # show value-label mapping\nstata-cli labels --var foreign # show label attached to a variable\n```\n\n### `macro` — Get\u002FSet Macros\n\n```bash\nstata-cli macro get \"c(current_date)\"\nstata-cli macro get \"e(cmd)\"\nstata-cli macro set myvar \"hello\"\n```\n\nAccess Stata macros including system macros (`c()`, `e()`, `r()`).\n\n### `frame` — List Frames\n\n```bash\nstata-cli frame\n```\n\nShows all Stata frames and the current working frame.\n\n### `skill` — Stata Reference Library\n\n```bash\nstata-cli skill                # overview: gotchas, patterns, topic routing table\nstata-cli skill --list         # list all 57 topics with descriptions\nstata-cli skill regression     # linear regression reference\nstata-cli skill did            # modern DiD packages (csdid, did_multiplegt)\nstata-cli skill reghdfe        # reghdfe package guide\n```\n\nBuilt-in reference library covering data management, econometrics, causal inference, graphics, Mata programming, and 20+ community packages. Aliases supported (e.g. `did` for `difference-in-differences`, `panel` for `panel-data`).\n\n## Daemon Mode\n\nThe daemon keeps PyStata alive in the background — reduces execution time from **~2-3s to ~85ms** (35x speedup).\n\n```bash\nstata-cli daemon start       # Start background daemon\nstata-cli run \"display 1\"    # Fast — auto-routes through daemon\nstata-cli daemon status      # Check daemon state (PID, uptime, idle)\nstata-cli daemon restart     # Clean restart (reset Stata state)\nstata-cli daemon stop        # Shut down\n```\n\n| Command | Description |\n|---------|-------------|\n| `daemon start` | Start the background daemon process |\n| `daemon stop` | Graceful shutdown |\n| `daemon stop --all` | Stop all running sessions |\n| `daemon status` | Show all running sessions (PID, uptime, idle) |\n| `daemon restart` | Stop + start (clean Stata state) |\n\nCommands auto-route through the daemon when it is running. Use `--no-daemon` to force direct execution.\n\nThe daemon auto-shuts down after 1 hour of inactivity (configurable with `--idle-timeout`).\n\n### Parallel Sessions\n\nRun multiple independent Stata instances — like opening multiple Stata windows:\n\n```bash\n# Start named sessions\nstata-cli --session proj_a daemon start\nstata-cli --session proj_b daemon start\n\n# Each session has its own data, estimates, and macros\nstata-cli --session proj_a run \"use project_a.dta, clear\"\nstata-cli --session proj_b run \"use project_b.dta, clear\"\n\n# Route any command to a specific session\nstata-cli --session proj_a run \"regress price mpg weight\"\nstata-cli --session proj_b return e\n```\n\n## Advanced Usage\n\n### Global Options\n\n| Option | Description | Default |\n|--------|-------------|---------|\n| `--stata-path PATH` | Stata installation directory | auto-detected |\n| `--edition [mp\\|se\\|be]` | Stata edition | `mp` |\n| `--session NAME` | Daemon session name (for parallel sessions) | `default` |\n| `--compact` | Strip verbose output noise | off |\n| `--json` | Structured JSON output | off |\n| `--timeout SECONDS` | Execution timeout | 600 |\n| `--max-tokens N` | Max output tokens (0=unlimited) | 0 |\n| `--no-daemon` | Force direct execution | off |\n| `--graphs-dir PATH` | Graph export directory | `~\u002F.stata-cli\u002Fgraphs\u002F` |\n| `--graph-format [png\\|svg\\|pdf]` | Graph export format | `png` |\n| `--log PATH` | Save output to a log file | off |\n\n### JSON Output\n\n```bash\nstata-cli --json run \"display 1+1\"\n```\n\n```json\n{\n  \"success\": true,\n  \"output\": \". display 1+1\\n2\",\n  \"error\": \"\",\n  \"execution_time\": 0.04,\n  \"return_code\": 0,\n  \"extra\": {}\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `success` | bool | Whether the command succeeded |\n| `output` | string | Stata output text |\n| `error` | string | Error message (if any) |\n| `execution_time` | float | Seconds elapsed |\n| `return_code` | int | Stata r-code (0 = ok) |\n| `extra` | dict | May contain `graphs` list with exported file paths |\n\n### Graph Export\n\nWhen Stata code creates graphs, they are automatically detected and exported as PNG:\n\n```bash\nstata-cli run \"sysuse auto, clear\nscatter price mpg\"\n```\n\n```\n[graph] graph1: \u002FUsers\u002Fyou\u002F.stata-cli\u002Fgraphs\u002Fexec-...\u002Fgraph1.png\n```\n\nIn JSON mode, graph paths appear under `extra.graphs`.\n\n### Token Limit Management\n\nFor long outputs, use `--max-tokens` to truncate and save the full output to a file:\n\n```bash\nstata-cli --max-tokens 500 run \"sysuse auto, clear\ndescribe\"\n```\n\nWhen output exceeds the limit, a preview is shown with a path to the full saved output.\n\n### Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `STATA_PATH` | Override Stata installation path |\n| `STATA_CLI_GRAPHS_DIR` | Override graph export directory |\n\n### Exit Codes\n\n| Code | Meaning |\n|------|---------|\n| 0 | Success |\n| 1 | Stata command error |\n| 2 | CLI usage error |\n| 3 | Stata not found \u002F init failure |\n\n## Agent Usage Pattern\n\n```bash\n# Full analysis workflow\nstata-cli run \"sysuse auto, clear\nsummarize price mpg\nregress price mpg weight\npredict yhat\nlist make price yhat in 1\u002F5\"\n\n# Retrieve regression results as structured JSON\nstata-cli return e\n\n# Get coefficient matrix\nstata-cli matrix e(b)\n\n# Inspect variable metadata\nstata-cli vars price mpg weight\n\n# Check value labels\nstata-cli labels --var foreign\n\n# Read system macros\nstata-cli macro get \"c(N)\"\n\n# Check data after loading\nstata-cli data --if \"price>10000\"\n\n# Lookup command syntax\nstata-cli help anova\n\n# Compact mode for less noise\nstata-cli --compact run \"sysuse auto, clear\ndescribe\"\n\n# JSON mode for structured parsing\nstata-cli --json run \"display 1+1\"\n\n# Export graph as SVG\nstata-cli --graph-format svg run \"scatter price mpg\"\n```\n\n## Contributing\n\nCommunity contributions are welcome! If you find a bug or have feature suggestions, please submit an [Issue](https:\u002F\u002Fgithub.com\u002FashuiGordon\u002Fstata-cli\u002Fissues) or [Pull Request](https:\u002F\u002Fgithub.com\u002FashuiGordon\u002Fstata-cli\u002Fpulls).\n\nFor major changes, we recommend discussing with us first via an Issue.\n\n## License\n\nThis project is licensed under the **MIT License**.\n","stata-cli 是一个基于 PyStata 的命令行工具，旨在为人类用户和AI代理提供高效运行Stata代码的环境。其核心功能包括通过命令行执行Stata代码、.do文件，查看数据集，获取帮助文档，以及导出图表等。技术特点上，该项目支持结构化的JSON输出、快速启动（约85毫秒）的守护进程模式、紧凑的输出格式和自动命名图表等功能，特别优化了与AI代理的交互体验。适用于需要频繁使用Stata进行数据分析、统计建模的研究人员或开发团队，尤其是那些希望将Stata集成到自动化工作流中的场景。","2026-06-11 04:01:37","CREATED_QUERY"]