程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Back test of turtle trading method with Python

編輯:Python

Turtle trading is the earliest quantitative trading method , It has been used for many years , I find there are many uses on the Internet python Turtle trading method back to test the code tutorial , And they all pass first akshare The library is realized by means of average combination , But most of them will report errors , Xiaobian looked for a lot , But in the end, it is still not satisfactory , So here are the following . I hope it will be of some help to you . I have noted some points that need attention , In fact, this moving average strategy can be modified , For example 10 Day and 20 Daily moving average changed to 100 Day and 200 Japan , Xiaobian believes that the specific choice of moving average can be based on the different varieties of specific stocks and futures , I think you should make a specific choice according to the specific nature and fundamentals of the stocks you want to trade , For example, Maotai, which is suitable for value investment, can choose a long-term moving average portfolio , And some stocks or futures with large fluctuations in history can choose some time sensitive moving average combinations , such as 10 Day and 20 Japan ,5 Day and 10 Day and so on , Magic numbers can be added to the choice of moving average , Fibonacci sequence . No joy, no spray. , The dog's head lives .

# Read A Share data
import akshare as ak
import tushare
import pandas as pd
import datetime
import numpy
import os, sys
import nodejs
# call akshare Library API Interface to get data
df = stock_zh_index_daily_df = ak.stock_zh_index_daily(symbol="sh600113")
print(stock_zh_index_daily_df)
df = df.reset_index()
# Change the name
df.columns = [x.upper() for x in df.columns]
df.rename(columns={"DATE": "index"}, inplace=True)
df = df[df['OPEN'].notnull()]
# adopt rolling Rolling average and BOLL passageway
df['MA_5'] = df['CLOSE'].rolling(window=5).mean()
df['MA_10'] = df['CLOSE'].rolling(window=10).mean()
df['MA_20'] = df['CLOSE'].rolling(window=20).mean()
df['MA_30'] = df['CLOSE'].rolling(window=30).mean()
df['MA_60'] = df['CLOSE'].rolling(window=60).mean()
df['MA_250'] = df['CLOSE'].rolling(window=250).mean()
df['BOLL_STD'] = df['CLOSE'].rolling(window=250).std()
df['BOLL_UPPER'] = df['MA_250'] + 2 * df['BOLL_STD']
df['BOLL_LOWER'] = df['MA_250'] - 2 * df['BOLL_STD']
with pd.ExcelWriter('D:\jiangtingrui1\ Stock trading information '+'XY'+'.xlsx') as writer:
df.to_excel(writer, index=False, sheet_name='Sheet1')
# The first... Is created and written excel Put this excel Drag in and out excel In a common folder , Run it again and you will see the result
# Judge the trading node
# Use the short-term moving average to wear the long-term moving average to buy points
# The selling point is to use the short-term moving average to cross the long-term moving average
def is_dbljx(data, i, mode='buy', j1='MA_60', j2='MA_250'):
# This step is to modify the moving average you want to combine , For example, in the turtle trading law 10 Day and 20 Japan , By turning the top MA_60 and MA_250 Modify to complete the modified moving average combination
if i < 250:
return False
if mode == 'buy':
if (data.loc[i, j1] > data.loc[i, j2]) & (data.loc[i - 1, j1] < data.loc[i - 1, j2]):
return True
else:
if (data.loc[i, j1] < data.loc[i, j2]) & (data.loc[i - 1, j1] > data.loc[i - 1, j2]):
return True
return False
# data According to the total ,l List of operation records ( buy 、 Sales form a record )
# Calculate the profit amount of each holding of shares 、 Profit margin 、 Hold a number of days 、 Maximum income during the period 、 Interval minimum return
def huizong_one(data, l):
# Output results
dfout = pd.DataFrame(l, columns=[' Stock code ', ' Buy index ', ' Sell index ', ' Date of purchase ', ' Date of sale ', ' Buying price ', ' Selling price ', ' state '])
dfout = dfout.reindex(
columns=[' Stock code ', ' Buy index ', ' Sell index ', ' Date of purchase ', ' Date of sale ', ' Buying price ', ' Selling price ', ' state ', ' Maximum income during the period ', ' Period minimum return ', ' Profit amount ', ' Profit margin ',
' Hold a number of days '])
# ,' Profit amount ',' Profit margin ',' Hold a number of days '
for i, row in dfout.iterrows():
dfout.loc[i, ' Profit amount '] = dfout.loc[i, ' Selling price '] - dfout.loc[i, ' Buying price ']
dfout.loc[i, ' Profit margin '] = (dfout.loc[i, ' Selling price '] - dfout.loc[i, ' Buying price ']) / dfout.loc[i, ' Buying price '] * 100
dfout.loc[i, ' Hold a number of days '] = dfout.loc[i, ' Date of sale '] - dfout.loc[i, ' Date of purchase ']
m = data.loc[dfout.loc[i, ' Buy index ']:dfout.loc[i, ' Sell index '], 'CLOSE'].max()
if m < dfout.loc[i, ' Selling price ']:
m = dfout.loc[i, ' Selling price ']
dfout.loc[i, ' Maximum income during the period '] = (m - dfout.loc[i, ' Buying price ']) / dfout.loc[i, ' Buying price '] * 100
m = data.loc[dfout.loc[i, ' Buy index ']:dfout.loc[i, ' Sell index '], 'CLOSE'].min()
if m > dfout.loc[i, ' Selling price ']:
m = dfout.loc[i, ' Selling price ']
dfout.loc[i, ' Period minimum return '] = (m - dfout.loc[i, ' Buying price ']) / dfout.loc[i, ' Buying price '] * 100
return dfout
# Traverse and back test all the collected stock data
folder_name = 'D:\\jiangtingrui1\\ Stock trading information '
file_list = os.listdir(folder_name)
ldf = []
if len(file_list) > 0:
# Traverse all files under the folder
ldf = []
for f in range(len(file_list)):
data = pd.read_excel(folder_name + str(file_list[f]), dtype=object)
data['bs'] = ''
code = str(file_list[f])[:-5]
l = []
buy_index = 0
for i in range(250, len(data)):
# Judging buying and selling signals
if is_dbljx(data, i, 'buy'):
# Record purchases
buy_index = i
data.loc[i, 'bs'] = 'b'
# Sell signal
elif (buy_index != 0) & is_dbljx(data, i, 'sell'):
# Stock code Buy index Sell index Date of purchase Date of sale Buying price Selling price
# Record the point of sale , Clear buy some
l.append([code, buy_index, i, data.loc[buy_index, 'index'], data.loc[i, 'index'],
data.loc[buy_index, 'CLOSE'], data.loc[i, 'CLOSE'], ' End '])
buy_index = 0
data.loc[i, 'bs'] = 's'
# Save the results when finished
with pd.ExcelWriter(folder_name + str(file_list[f])) as writer:
data.to_excel(writer, index=False, sheet_name='Sheet1')
# Summarize the single results
if buy_index != 0:
# Record a current
l.append([code, buy_index, i - 1, data.loc[buy_index, 'index'], data.loc[i - 1, 'index'],
data.loc[buy_index, 'CLOSE'], data.loc[i - 1, 'CLOSE'], ' hold '])
ldf.append(huizong_one(data, l)) # Store the operation results of each stock
# Finally, summarize the output
dfout = pd.concat(ldf, ignore_index=True)
with pd.ExcelWriter('D:\jiangtingrui1\ Stock trading information \XYYY.xlsx') as writer:
dfout.to_excel(writer, index=False, sheet_name='Sheet1', float_format="%.2f")


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved