脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现马丁策略的实例详解

python实现马丁策略的实例详解

2021-08-26 00:04达科索斯 Python

这篇文章主要介绍了python实现马丁策略的实例详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

马丁策略本来是一种赌博方法,但在投资界应用也很广泛,不过对于投资者来说马丁策略过于简单,所以本文将其改进并使得其在震荡市中获利,以下说明如何实现马丁策略。

策略

逢跌加仓,间隔由自己决定,每次加仓是当前仓位的一倍。
连续跌两次卖出,且卖出一半仓位。
如果爆仓则全仓卖出止损。
初始持仓设置为10%~25%,则可进行2到3次补仓。

初始化马丁策略类属性

  1. def __init__(self,startcash, start, end):
  2. self.cash = startcash #初始化现金
  3. self.hold = 0 #初始化持仓金额
  4. self.holdper = self.hold /startcash #初始化仓位
  5. self.log = [] #初始化日志
  6. self.cost = 0 #成本价
  7. self.stock_num = 0 #股票数量
  8. self.starttime = start #起始时间
  9. self.endtime = end #终止时间
  10. self.quantlog = [] #交易量记录
  11. self.earn = [] #总资产记录
  12. self.num_log = []
  13. self.droplog = [0]

为了记录每次买卖仓位的变化初始化了各种列表。

交易函数

