金融量化学习---Python, MySQL, Pandas

这里用来记录一些在金融领域,尤其是银行相关的资金、债券、票据中应用到的数据管理与分析, 编程等心得或笔记,以及个人的一点小小兴趣(易经八卦、藏密禅修)等

导航

好用的python项目

数据分析

Numpy

numpy中与金融有关的函数 https://www.cnblogs.com/traditional/p/11113862.html
**numpy-financial **
https://pypi.org/project/numpy-financial/
https://github.com/numpy/numpy-financial
Numpy是高性能科学计算和数据分析的基础包。 NumPy系统是Python的一种开源的数值计算扩展。NumPy(Numeric Python)提供了许多高级的数值编程工具,如:矩阵数据类型、矢量处理,以及精密的运算库。专为进行严格的数字处理而产生。

Pandas

十分钟掌握Pandas(上)
https://www.cnblogs.com/littlepage/p/11964838.html

ydata

https://ydata.ai/
https://github.com/ydataai

金融计算

quant-lib

下载:https://www.lfd.uci.edu/~gohlke/pythonlibs/#quantlib
在线文档:https://quantlib-python-docs.readthedocs.io/en/latest/
QuantLib Python Tutorials With Examples
(英文)http://gouthamanbalaraman.com/blog/quantlib-python-tutorials-with-examples.html
(中文)https://www.cnblogs.com/xuruilong100/p/8711520.html

相比TA-Lib在技术分析领域的地位,QuantLib在金融工程领域的地位可以说有过之而无不及。

参考其官方网站,QuantLib中包含的的模块如下(其中个人感觉国内比较有用的添加了中文注释):
Currencies and FX rates(货币相关)
Date and time calculations(日期和时间计算)
Calendars
Day counters
Design patterns
Financial instruments
Finite-differences framework
Lattice methods
Math tools
1-D Interpolations and corresponding traits
One-dimensional solvers
Optimizers(优化器)
Monte Carlo framework (蒙特卡洛模拟框架)
Numeric types
Output manipulators
Pricing engines(定价引擎)
Asian option engines(亚式期权)
Barrier option engines(障碍期权)
Basket option engines(篮子期权)
Cap/floor engines
Cliquet option engines
Forward option engines(远期期权)
Quanto option engines
Swaption engines
Vanilla option engines(普通期权)
QuantLib macros
Debugging macros
Numeric limits
Short-rate modelling framework(短期利率建模框架)
Stochastic processes(随机过程)
Term structures(期限结构)
Utilities

QuantLib实用例子:https://github.com/lballabio/QuantLib/tree/master/Examples

pyfinance

项目地址:https://github.com/bsolomon1124/pyfinance
https://pypi.org/project/pyfinance/
https://www.cnpython.com/pypi/pyfinance

pyfinance是为投资管理和证券收益分析而构建的Python分析包,主要是对面向定量金融的现有包进行补充,如pyfolio和pandas等。pyfinance包含六个模块,

datasets.py :金融数据下载(基于request进行数据爬虫,有些数据由于外网受限已经无法下载);
general.py:通用财务计算,例如主动份额计算,收益分配近似值和跟踪误差优化;
ols.py:回归分析,支持pandas滚动窗口回归;
options.py:期权衍生品计算和策略分析;
returns.py:通过CAPM框架对财务时间序列进行统计分析,旨在模拟FactSet Research Systems和Zephyr等软件的功能,并提高了速度和灵活性;
utils.py:基础架构。

Module Description

  • datasets.py Financial dataset download & assembly via requests.
  • general.py General-purpose financial computations, such as active share calculation, returns distribution approximation, and tracking error optimization.
  • ols.py Ordinary least-squares (OLS) regression, supporting static and rolling cases, built with a matrix formulation and implemented with NumPy.
  • options.py Vectorized option calculations, including Black-Scholes Merton European option valuation, Greeks, and implied volatility, as well as payoff determination for common money-spread option strategies.
  • returns.py Statistical analysis of financial time series through the CAPM framework, designed to mimic functionality of software such as FactSet Research Systems and Zephyr, with improved speed and flexibility.
  • utils.py Utilities not fitting into any of the above.

