## 交易系统

• 1、市场----买卖什么
• 2、头寸规模----买卖多少
• 3、入市----何时买入
• 4、止损----何时退出亏损的头寸
• 5、止盈----何时退出盈利的头寸
• 6、离市----何时离市

### 简单的示例

• 买卖A股
• 全仓
• 当日涨幅超过3%买入。
• 当持有头寸亏损超过3%，平仓
• 当日跌幅大于3%或者三个连续阴线

## 数据获取及处理

### python环境安装

``安装Anaconda(python2版本)``

### 安装tushare

``pip install tushare``

### 获取行情数据

``````import pandas as pd
import tushare as ts

# 通过股票代码获取股票数据,这里没有指定开始及结束日期
df = ts.get_k_data("300104")

# 查看前十条数据

# 查看后十条数据
df.tail()

# 将数据的index转换成date字段对应的日期
df.index = pd.to_datetime(df.date)

# 将多余的date字段删除
df.drop("date", inplace=True, axis=1)``````

### 计算常用指标

``````# 计算5,15,50日的移动平均线, MA5, MA15, MA50
days = [5, 15, 50]
for ma in days:
column_name = "MA{}".format(ma)
df[column_name] = pd.rolling_mean(df.close, ma)

# 计算浮动比例
df["pchange"] = df.close.pct_change()
# 计算浮动点数
df["change"] = df.close.diff()``````

``````df.head()
Out[13]:
open  close   high    low    volume    code     MA5  MA15  MA50  \
date
2013-11-29  9.396  9.741  9.870  9.389  146587.0  300104     NaN   NaN   NaN
2013-12-02  9.298  8.768  9.344  8.768  177127.0  300104     NaN   NaN   NaN
2013-12-03  8.142  8.414  8.546  7.890  176305.0  300104     NaN   NaN   NaN
2013-12-04  8.391  8.072  8.607  8.053  120115.0  300104     NaN   NaN   NaN
2013-12-05  7.983  7.366  8.108  7.280  253764.0  300104  8.4722   NaN   NaN

pchange  change
date
2013-11-29       NaN     NaN
2013-12-02 -0.099887  -0.973
2013-12-03 -0.040374  -0.354
2013-12-04 -0.040647  -0.342 ``````

### 可视化

#### 走势图

``df[["close", "MA5", "MA15", "MA50"]].plot(figsiz=(10,18))``

### k线图

``````import matplotplib.pyplot as plt
from matplotlib.daet import DateFormatter
from matplotlib.finance import date2num, candlestick_ohlc

def candlePlot(data, title=""):
data["date"] = [date2num(pd.to_datetime(x)) for x in data.index]
dataList = [tuple(x) for x in data[
["date", "open", "high", "low", "close"]].values]

ax = plt.subplot()
ax.set_title(title)
ax.xaxis.set_major_formatter(DateFormatter("%y-%m-%d"))
candlestick_ohlc(ax, dataList, width=0.7, colorup="r", colordown="g")
plt.setp(plt.gca().get_xticklabels(), rotation=50,
horizontalalignment="center")
fig = plt.gcf()
fig.set_size_inches(20, 15)
plt.grid(True)

candlePlot(df)``````

## 策略测试

### 手动撸代码

``````# 导入相关模块
import tushare as ts
import pandas as pd

# 获取数据
df = ts.get_k_data("000725")

# 处理数据
df.index = pd.to_datetime(df.date)
df.drop("date", axis=1, inplace=True)

# 计算浮动比例
df["pchange"] = df.close.pct_change()
# 计算浮动点数
df["change"] = df.close.diff()

# 查看当前数据数据前五行
open  close   high    low      volume    code   pchange  change
date
2015-07-20  4.264  4.234  4.342  4.165  13036186.0  000725       NaN     NaN
2015-07-21  4.136  4.195  4.274  4.096   8776773.0  000725 -0.009211  -0.039
2015-07-22  4.175  4.146  4.214  4.067   9083703.0  000725 -0.011681  -0.049
2015-07-23  4.136  4.254  4.283  4.096  12792734.0  000725  0.026049   0.108
2015-07-24  4.224  4.136  4.254  4.106  13009620.0  000725 -0.027739  -0.118

# 设定回撤值
withdraw = 0.03
# 设定突破值
breakthrough = 0.03
# 设定账户资金
account = 10000
# 持有仓位手数
position = 0

global account, position
# 一手价格
one = bar.close * 100
position = account // one
account = account - (position * one)

def sell(bar):
global account, position
# 一手价格
print("{}: sell {}".format(bar.date, bar.close))
one = bar.close * 100
account += position * one
position = 0

print("开始时间投资时间: ", df.iloc[0].date)
for date in df.index:
bar = df.loc[date]
if bar.pchange and bar.pchange > breakthrough and position == 0:
elif bar.pchange and bar.pchange < withdraw and position > 0:
sell(bar)

print("最终可有现金: ", account)
print("最终持有市值: ", position * df.iloc[-1].close * 100)``````

``````开始时间投资时间:  2015-07-20
2015-07-30: sell 3.653
......
2018-02-27: sell 5.71

### 借助测试框架

#### 简单使用

``````from pyalgotrade import strategy

# 自定义事件窗口类
class DiffEventWindow(technical.EventWindow):
def __init__(self, period):
assert(period > 0)
super(DiffEventWindow, self).__init__(period)
self.__value = None

def onNewValue(self, dateTime, value):
super(DiffEventWindow, self).onNewValue(dateTime, value)
if self.windowFull():
lastValue = self.getValues()[0]
nowValue = self.getValues()[1]
self.__value = (nowValue - lastValue) / lastValue

