方式二:Jupyter Notebook + nbstata

在 VSCode 中交互式运行 Stata

通过 nbstata 内核,可以在 Jupyter Notebook 中交互式运行 Stata 代码。配合 Quarto,还可以将 Notebook 渲染为 HTML 或 Word。这是 VSCode 环境下体验最流畅 的方式。

更多细节请参阅 nbstata 用户指南(中文版)

设置步骤

第 1 步:安装 Python

推荐安装 Miniconda。安装完成后,在终端中确认:

python --version   # 需要 3.10 或更高版本

第 2 步:安装 nbstata

pip install nbstata
python -m nbstata.install

第 3 步:配置 Stata 路径(如未自动检测到)

创建配置文件 ~/.config/nbstata/nbstata.conf

[nbstata]
stata_dir = /Applications/StataNow/StataMP         ; macOS 例子
stata_dir = C:\Program Files\StataNow\StataMP    ; Windows 例子
edition = mp

第 4 步:安装 VSCode 扩展

在 VSCode 扩展商店中安装:

  • Python(Microsoft)
  • Jupyter(Microsoft)

第 5 步:验证

在终端中运行:

jupyter kernelspec list

输出中应包含 nbstata。然后在 VSCode 中新建 Jupyter Notebook(Ctrl+Shift+PJupyter: Create New Blank Notebook),选择 nbstata 内核,在单元格中输入:

display "Hello, Stata in Jupyter!"

Shift+Enter 执行,如果看到输出,说明设置成功。

模板

在 VSCode 中新建 Jupyter Notebook,选择 nbstata 内核,按以下顺序创建单元格:

单元格 1(Markdown):

# 作业:Jupyter + nbstata 示例

**姓名:** 张三
**学号:** 20260001

单元格 2(Markdown):

## 1. 数据描述
加载数据并查看描述统计:

单元格 3(Code):

sysuse auto, clear
summarize price mpg weight

单元格 4(Markdown):

## 2. 散点图

单元格 5(Code):

scatter price mpg, title("Price vs. MPG")

单元格 6(Markdown):

## 3. 回归分析

单元格 7(Code):

regress price mpg weight

单元格 8(Markdown):

## 4. 结论
根据回归结果,mpg 和 weight 对价格均有显著影响。

生成文档

方法 A:直接导出

在 VSCode 中打开 Notebook,Ctrl+Shift+PJupyter: Export to HTML

方法 B:使用 Quarto(推荐)

先安装 Quarto,然后在终端运行:

quarto render homework_nbstata.ipynb --to html
quarto render homework_nbstata.ipynb --to docx

也可以直接编写 .qmd 文件(而非 .ipynb),在 YAML 头部指定 jupyter: nbstata,参考下面的 Quarto 模板:

---
title: "作业:Quarto + nbstata 示例"
author: "张三(20260001)"
format: html
jupyter: nbstata
---

## 1. 数据描述

::: {#26f2d0a2 .cell}
``` {.stata .cell-code}
sysuse auto, clear
summarize price mpg weight
```
:::


## 2. 散点图

::: {#ccc42580 .cell}
``` {.stata .cell-code}
scatter price mpg, title("Price vs. MPG")
```
:::


## 3. 回归分析

::: {#e22a7f6e .cell}
``` {.stata .cell-code}
regress price mpg weight
```
:::


回归结果显示,mpg 每增加一个单位,价格变化约为 `{stata} %9.2f _b[mpg]` 美元。