学习案例
【手把手教你】使用pyfinance进行证券收益分析
https://blog.csdn.net/ndhtou222/article/details/108544117

DROP

https://github.com/lakshmiDRIP/DROP
https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal

DROP is composed of three modules:

DROP implements libraries targeting analytics/risk, transaction cost analytics, asset liability analytics, capital, exposure, and margin analytics, valuation adjustment analytics, and portfolio construction analytics within and across fixed income, credit, commodity, equity, FX, and structured products. It also includes auxiliary libraries for graph algorithms, numerical analysis, numerical optimization, spline builder, model validation, statistical learning, and computational support

DROP is composed of three modules.
DROP Specifications
干货(太棒了):https://github.com/lakshmiDRIP/DROP/blob/master/Docs/Internal/FixedIncomeAnalytics/FixedIncomeAnalytics_v3.11.pdf
Main => https://lakshmidrip.github.io/DROP/
Wiki => https://github.com/lakshmiDRIP/DROP/wiki
GitHub => https://github.com/lakshmiDRIP/DROP
Repo Layout Taxonomy => https://lakshmidrip.github.io/DROP/Taxonomy.md
Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html
Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal
Release Versions => https://lakshmidrip.github.io/DROP/version.html
Community Credits => https://lakshmidrip.github.io/DROP/credits.html
Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues
JUnit => https://lakshmidrip.github.io/DROP/junit/index.html
Jacoco => https://lakshmidrip.github.io/DROP/jacoco/index.html

Product Core Module => Fixed Income Product Analytics, Loan Analytics, and Transaction Cost Analytics.
Portfolio Core Module => Portfolio Contruction and Asset Liability, along with Exposure, Margin, XVA, and Capital Analytics.
Computation Core Module => Algorithm/Computation Support, Function Analysis, Model Validation, Numerical Analysis, Numerical Optimizer, Spline Builder, Graph Algorithms, and Statistical Learning.

pyfolio

https://github.com/quantopian/pyfolio

financepy

项目地址:
https://github.com/domokane/FinancePy
学习案例
https://github.com/domokane/FinancePy-Conference-Notebooks

Overview
FinancePy is a python-based library that is currently in beta version. It covers the following functionality:

Valuation and risk models for a wide range of equity, FX, interest rate and credit derivatives.
Although it is written entirely in Python, it can achieve speeds comparable to C++ by using Numba. As a result the user has both the ability to examine the underlying code and the ability to perform pricing and risk at speeds which compare to a library written in C++.
Contact author at quant@financepy.com.

pyportfolioopt 资产组合优化

pip install PyPortfolioOpt
它的安装依赖于cvxpy等。
https://pyportfolioopt.readthedocs.io/en/latest/

TA-Lib

https://ta-lib.org/hdr_dw.html
如果直接pip install TA-Lib不成功,出现 Failed building wheel for TA-Lib
可以试试这个网址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib
下载好相应的包之后,再用下面的命令安装
pip install C:\Users\Administrator\Downloads\TA_Lib-0.4.17-cp35-cp35m-win_amd64.whl

还有人说是因为缺了这个lxml包:
在这里下载对应的.whl文件,注意别改文件名!
http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

Ctrl + F,输入lxml,找到下面这段

Lxml, a binding for the libxml2 and libxslt libraries.
lxml‑3.4.4‑cp27‑none‑win32.whl
lxml‑3.4.4‑cp27‑none‑win_amd64.whl
lxml‑3.4.4‑cp33‑none‑win32.whl
lxml‑3.4.4‑cp33‑none‑win_amd64.whl
lxml‑3.4.4‑cp34‑none‑win32.whl
lxml‑3.4.4‑cp34‑none‑win_amd64.whl
lxml‑3.4.4‑cp35‑none‑win32.whl
lxml‑3.4.4‑cp35‑none‑win_amd64.whl

cp后面是Python的版本号,27表示2.7,根据你的Python版本选择下载。

文本图形

Graphviz 绘制关系图

