Python 做 Quant 的虚拟环境管理

Python 做 Quant 的虚拟环境管理

MacOS 管理虚拟环境有几种方案选择:

Anaconda(2/3), MiniConda(2), virtualenv, pyenv 等.

后两者小巧, 前两者功能丰富.

我是从 anaconda 过渡到 miniconda 的, 原因主要是因为 macOS 系统下使用使用 anaconda 虚拟环境的时候 vnpy 包一直报错.

下面简单记录一下 miniconda 的安装使用过程.

安装

下载 Miniconda: 下载地址

由于我是 macOS 所以选择了 macOS + Python 2.7 64-bit(.pkg installer), 下载好后直接双击安装即可, 安装目录可能是 /Users/${USERNAME}/miniconda2/ 或者 /miniconda2/, 这取决于是否只支持当前用户使用.

激活虚拟环境

创建一个虚拟环境, 名称为 py27: conda create -n py27 python=2.7

进入虚拟环境: conda activate py27

初次安装后, 进入虚拟环境的时候可能会提示错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
CommandNotFoundError: Your shell has not been properly configured to use 'conda activate'.
If your shell is Bash or a Bourne variant, enable conda for the current user with

$ echo ". /Users/admin/miniconda2/etc/profile.d/conda.sh" >> ~/.bash_profile

or, for all users, enable conda with

$ sudo ln -s /Users/admin/miniconda2/etc/profile.d/conda.sh /etc/profile.d/conda.sh

The options above will permanently enable the 'conda' command, but they do NOT
put conda's base (root) environment on PATH. To do so, run

$ conda activate

in your terminal, or to put the base environment on PATH permanently, run

$ echo "conda activate" >> ~/.bash_profile

Previous to conda 4.4, the recommended way to activate conda was to modify PATH in
your ~/.bash_profile file. You should manually remove the line that looks like

export PATH="/Users/admin/miniconda2/bin:$PATH"

^^^ The above line should NO LONGER be in your ~/.bash_profile file! ^^^

大致意思就是没有进行环境变量的配置, 执行:

1
2
3
4
5
echo ". /Users/admin/miniconda2/etc/profile.d/conda.sh" >> ~/.bash_profile
source ~/.bash_profile

echo ". /Users/admin/miniconda2/etc/profile.d/conda.sh" >> ~/.zshrc
source ~/.zshrc

安装其他依赖

安装完 Miniconda 之后不算完成, 想要使用 vnpy 还需要安装一些其他依赖, 我大致整理了一下可能需要安装的包, 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
conda --version
python --version
pip --version
ipython --version
which conda
which python
which pip
which ipython

brew install qt pyqt ta-lib
conda install -c quantopian ta-lib=0.4.9
conda install matplotlib spyder pyqt QtPy future pymongo pandas numpy
pip install bs4 tushare vnpy

虚拟环境切换

1
2
3
4
5
6
7
8
9
10
11
12
# 创建环境
conda create -n py36 python=3.6
conda create -n py27 python=2.7

# 删除环境 - 不要乱删啊
# conda remove -n py36 --all

# 激活环境
conda activate py36

# 退出环境
conda deactivate
Donate - Support to make this site better.
捐助 - 支持我让我做得更好.