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

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

这节我就用上节提到的pyalgotrade来编写回测策略程序,模拟股票交易。本篇文章里用的是SMA均线策略。


数据

在这里插入图片描述

数据我使用的是 大恒科技(600288.SH) 2010年到2016年的day级数据,我将其变换成了pyalgotrade教程的格式:

Adj. Close,Adj. High,Adj. Low,Adj. Open,Adj. Volume,Close,Date,Ex-Dividend,High,Low,Open,Split Ratio,Volume
0,13.53,13.45,12.65,12.62,51597046.82,11.16,2010-01-04,572108102.0,11.37,10.62,10.76,1.0,51597044.0
1,13.64,13.72,12.91,12.92,48822968.82,11.27,2010-01-05,549279336.0,11.64,10.86,11.06,1.0,48822966.0
2,13.38,13.56,13.05,13.07,41360141.82,11.01,2010-01-06,461521697.0,11.48,11.02,11.21,1.0,41360139.0
... ...

简单交易程序

简单的策略程序:

# -*-coding:utf-8-*-
from __future__ import print_function
from pyalgotrade import strategy
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.technical import ma


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

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

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

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

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

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

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


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

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

run_strategy(15);

输出结果:

... ...
2016-06-22 00:00:00 strategy [INFO] 在价格 ¥14.62 时抛出
2016-06-23 00:00:00 strategy [INFO] 在价格 ¥14.94 时买入
2016-06-27 00:00:00 strategy [INFO] 在价格 ¥14.68 时抛出
2016-06-28 00:00:00 strategy [INFO] 在价格 ¥14.95 时买入
2016-07-19 00:00:00 strategy [INFO] 在价格 ¥15.35 时抛出
2016-07-20 00:00:00 strategy [INFO] 在价格 ¥15.34 时买入
2016-07-28 00:00:00 strategy [INFO] 在价格 ¥15.12 时抛出
2016-08-11 00:00:00 strategy [INFO] 在价格 ¥15.88 时买入
2016-08-26 00:00:00 strategy [INFO] 在价格 ¥15.58 时抛出
最终盈亏情况: ¥ 925.78

策略和绘制曲线程序:

在这里插入图片描述

# -*-coding:utf-8-*-
from pyalgotrade import strategy
from pyalgotrade.technical import ma
from pyalgotrade.technical import cross
from pyalgotrade import plotter
from pyalgotrade.barfeed import quandlfeed
from pyalgotrade.stratanalyzer import returns

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

    def getSMA(self):
        return self.__sma

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

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

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

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

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

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

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

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

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

# Plot the strategy.
plt.plot()

  • 8
    点赞
  • 97
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 好的,这是一个关于如何用 Python 写一个量化交易策略的简单示例。 首先,需要准备好所需的数据。这可以通过使用量化交易软件或者第三方数据源来获取。接下来,你可以使用 Python 的 pandas 库来处理数据并进行分析。 然后,你需要定义你的交易策略。这可以根据市场情况,你的风险承受能力以及其他因素来决定。比如说,你可以使用技术分析工具来确定买入或卖出的时机,或者使用机器学习模型来预测市场走势。 最后,你可以使用 Python 的量化交易库(比如 pyalgotrade、zipline 等)来执行你的交易策略。这些库通常会提供许多实用的功能,比如自动化交易模拟交易等。 希望这些信息能帮到你! ### 回答2: 量化交易是基于程序化交易的一种交易方法,使用统计学和数学模型来进行决策。Python是一种功能强大且易于学习的编程语言,非常适合编写量化交易策略编写一个量化交易策略的主要步骤包括: 1. 数据获取:使用Python数据接口或API来获取金融市场的实时行情数据。可以使用Python的相关库,如pandas和numpy来进行数据分析和处理。 2. 策略开发:根据市场需求和自己的投资理念,采用相关的量化交易策略方法对数据进行分析和建模,确定交易信号。常用的策略包括均值回归、趋势跟随和市场中性等。 3. 回测测试:使用历史数据策略进行回测,评估策略的盈利能力和风险水平。可以使用Python的回测框架,如zipline或backtrader来进行回测,计算策略的平均收益率、夏普比率和最大回撤等指标。 4. 实盘交易:在经过充分的回测测试后,可以将策略应用到实盘交易中。可以使用Python交易API来进行实时交易操作。需要注意风险管理,设置止损和止盈等交易规则。 5. 策略优化:根据实际交易情况,及时调整和优化策略。可以根据交易数据和市场信息,采用机器学习和人工智能的方法来优化策略。 使用Python编写量化交易策略具有很多优势: - Python语言简洁易读,易于理解和维护; - Python拥有丰富的第三方库和工具,如pandas、numpy和scikit-learn,用于数据处理和机器学习; - Python拥有成熟的量化交易框架和回测工具,如zipline和backtrader,方便快速开发和测试策略; - Python可以与金融市场的数据接口和交易API进行无缝对接; - Python具有广泛的社区支持和丰富的学习资源,便于解决问题和提高开发效率。 总之,使用Python编写量化交易策略可以提升交易效率和盈利能力,是目前金融市场中的一种重要趋势。 ### 回答3: 量化交易是通过使用计算机程序和数学模型来制定投资决策的一种交易策略Python是一种功能强大且易于学习的编程语言,广泛应用于量化交易领域。下面是一个使用Python编写的简单量化交易策略的示例: 首先,我们需要安装Python的相关库,如pandas用于数据处理,numpy用于数值计算,以及其他一些量化交易库如zipline或者backtrader。 接下来,我们需要获取相应的金融数据,可以从在线API获取或者通过下载历史数据。使用pandas库可以将数据加载到DataFrame对象中,并进行数据清洗和预处理。 然后,我们可以基于所选择的交易策略进行指标计算。例如,使用移动平均线策略,我们可以计算股票价格的短期和长期移动平均,并通过比较两者的关系来产生买入或卖出信号。 接下来,我们可以使用条件语句来执行交易决策。例如,如果短期移动平均线向上穿过长期移动平均线,则产生买入信号。我们可以使用Python的条件语句来执行交易操作,如购买股票或卖出现有持仓。 最后,我们可以使用Python的可视化库如matplotlib来绘制图表,以便对交易结果进行分析和可视化。 总之,使用Python编写量化交易策略可以通过结合数据处理、数值计算、条件语句和可视化等功能,帮助投资者自动化制定投资决策并对交易策略进行测试和优化。这只是一个简单的示例,实际的量化交易策略涉及更多复杂的算法和技术,需要深入的领域知识和开发经验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值