graphviz实际上是一个绘图工具,可以根据dot脚本画出树形图等。
windows安装

  1. 安装graphviz软件:https://graphviz.gitlab.io/_pages/Download/Download_windows.html
  2. 配置环境变量:把bin文件夹的路径加入到环境变量path里
  3. 安装python的graphviz模块:pip install graphviz
    http://www.graphviz.org/

安装使用指南

@startuml
digraph G {
    main -> parse -> execute;
    main -> init;
    main -> cleanup;
    execute -> make_string;
    execute -> printf;
    init -> make_string;
    main -> printf;
    execute -> compare;
}
@enduml

@startuml order
hide empty description
[*] --> 待处理
待处理 : 商家待处理
待处理 --> 待使用:商家排座
待使用 --> 已使用:商家扫码入座
已使用 : 已使用待结账

state 退款{
 待使用 --> 退款中:申请退款
 退款中--> 退款成功:商家审核
 退款中--> 退款失败:商家审核
 待使用 --> 退款成功:商家退款
}

待使用 --> 已取消:用户取消
待使用 --> 已取消:商家取消

待处理 --> 待处理:用户修改订单
待使用 --> 待处理:用户修改订单

已使用 --> 待评价:用户结账
已使用 --> 待评价:商家结账
待评价 : 已使用已结账
待评价 --> [*]:用户评价
@enduml

python-docx 和 docxtpl

python读写doc文件的应用, python-docx 用于新生成文档比较方便, docxtpl 用于填写已有模板方便

pyecharts

https://github.com/pyecharts/pyecharts-gallery

pdfplumber

PDF文档读写应用

几个例子:
https://github.com/jsvine/pdfplumber/tree/stable/examples/notebooks
PDFPlumber使用入门
https://blog.csdn.net/weixin_48629601/article/details/107224376
https://cloud.tencent.com/developer/article/1709212

tesseract OCR文字识别

OCR,即Optical Character Recognition,光学字符识别,

https://digi.bib.uni-mannheim.de/tesseract/
https://github.com/tesseract-ocr/tesseract

pygwalker可视化工具

PyGWalker用于简化Jupyter Notebook工作流。无需复杂的数据分析和数据可视化步骤,您可以使用PyGWalker把 pandas dataframe 转化为可交互的图形界面进行分析。想象一下:在Jupyter Notebook 中跑起来一个类Tableau/PowerBI风格的界面,通过简单的拖放操作,就可以完成数据分析和可视化的操作。

Altair

它是一个专为Python编写的可视化软件包,它能让数据科学家更多地关注数据本身和其内在的联系。
图库示例:https://altair-viz.github.io/gallery/
用户手册:https://altair-viz.github.io/user_guide/data.html#user-guide-data

chart.show()需要altair_viewer, altair-data-server的支持
http://github.com/altair-viz/altair_viewer
pip install altair_viewer
https://pypi.org/project/altair-data-server/#files
更多encode()方法,大家可以参照以下网址进行了解:
https://altair-viz.github.io/user_guide/encoding.html
教程:
https://blog.csdn.net/pyjishu/article/details/115768951
https://zhuanlan.zhihu.com/p/452820776

数学计算

SymPy

核心能力:SymPy是一个符号计算的Python库。它的目标是成为一个全功能的计算机代数系统,同时保持代码简洁、易于理解和扩展。它完全由Python写成,不依赖于外部库。
SymPy支持符号计算、高精度计算、模式匹配、绘图、解方程、微积分、组合数学、离散数学、几何学、概率与统计、物理学等方面的功能。
https://www.sympy.org/zh/index.html
https://github.com/sympy/sympy/
具体包括:多项式/演算/解方程/Combinatorics/离散数学/矩阵/几何学/绘图/物理学/统计/Cryptography/Parsing

from sympy import init_printing, integrate, log, sqrt, symbols
init_printing()
x = symbols('x')
g = sqrt(x + log(x))
f = (x ** 2 + 2 * x + 1 + (3 * x + 1) * g) / (x * g * (x + g))

输出(公式):

CVXOPT

