python:海龟交易法则 画唐奇安通道

回忆一下海龟交易法则的策略:
入场条件:当收盘价突破20日价格高点时,买入一单元股票;
加仓条件:当价格大于上一次买入价格的0.5个ATR(平均波幅),买入一单元股票,加仓次数不超过3次;
止损条件:当价格小于上一次买入价格的2个ATR时清仓;
离场条件:当价格跌破10日价格低点时清仓。
这里的20日价格高点和10日价格低点构成唐奇安通道,所以海龟交易法则也可以理解成通道突破的趋势跟踪。

stock_dc.py

# coding: utf-8
import os, sys
#import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tushare as ts

if len(sys.argv) ==2:
    code = sys.argv[1]
else:
    print('usage: python stock_dc.py stockcode ')
    sys.exit(1)

if len(code) !=6:
    print('stock code length: 6')
    sys.exit(2)

# help(ts.get_k_data) 了解参数
df = ts.get_k_data(code, start='2021-01-01')
#print(df.head())
# 10日移动均线
df['ma10'] = df['close'].rolling(window=10).mean()

# 唐奇安通道(Donchian Channel)取过去20日的最高价,10日的最低价
df['up20'] = df['high'].shift(1).rolling(window=20).max()
df['down'] = df['low'].shift(1).rolling(window=10).min()
#print(df.head())
# 取样 2022年以后的数据
d2 = df[ df.date >'2022-01-01']
print(d2.tail())
d2.index = pd.to_datetime(d2.date)
# 画股价走势图
d2[['close','ma10','up20','down']].plot(grid=True, title=code)
plt.legend(loc='best', shadow=True)
plt.show()

kline_dc.py

# coding: utf-8
import os, sys
import datetime
import matplotlib.pyplot as plt
from matplotlib.pylab import date2num
#import matplotlib.finance as mpf
import mpl_finance as mpf
import pandas as pd
import tushare as ts
import talib

if len(sys.argv) ==2:
    code = sys.argv[1]
else:
    print('usage: python kline_dc.py stockcode ')
    sys.exit(1)

if len(code) !=6:
    print('stock code length: 6')
    sys.exit(2)
    
# help(ts.get_k_data) 了解参数
df = ts.get_k_data(code, start='2021-01-01')
if len(df) <30:
    print(" len(df) <30 ")
    sys.exit(2)

# 10日移动均线
df['ma10'] = df['close'].rolling(window=10).mean()

# 唐奇安通道(Donchian Channel)取过去20日的最高价,10日的最低价
df['up20'] = df['high'].shift(1).rolling(window=20).max()
df['down'] = df['low'].shift(1).rolling(window=10).min()

df = df[ df['date'] >'2022-01-01']
print(df.tail())
# 对tushare获取到的数据转换成 candlestick_ohlc()方法可读取的格式
alist = []
tlist = []
for idx,row in df.iterrows():
    date,open,close,high,low,volume = row[0:6]
    # 将日期转换为数字
    date1 = datetime.datetime.strptime(date,'%Y-%m-%d')
    t = date2num(date1)
    data = (t, open,high,low,close)
    alist.append(data)
    tlist.append(t)

# 加这个两句 可以显示中文
plt.rcParams['font.sans-serif'] = [u'SimHei'] 
plt.rcParams['axes.unicode_minus'] = False

# 创建子图
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
# 设置X轴刻度为日期时间
ax.xaxis_date()
# 对数坐标y轴
#ax.set_yscale('log') 
ax.autoscale_view()
#plt.axes(yscale='log')
#plt.setp(plt.gca().get_xticklabels(), rotation=45)
plt.xticks(rotation=45) 
plt.yticks()
plt.title("股票 {0}:K线图".format(code))
plt.xlabel("date")
plt.ylabel("price")
#mpf.candlestick_ohlc(ax,alist,colorup='green',colordown='red')
mpf.candlestick_ohlc(ax,alist,colorup='red',colordown='green')
# 画 10日均线, 唐奇安通道
plt.plot(tlist, df['ma10'].values, 'orange', label='ma10')
plt.plot(tlist, df['up20'].values, 'maroon', label='up20')
plt.plot(tlist, df['down'].values, 'gray', label='down')
plt.legend(loc='best', shadow=True)
plt.grid()
plt.show()

运行 python kline_dc.py 600566

参考: 【手把手教你】用backtrader量化回测海龟交易策略_Python金融量化的博客-CSDN博客

你可能感兴趣的:(python,python,tushare,数据分析)