def getValue(self):
return self.__value

# 自定义指标
class Diff(technical.EventBasedFilter):
def __init__(self, dataSeries, period, maxLen=None):
super(Diff, self).__init__(dataSeries, DiffEventWindow(period), maxLen)

# 定义自己的策略
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, diffPeriod=2):
# 传入feed及初始账户资金
super(MyStrategy, self).__init__(feed, 10000)
self.__instrument = instrument
self.__position = None
self.__prices = feed[instrument].getPriceDataSeries()
self.__diff = Diff(self.__prices, diffPeriod)
self.__break = 0.03
self.__withdown = -0.03

def getDiff(self):
return self.__diff

def onEnterCanceled(self, position):
self.__position = None

def onEnterOk(self, position):
execInfo = position.getEntryOrder().getExecutionInfo()

def onExitOk(self, position):
execInfo = position.getExitOrder().getExecutionInfo()
self.info("SELL at \$%.2f" % (execInfo.getPrice()))
self.__position = None

def onExitCanceled(self, position):
# If the exit was canceled, re-submit it.
self.__position.exitMarket()

def onBars(self, bars):
account = self.getBroker().getCash()
bar = bars[self.__instrument]
if self.__position is None:
one = bar.getPrice() * 100
oneUnit = account // one
if oneUnit > 0 and self.__diff[-1] > self.__break:
self.__position = self.enterLong(self.__instrument, oneUnit * 100, True)
elif self.__diff[-1] < self.__withdown and not self.__position.exitActive():
self.__position.exitMarket()

def runStrategy():
# 下载数据
jdf = ts.get_k_data("000725")

jdf.columns = ["Date", "Open", "Close", "High", "Low", "Volume", "code", "Adj Close"]

# 将数据保存成本地csv文件
jdf.to_csv("jdf.csv", index=False)

feed = yahoofeed.Feed()

myStrategy = MyStrategy(feed, "jdf")

myStrategy.run()
print("Final portfolio value: \$%.2f" % myStrategy.getResult())

runStrategy()
``````

``````2015-07-30 00:00:00 strategy [INFO] BUY at \$3.78
2015-07-31 00:00:00 strategy [INFO] SELL at \$3.57
2015-08-05 00:00:00 strategy [INFO] BUY at \$3.73
2015-08-06 00:00:00 strategy [INFO] SELL at \$3.56
...
2018-02-13 00:00:00 strategy [INFO] BUY at \$5.45
Final portfolio value: \$7877.30``````

### 策略可视化

``````from pyalgotrade import strategy

class DiffEventWindow(technical.EventWindow):
def __init__(self, period):
assert(period > 0)
super(DiffEventWindow, self).__init__(period)
self.__value = None

def onNewValue(self, dateTime, value):
super(DiffEventWindow, self).onNewValue(dateTime, value)
if self.windowFull():
lastValue = self.getValues()[0]
nowValue = self.getValues()[1]
self.__value = (nowValue - lastValue) / lastValue

def getValue(self):
return self.__value

class Diff(technical.EventBasedFilter):
def __init__(self, dataSeries, period, maxLen=None):
super(Diff, self).__init__(dataSeries, DiffEventWindow(period), maxLen)

class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument, diffPeriod=2):
super(MyStrategy, self).__init__(feed, 10000)
self.__instrument = instrument
self.__position = None
self.__prices = feed[instrument].getPriceDataSeries()
self.__diff = Diff(self.__prices, diffPeriod)
self.__break = 0.03
self.__withdown = -0.03

def getDiff(self):
return self.__diff

def onEnterCanceled(self, position):
self.__position = None

def onEnterOk(self, position):
execInfo = position.getEntryOrder().getExecutionInfo()

def onExitOk(self, position):
execInfo = position.getExitOrder().getExecutionInfo()
self.info("SELL at \$%.2f" % (execInfo.getPrice()))
self.__position = None

def onExitCanceled(self, position):
# If the exit was canceled, re-submit it.
self.__position.exitMarket()

def onBars(self, bars):
account = self.getBroker().getCash()
bar = bars[self.__instrument]
if self.__position is None:
one = bar.getPrice() * 100
oneUnit = account // one
if oneUnit > 0 and self.__diff[-1] > self.__break:
self.__position = self.enterLong(self.__instrument, oneUnit * 100, True)
elif self.__diff[-1] < self.__withdown and not self.__position.exitActive():
self.__position.exitMarket()

def runStrategy():
# 下载数据
jdf = ts.get_k_data("000725")

jdf.columns = ["Date", "Open", "Close", "High", "Low", "Volume", "code", "Adj Close"]

# 将数据保存成本地csv文件
jdf.to_csv("jdf.csv", index=False)

feed = yahoofeed.Feed()

myStrategy = MyStrategy(feed, "jdf")

returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)
plt = plotter.StrategyPlotter(myStrategy)
plt.getInstrumentSubplot("jdf")

myStrategy.run()
print("Final portfolio value: \$%.2f" % myStrategy.getResult())
plt.plot()

runStrategy()
``````

## 股价监控

default段落

breakthrough代表突破的比例，需要传入两个值,项目里面的突破比例依次是3%，5%.

withdraw代表回撤，也需要两个值，示例为3%，5%.

attention代表关注的股票列表，填入关注的股票代码，用空格隔开

mail段落

position段落

000725 = 5.76

==PS:很难过的是英文水平不好还用因为注释，以及用英文词汇做变量名,如果词不达意请见谅。==