CVXOPT is a free software package for convex optimization based on the Python programming language. It can be used with the interactive Python interpreter, on the command line by executing Python scripts, or integrated in other software via Python extension modules. Its main purpose is to make the development of software for convex optimization applications straightforward by building on Python’s extensive standard library and on the strengths of Python as a high-level programming language.
案例:
http://cvxopt.org/examples/index.html

cvxpy

它的安装依赖于MS Visual C++ 14.0 or greater, 需要下载 https://visualstudio.microsoft.com/zh-hans/visual-cpp-build-tools/

Scipy

pulp

爬虫

spider-flow 无需代码的爬虫

https://www.spiderflow.org/
https://github.com/ssssssss-team/spider-flow

GUI设计

主流的Python GUI库有:

  1. Tkinter:Python自带的GUI库,简单易用,但界面较差。
  2. PyQt:跨平台的库,基于Qt,功能强大,界面美观,学习曲线较高。
  3. wxPython:老牌的跨平台库,界面不及PyQt但也不俗,较易上手。
  4. Kivy:主打跨平台的移动应用开发,支持多点触控等,主要用于开发安卓和IOS APP。
  5. dearpygui:一款新的简单易用的GUI库,支持跨平台,界面较简洁,学习成本低。
  6. Pygame:主要用于游戏开发,支持访问键盘、鼠标、游戏手柄等设备。
  7. Nicegui: NiceGUI is an open-source Python library to write graphical user interfaces which run in the browser.
  8. PySimpleGUI:

除此之外,还有其他选择如:

  • PySide:Qt的另一个Python绑定,功能与PyQt类似。
  • Qt for Python(PySide2):最新Qt的Python绑定,集成PyQt5和PySide2的优点。
  • Flask:虽非GUI库,但可以用来构建网页GUI,展现在浏览器中。
  • Tornado:同Flask,基于web的GUI方案。

PySimpleGUI

https://www.pysimplegui.org/en/latest/

手册:https://pysimplegui.readthedocs.io/en/latest/
Github:https://github.com/PySimpleGUI/PySimpleGUI
案例:
https://zhuanlan.zhihu.com/p/514540346

NiceGUI (run in browser)

https://nicegui.io/
NiceGUI is an open-source Python library to write graphical user interfaces which run in the browser.

wxpython GUI界面程序

https://wxpython.org/

pip install wxPython  (注意它区分大小写)
pip install wxPython -i https://pypi.tuna.tsinghua.edu.cn/simple

baidu文库教程:
https://wenku.baidu.com/view/214bf71eec3a87c24028c4e7.html
易百教程
https://www.yiibai.com/wxpython/wxpython_hello_world.html

dearpygui

https://www.osgeo.cn/dearpygui/
https://pypi.org/project/dearpygui/
https://dearpygui.readthedocs.io/en/latest/index.html

dearPyGui是一个易于使用的、动态的、GPU加速的、跨平台的、适用于Python的图形用户界面工具包(GUI)。它是用 Dear ImGui “建造的” 。
功能包括传统的图形用户界面元素,如按钮、单选按钮、菜单和创建功能布局的各种方法。
此外,DPG拥有令人难以置信的各种动态绘图、表格、绘图、调试器和多种资源查看器。
DPG非常适合于创建简单的用户界面以及开发复杂且要求苛刻的图形界面。
DPG为开发科学、工程、游戏、数据科学和其他需要快速交互界面的应用程序提供了坚实的框架。

教程:
https://zhuanlan.zhihu.com/p/262853284
https://www.jianshu.com/p/36e527888c5f

deargui和nicegui的区别和对比(以下答案是chatgpt给我的)

deargui和nicegui都是知名的Python GUI库,用于构建图形界面应用程序。两者有以下主要区别:
deargui:

  1. 老牌库,开发团队维护多年,社区活跃,资料丰富。
  2. 基于Tkinter,集成度高,学习曲线低,开发效率高。
  3. 支持Python 2和3,跨平台(Windows,MacOS,Linux)。
  4. 基本控件丰富,布局方便,代码结构简单。适合初学者和快速开发。
    **nicegui: **
  5. 近年流行的新库,开发活跃,不断改进和发布新版本。
  6. 基于PyQt5,界面美观,性能较高,开发出的软件体验好。
  7. 仅支持Python 3和PyQt5。
  8. 控件和布局方式较复杂,学习曲线较高,但可以开发出高大上的界面。
    综上,如果要我选一个的话,我会根据以下考虑进行选择:
  9. 如果是初学者,或者需要快速开发跨平台APP,我会选择deargui。它简单易学,开发效率高,且支持旧版本Python。
  10. 如果需要开发性能高和界面高大上的软件,同时我也熟悉PyQt5,那么会选择nicegui。它可以开发出更加专业的应用程序。
  11. 两者也可结合,比如用deargui快速开发原型,然后用nicegui重构界面,提高用户体验。
  12. 若两者都不太满意,也可以选择更强大的Qt Desinger或WxPython等GUI库。
    所以,总体来说,deargui更适合入门和快速开发,nicegui更适合高级应用开发。但两者也可根据需要相互补充。开发人员可以根据项目需求和自身技术实力选择更合适的库。 (已编辑)

Gradio

可以快速生成交互式页面,主要用于AI领域
Gradio官网:https://www.gradio.app/
Gradio官方文档:https://gradio.app/docs
使用Gradio的项目「Anime2Sketch」:https://www.gradio.app/hub/AK391/Anime2Sketch
个人博客:小林的思考薄 | 学海浮沉

streamlit (run in browser)

一个傻瓜式构建可视化web的程序
Streamlit库官方地址:https://streamlit.io/
API文档地址:https://docs.streamlit.io/

Streamlit库基本介绍
Streamlit是一个基于 Python 的 Web 应用程序框架,致力于以更高效、更灵活的方式可视化数据,并分析结果。它是一个开源库,可以帮助数据科学家和学者在短时间内开发机器学习 (ML) 可视化仪表板。只需几行代码,我们就可以构建并部署强大的数据应用程序。

其实就是用Python语言写一个本地Web,应用场景常常是机器学习可视化(当然也可做其他的图表分析等),不需要任何Web前后端开发经验(事实上我也没有)。注意我们写出的Web只有本地可以访问,要接入互联网还需要其他进阶方法!

我用下来整体体会是这个库集成度很高,功能都是完整地打包入完整的API里了,所以使用起来非常简单快捷。但集成度高也有缺点,例如设计的自由度较低,诸如前端说明字的位置、大小等不能直接实现,需要借助HTML、CSS样式表等进阶手段完成。

https://docs.streamlit.io/library/cheatsheet

YouTube tutorials
Here’s a list of these YouTube channels about Streamlit:

Streamlit. The official Streamlit YouTube channel with official announcements of the latest features.
Data Professor. My YouTube channel with videos on data science and bioinformatics and a growing playlist of 30 videos on Streamlit.
JCharisTech. Jesse’s YouTube channel with tutorial videos on Python and Streamlit and with a playlist of almost 70 videos on Streamlit.
1littlecoder. AbdulMajed’s YouTube channel with tutorial videos on Python and Streamlit and with a playlist of almost 20 videos on Streamlit.

pyqtgraph