首先导入需要的模块

  1. import pandas as pd
  2. import numpy as np
  3. import tushare as ts
  4. import matplotlib.pyplot as plt
  1. def buy(self, currentprice, count):
  2.  
  3. self.cash -= currentprice*count
  4. self.log.append('buy')
  5. self.hold += currentprice*count
  6. self.holdper = self.hold / (self.cash+ self.hold)
  7. self.stock_num += count
  8. self.cost = self.hold / self.stock_num
  9. self.quantlog.append(count//100)
  10. print('买入价:%.2f,手数:%d,现在成本价:%.2f,现在持仓:%.2f,现在筹码:%d' %(currentprice ,count//100, self.cost, self.holdper, self.stock_num//100))
  11. self.earn.append(self.cash+ currentprice*self.stock_num)
  12. self.num_log.append(self.stock_num)
  13. self.droplog = [0]
  14.  
  15. def sell(self, currentprice, count):
  16. self.cash += currentprice*count
  17. self.stock_num -= count
  18. self.log.append('sell')
  19. self.hold = self.stock_num*self.cost
  20. self.holdper = self.hold / (self.cash + self.hold)
  21. #self.cost = self.hold / self.stock_num
  22. print('卖出价:%.2f,手数:%d,现在成本价:%.2f,现在持仓:%.2f,现在筹码:%d' %(currentprice ,count//100, self.cost, self.holdper, self.stock_num//100))
  23. self.quantlog.append(count//100)
  24. self.earn.append(self.cash+ currentprice*self.stock_num)
  25. self.num_log.append(self.stock_num)
  26.  
  27. def holdstock(self,currentprice):
  28. self.log.append('hold')
  29. #print('持有,现在仓位为:%.2f。现在成本:%.2f' %(self.holdper,self.cost))
  30. self.quantlog.append(0)
  31. self.earn.append(self.cash+ currentprice*self.stock_num)
  32. self.num_log.append(self.stock_num)

持仓成本的计算方式是利用总持仓金额除以总手数,卖出时不改变持仓成本。持有则是不做任何操作只记录日志

数据接口

  1. def get_stock(self, code):
  2. df=ts.get_k_data(code,autype='qfq',start= self.starttime ,end= self.endtime)
  3. df.index=pd.to_datetime(df.date)
  4. df=df[['open','high','low','close','volume']]
  5. return df

数据接口使用tushare,也可使用pro接口,到官网注册领取token。

  1. token = '输入你的token'
  2. pro = ts.pro_api()
  3. ts.set_token(token)
  4. def get_stock_pro(self, code):
  5. code = code + '.SH'
  6. df = pro.daily(ts_code= code, start_date = self.starttime, end_date= self.endtime)
  7. return df

数据结构:

python实现马丁策略的实例详解

回测函数

  1. def startback(self, data, everyChange, accDropday):
  2. """
  3. 回测函数
  4. """
  5. for i in range(len(data)):
  6. if i < 1:
  7. continue
  8. if i < accDropday:
  9. drop = backtesting.accumulateVar(everyChange, i, i)
  10. #print('现在累计涨跌幅度为:%.2f'%(drop))
  11. self.martin(data[i], data[i-1], drop, everyChange,i)
  12. elif i < len(data)-2:
  13. drop = backtesting.accumulateVar(everyChange, i, accDropday)
  14. #print('现在累计涨跌幅度为:%.2f'%(drop))
  15. self.martin(data[i],data[i-1], drop, everyChange,i)
  16. else:
  17. if self.stock_num > 0:
  18. self.sell(data[-1],self.stock_num)
  19. else: self.holdstock(data[i])

因为要计算每日涨跌幅,要计算差分,所以第一天的数据不能计算在for循环中跳过,accDropday是累计跌幅的最大计算天数,用来控制入场,当累计跌幅大于某个数值且仓位为0%时可再次入场。以下是入场函数:

  1. def enter(self, currentprice,ex_price,accuDrop):
  2. if accuDrop < -0.01:#and ex_price > currentprice:
  3. count = (self.cash+self.hold) *0.24 // currentprice //100 * 100
  4. print('再次入场')
  5. self.buy(currentprice, count)
  6. else: self.holdstock(currentprice)

入场仓位选择0.24则可进行两次抄底,如果抄底间隔为7%可承受最大跌幅为14%。

策略函数

  1. def martin(self, currentprice, ex_price, accuDrop,everyChange,i):
  2. diff = (ex_price - currentprice)/ex_price
  3. self.droplog.append(diff)
  4.  
  5. if sum(self.droplog) <= 0:
  6. self.droplog = [0]
  7.  
  8. if self.stock_num//100 > 1:
  9. if sum(self.droplog) >= 0.04:
  10. if self.holdper*2 < 0.24:
  11. count =(self.cash+self.hold) *(0.25-self.holdper) // currentprice //100 * 100
  12. self.buy(currentprice, count)
  13. elif self.holdper*2 < 1 and (self.hold/currentprice)//100 *100 > 0 and backtesting.computeCon(self.log) < 5:
  14. self.buy(currentprice, (self.hold/currentprice)//100 *100)
  15.  
  16. else: self.sell(currentprice, self.stock_num//100 *100);print('及时止损')
  17.  
  18. elif (everyChange[i-2] < 0 and everyChange[i-1] <0 and self.cost < currentprice):# or (everyChange[i-1] < -0.04 and self.cost < currentprice):
  19.  
  20. if (self.stock_num > 0) and ((self.stock_num*(1/2)//100*100) > 0):
  21.  
  22. self.sell(currentprice, self.stock_num*(1/2)//100*100 )
  23.  
  24. #print("现在累计涨跌幅为: %.3f" %(accuDrop))
  25. elif self.stock_num == 100: self.sell(currentprice, 100)
  26. else: self.holdstock(currentprice)
  27. else: self.holdstock(currentprice)
  28. else: self.enter(currentprice,ex_price,accuDrop)

首先构建了droplog专门用于计算累计涨跌幅,当其大于0时重置为0,每次购买后也将其重置为0。当跌幅大于0.04则买入,一下为流程图(因为作图软件Visustin为试用版所以有水印,两个图可以结合来看):

python实现马丁策略的实例详解
python实现马丁策略的实例详解

此策略函数可以改成其他策略甚至是反马丁,因为交易函数可以通用。

作图和输出结果

  1. buylog = pd.Series(broker.log)
  2. close = data.copy()
  3. buy = np.zeros(len(close))
  4. sell = np.zeros(len(close))
  5. for i in range(len(buylog)):
  6. if buylog[i] == 'buy':
  7. buy[i] = close[i]
  8. elif buylog[i] == 'sell':
  9. sell[i] = close[i]
  10.  
  11. buy = pd.Series(buy)
  12. sell = pd.Series(sell)
  13. buy.index = close.index
  14. sell.index = close.index
  15. quantlog = pd.Series(broker.quantlog)
  16. quantlog.index = close.index
  17. earn = pd.Series(broker.earn)
  18. earn.index = close.index
  19.  
  20. buy = buy.loc[buy > 0]
  21. sell = sell.loc[sell>0]
  22. plt.plot(close)
  23. plt.scatter(buy.index,buy,label = 'buy')
  24. plt.scatter(sell.index,sell, label = 'sell')
  25. plt.title('马丁策略')
  26. plt.legend()
  27.  
  28. #画图
  29. plt.rcParams['font.sans-serif'] = ['SimHei']
  30.  
  31. fig, (ax1, ax2, ax3) = plt.subplots(3,figsize=(15,8))
  32.  
  33. ax1.plot(close)
  34. ax1.scatter(buy.index,buy,label = 'buy',color = 'red')
  35. ax1.scatter(sell.index,sell, label = 'sell',color = 'green')
  36. ax1.set_ylabel('Price')
  37. ax1.grid(True)
  38. ax1.legend()
  39.  
  40. ax1.xaxis_date()
  41. ax2.bar(quantlog.index, quantlog, width = 5)
  42. ax2.set_ylabel('Volume')
  43.  
  44. ax2.xaxis_date()
  45. ax2.grid(True)
  46. ax3.xaxis_date()
  47. ax3.plot(earn)
  48. ax3.set_ylabel('总资产包括浮盈')
  49. plt.show()

python实现马丁策略的实例详解

python实现马丁策略的实例详解

交易日志

到此这篇关于python实现马丁策略的实例详解的文章就介绍到这了,更多相关python马丁策略内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_40264579/article/details/112548318

延伸 · 阅读

精彩推荐