Algorithmic Trading

Algorithmic Trading

本文是学习 Mastering pandas for finance 一书第七章的笔记。由于我电脑上的 Python 是 3.7.1 版本的,无法安装 zipline 包,所以我只学习了这一章的开头部分。

准备工作

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# !/anaconda3/bin/python
# -*- coding: utf-8 -*-
"""
标题 : Algorithm·Trading
作者 : 程振兴
创建日期: 2019-03-25
"""
import pandas as pd
import numpy as np
import tushare as ts
import matplotlib.pyplot as plt
from datetime import datetime
from matplotlib import rcParams

pro = ts.pro_api('你的 Tushare 密钥')
from matplotlib.font_manager import FontProperties

# 中文字体
cnfont = FontProperties(fname='/Library/Fonts/Songti.ttc', size=14)
# 英文字体
enfont = FontProperties(fname='/Users/czx/Library/Fonts/RobotoSlab-Regular.ttf', size=14)
# 解决负号'-'显示为方块的问题
rcParams['axes.unicode_minus'] = False
rcParams['savefig.dpi'] = 300 # 图片像素
rcParams['figure.dpi'] = 300 # 分辨率

#==========================================================#

Simple moving average

Python
1
2
3
4
5
6
7
8
9
10
11
12
import pandas_datareader.data as web
msft = web.DataReader("MSFT", 'av-daily', \
access_key = '60JBG2Z4MJZFXM1E', \
start = datetime(2000, 1, 1), end = datetime(2014, 12, 31))
msft['MA7'] = msft.close.rolling(7).mean()
msft['MA30'] = msft.close.rolling(30).mean()
msft['MA90'] = msft.close.rolling(90).mean()
msft['MA120'] = msft.close.rolling(120).mean()
msft.index = pd.to_datetime(msft.index)
msft['2014'][['close', 'MA7', 'MA30', 'MA120']].plot()
plt.savefig("20190325a1.svg")
plt.show()

Python
1
2
3
msft['2002'][['close', 'MA7', 'MA30', 'MA120']].plot()
plt.savefig('20190325a2.svg')
plt.show()

Exponentially weighted moving average

Python
1
2
3
4
5
6
msft_ewma = msft[['close']].copy()
msft_ewma['MA90'] = msft_ewma.rolling(90).mean()
msft_ewma['EWMA90'] = msft_ewma['close'].ewm(90).mean()
msft_ewma.plot()
plt.savefig('20190325a3.svg')
plt.show()

Technical analysis techniques

Python
1
2
3
msft['2002-1':'2002-9'][['close', 'MA30']].plot()
plt.savefig('20190325a4.svg')
plt.show()

Python
1
2
3
msft['2002-1':'2002-6'][['close', 'MA30', 'MA90']].plot()
plt.savefig('20190325a5.svg')
plt.show()

# Python

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×