数据】【自动化交易】Python编写策略模拟股票交易

0
回复
6232
查看
[复制链接]

70

主题

2

回帖

252

积分

超级版主

积分
252
来源: 2019-7-2 22:13:48 显示全部楼层 |阅读模式
股票.png
数据我使用的是 大恒科技(600288.SH) 2010年到2016年的day级数据,我将其变换成了pyalgotrade教程的格式:
简单交易程序

简单的策略程序:

  1. # -*-coding:utf-8-*-
  2. from __future__ import print_function
  3. from pyalgotrade import strategy
  4. from pyalgotrade.barfeed import quandlfeed
  5. from pyalgotrade.technical import ma


  6. class MyStrategy(strategy.BacktestingStrategy):
  7.     def __init__(self, feed, instrument, smaPeriod):
  8.         super(MyStrategy, self).__init__(feed, 1000)
  9.         self.__position = None
  10.         self.__instrument = instrument
  11.         # We'll use adjusted close values instead of regular close values.
  12.         self.setUseAdjustedValues(True)
  13.         self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)

  14.     #---- BUY ----
  15.     def onEnterOk(self, position):
  16.         execInfo = position.getEntryOrder().getExecutionInfo()
  17.         #self.info("BUY at $%.2f" % (execInfo.getPrice()))
  18.         self.info("在价格 ¥%.2f 时买入" % (execInfo.getPrice()));

  19.     #---- NO BUY ----
  20.     def onEnterCanceled(self, position):
  21.         self.__position = None

  22.     #---- SELL ----
  23.     def onExitOk(self, position):
  24.         execInfo = position.getExitOrder().getExecutionInfo()
  25.         #self.info("SELL at $%.2f" % (execInfo.getPrice()))
  26.         self.info("在价格 ¥%.2f 时抛出" % (execInfo.getPrice()));
  27.         self.__position = None

  28.     #---- NO SELL ----
  29.     def onExitCanceled(self, position):
  30.         # If the exit was canceled, re-submit it.
  31.         self.__position.exitMarket()

  32.     def onBars(self, bars):
  33.         # Wait for enough bars to be available to calculate a SMA.
  34.         if self.__sma[-1] is None:
  35.             return

  36.         bar = bars[self.__instrument]
  37.         # If a position was not opened, check if we should enter a long position.
  38.         if self.__position is None:
  39.             if bar.getPrice() > self.__sma[-1]:
  40.                 # Enter a buy market order for 10 shares. The order is good till canceled.
  41.                 self.__position = self.enterLong(self.__instrument, 10, True)
  42.         # Check if we have to exit the position.
  43.         elif bar.getPrice() < self.__sma[-1] and not self.__position.exitActive():
  44.             self.__position.exitMarket()


  45. def run_strategy(smaPeriod):
  46.     # Load the bar feed from the CSV file
  47.     feed = quandlfeed.Feed()
  48.     feed.addBarsFromCSV("orcl", "600288SH.csv")

  49.     # Evaluate the strategy with the feed.
  50.     myStrategy = MyStrategy(feed, "orcl", smaPeriod)
  51.     myStrategy.run()
  52.     #print("Final portfolio value: $%.2f" % myStrategy.getBroker().getEquity())
  53.     print("最终盈亏情况: ¥ %.2f" % myStrategy.getBroker().getEquity())

  54. run_strategy(15);

复制代码

策略和绘制曲线程序:

2018092419185871.png

  1. # -*-coding:utf-8-*-
  2. from pyalgotrade import strategy
  3. from pyalgotrade.technical import ma
  4. from pyalgotrade.technical import cross
  5. from pyalgotrade import plotter
  6. from pyalgotrade.barfeed import quandlfeed
  7. from pyalgotrade.stratanalyzer import returns

  8. class SMACrossOver(strategy.BacktestingStrategy):
  9.     def __init__(self, feed, instrument, smaPeriod):
  10.         super(SMACrossOver, self).__init__(feed)
  11.         self.__instrument = instrument
  12.         self.__position   = None
  13.         # We'll use adjusted close values instead of regular close values.
  14.         self.setUseAdjustedValues(True)
  15.         self.__prices     = feed[instrument].getPriceDataSeries()
  16.         self.__sma        = ma.SMA(self.__prices, smaPeriod)

  17.     def getSMA(self):
  18.         return self.__sma

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

  21.     def onExitOk(self, position):
  22.         self.__position = None

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

  26.     def onBars(self, bars):
  27.         # If a position was not opened, check if we should enter a long position.
  28.         if self.__position is None:
  29.             if cross.cross_above(self.__prices, self.__sma) > 0:
  30.                 shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())
  31.                 # Enter a buy market order. The order is good till canceled.
  32.                 self.__position = self.enterLong(self.__instrument, shares, True)
  33.         # Check if we have to exit the position.
  34.         elif not self.__position.exitActive() and cross.cross_below(self.__prices, self.__sma) > 0:
  35.             self.__position.exitMarket()

  36. # Load the bar feed from the CSV file
  37. feed = quandlfeed.Feed()
  38. #feed.addBarsFromCSV("orcl", "WIKI-ORCL-2000-quandl.csv")
  39. feed.addBarsFromCSV("600288SH", "600288SH.csv")

  40. # Evaluate the strategy with the feed's bars.
  41. myStrategy = sma_crossover.SMACrossOver(feed, "600288SH", 20)

  42. # Attach a returns analyzers to the strategy.
  43. returnsAnalyzer = returns.Returns()
  44. myStrategy.attachAnalyzer(returnsAnalyzer)

  45. # Attach the plotter to the strategy.
  46. plt = plotter.StrategyPlotter(myStrategy)
  47. # Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
  48. plt.getInstrumentSubplot("600288SH").addDataSeries("SMA", myStrategy.getSMA())
  49. # Plot the simple returns on each bar.
  50. plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

  51. # Run the strategy.
  52. myStrategy.run()
  53. myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

  54. # Plot the strategy.
  55. plt.plot()


复制代码




回复

举报

您需要登录后才可以回帖 登录 | 免费注册
关注微信