https://www.pyqtgraph.org/
PyQtGraph是一个基于PyQt / PySide和numpy构建的纯python图形和GUI库。它旨在用于 数学/科学/工程应用。尽管是 完全用 Python 编写,由于其繁重,该库非常快 利用NumPy进行数字处理,利用Qt的GraphicsView框架进行快速显示。PyQtGraph在MIT开源许可证下分发。
主要特点

  • 交互式视图框中的基本 2D 打印
  • 折线图和散点图
  • 数据可以通过鼠标平移/缩放
  • 用于实时数据显示和交互的快速绘图
  • 通过交互式查找表和电平控制显示图像
  • 显示大多数数据类型(整数或浮点数;任何位深度;RGB, RGBA,或亮度)
  • 任意切片多维图像的功能 角度(非常适合 MRI 数据)
  • 视频显示或实时交互的快速更新
  • 3D图形系统(需要Python-OpenGL绑定)
  • 体积数据呈现
  • 3D 曲面图和散点图
  • 通过等值面生成进行网格渲染
  • 交互式视口使用鼠标旋转/缩放
  • 基本 3D 场景图,便于编程
  • 数据选择/标记和感兴趣区域控制
  • 交互式标记垂直/水平位置和区域 情节
  • 用于从图像中选择任意区域的小部件和 自动切片数据以匹配
  • 轻松生成新图形
  • 2D图形使用Qt的GraphicsView框架,这是高度的 有能力和成熟。
  • 3D 图形使用 OpenGL
  • 所有图形都使用场景图来管理项目;新图形 项目易于创建。
  • 对科学/工程有用的小部件和模块库 应用
  • 用于交互式原型的流程图小部件。
  • 接口类似于LabView(通过电线连接的节点)。
  • 用于显示/编辑层次结构的参数树小部件 参数(类似于大多数 GUI 设计应用程序使用的参数)。
  • 具有异常捕获功能的交互式 python 控制台。
  • 非常适合调试/内省以及高级用户 互动。
  • 多过程控制允许远程绘图,Qt信号 跨流程连接,非常简单的在线连接 并行。
  • 坞站系统允许用户重新排列GUI组件。
  • 类似于Qt的扩展坞系统,但更灵活一些, 可编程序。
  • 颜色渐变编辑器
  • 带 SI 单位显示和对数步进的旋转盒

杂项功能

鼠标和键盘控制 pyautogui

教程:
https://zhuanlan.zhihu.com/p/302592540

词云图 stylecloud

stylecloud 项目地址:https://github.com/minimaxir/stylecloud
pip3 install stylecloud
这款工具可以帮助生成风格多样的词云,包括梯度和图标形状!
stylecloud 是一个 Python 包,它基于流行的 word_cloud 包,并添加了一些有用的功能,从而创建出独特的词云。stylecloud 具备以下特点:
为词云提供(任意大小)的图标形状(通过 Font Awesome 5.11.2 获得);
支持高级调色板(通过 palettable 实现);
为上述调色板提供直接梯度;
支持读取文本文件,或预生成的 CSV 文件(包含单词和数字);
提供命令行接口。
更换中文字体,支持中文词云
stylecloud 包由数据科学家 Max Woolf 创建,是对其 2016 年风格化词云项目的较正式实现。
你可以在 stylecloud-examples repo 中查看 stylecloud 的更多示例,比如如何基于 Twitter 和 Reddit 数据制作 stylecloud。
地址:https://github.com/minimaxir/stylecloud-examples

lunar-python

无第三方依赖的公历(阳历)和农历(阴历、老黄历)工具,支持节假日、星座、儒略日、干支、生肖、节气、节日、彭祖百忌、每日宜忌、吉神宜趋凶煞宜忌、吉神(喜神/福神/财神/阳贵神/阴贵神)方位、胎神方位、冲煞、纳音、星宿、八字、五行、十神、建除十二值星、青龙名堂等十二神、黄道黑道日及吉凶等。lunar is a calendar library for Solar and Chinese Lunar.

https://github.com/6tail/lunar-python
http://6tail.cn/calendar/api.html

示例

pip install lunar_python
from lunar_python import Lunar

# 通过指定年月日初始化阴历
lunar = Lunar.fromYmd(1986, 4, 21)
# 打印阴历
print(lunar.toFullString())
# 阴历转阳历并打印
print(lunar.getSolar().toFullString())

输出结果:
一九八六年四月廿一 丙寅(虎)年 癸巳(蛇)月 癸酉(鸡)日 子(鼠)时 纳音[炉中火 长流水 剑锋金 桑柘木] 星期四 北方玄武 星宿[斗木獬](吉) 彭祖百忌[癸不词讼理弱敌强 酉不会客醉坐颠狂] 喜神方位[巽](东南) 阳贵神方位[巽](东南) 阴贵神方位[震](正东) 福神方位[兑](正西) 财神方位[离](正南) 冲[(丁卯)兔] 煞[东]
1986-05-29 00:00:00 星期四 双子座

you-get

这是一款开源的命令行视频下载工具,它支持多个视频网站,包括youtube, Vimeo, Bilibili等
pip install you-get

posted on 2020-10-27 09:26  chengjon  阅读(1290)  评论(0编辑  收藏  举报