第一阶段、一个简单策略入门量化投资

1-3移动均线交叉策略2

上一篇文章1-2 移动均线交叉策略1中我们最后提到:
如果我们从第一天买入股票,一直持有股票,最后一天卖出,获得的收益是每股124.02美元,收益率为412%
如果按照我们的策略进行买卖,总共完成了21笔交易,收益为美股82.35美元,收益率为273%
仔细分析后,我发现有以下两点需要改进:
1.回测需要使用调整后价格。
2.策略收益的计算有问题,需要充分考虑早先交易产生的收益或亏损对后续交易的收益产生的影响。
针对这两点,修改代码。
假设投资的初始资金为100万,得到的资产变化图如下:

修正后,我们的策略在截止日期的资金总额为298万,也就是说平均收益率为198%
虽然这回收益的计算错误已经改正,但结果是令人沮丧的,我们使用滑动平均模型得到的收益确实比不操作要少许多。


注:由于第一次写的博客不小心被自己盖掉了,你看到的是重写了一遍的,内容简略了许多,实在是不高兴再写一遍了,见谅,各位施主直接看代码吧。

完整代码

import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
import datetime
import timeimport draw_candle
import stockdata_preProcess as preProcess##### in stock_movingAverageCross_Strategy.py
# we have give a simple strategy to trade stocks called Moving Average Model
# it is still imperfect and we find it is necessary to consider the adjust price
# so in stock_movingAverageCross_Strategy2.py we try to improve the strategy##### read the data from csv
apple=pd.read_csv(filepath_or_buffer='data_AAPL.csv')
# note that some format(data type) of data we read from .csv has changed
# for example the attribute 'Date' should be the index of the dataframe, and the date type changed from datetime to string
# this changes would made our methods in draw_candle.py got trouble
# So we need to make the following changes
date_list = []
for i in range(len(apple)):date_str = apple['Date'][i]t = time.strptime(date_str, "%Y-%m-%d")temp_date = datetime.datetime(t[0], t[1], t[2])date_list.append(temp_date)
apple['DateTime'] = pd.Series(date_list,apple.index)
del apple['Date']
apple = apple.set_index('DateTime')##### it seems we need to consider the adjust price
# yahoo only provides the adjust price of 'Close'
# but it is easy to adjust the price by the proportion of 'Adj Close' and 'Close'# now we will use the adjust data apple_adj in the following code
apple_adj = preProcess.ohlc_adjust(apple)##### compute the trade information like before, use adjust price
apple_adj["20d"] = np.round(apple_adj["Close"].rolling(window = 20, center = False).mean(), 2)
apple_adj["50d"] = np.round(apple_adj["Close"].rolling(window = 50, center = False).mean(), 2)
apple_adj["200d"] = np.round(apple_adj["Close"].rolling(window = 200, center = False).mean(), 2)apple_adj['20d-50d'] = apple_adj['20d'] - apple_adj['50d']apple_adj["Regime"] = np.where(apple_adj['20d-50d'] > 0, 1, 0)
apple_adj["Regime"] = np.where(apple_adj['20d-50d'] < 0, -1, apple_adj["Regime"])regime_orig = apple_adj.ix[-1, "Regime"]
apple_adj.ix[-1, "Regime"] = 0
apple_adj["Signal"] = np.sign(apple_adj["Regime"] - apple_adj["Regime"].shift(1))
apple_adj.ix[-1, "Regime"] = regime_origapple_adj_signals = pd.concat([pd.DataFrame({"Price": apple_adj.loc[apple_adj["Signal"] == 1, "Close"],"Regime": apple_adj.loc[apple_adj["Signal"] == 1, "Regime"],"Signal": "Buy"}),pd.DataFrame({"Price": apple_adj.loc[apple_adj["Signal"] == -1, "Close"],"Regime": apple_adj.loc[apple_adj["Signal"] == -1, "Regime"],"Signal": "Sell"}),])
apple_adj_signals.sort_index(inplace = True)apple_adj_long_profits = pd.DataFrame({"Price": apple_adj_signals.loc[(apple_adj_signals["Signal"] == "Buy") &apple_adj_signals["Regime"] == 1, "Price"],"Profit": pd.Series(apple_adj_signals["Price"] - apple_adj_signals["Price"].shift(1)).loc[apple_adj_signals.loc[(apple_adj_signals["Signal"].shift(1) == "Buy") & (apple_adj_signals["Regime"].shift(1) == 1)].index].tolist(),"End Date": apple_adj_signals["Price"].loc[apple_adj_signals.loc[(apple_adj_signals["Signal"].shift(1) == "Buy") & (apple_adj_signals["Regime"].shift(1) == 1)].index].index})
#draw_candle.pandas_candlestick_ohlc(apple_adj, stick = 45, otherseries = ["20d", "50d", "200d"])##### take a simple analysis again
# compute a rough profit (don't consider fee of the deal)
rough_profit = apple_adj_long_profits['Profit'].sum()
print(rough_profit)# compute the profit if we don't take any operation
# (take long position at the first day and sale it on the last day of the date)
no_operation_profit = apple['Adj Close'][-1]-apple['Adj Close'][0]
print(no_operation_profit)tradeperiods = pd.DataFrame({"Start": apple_adj_long_profits.index,"End": apple_adj_long_profits["End Date"]})apple_adj_long_profits["Low"] = tradeperiods.apply(lambda x: min(apple_adj.loc[x["Start"]:x["End"], "Low"]), axis = 1)
#print(apple_adj_long_profits)cash = 1000000
apple_backtest = pd.DataFrame({"Start Port. Value": [],"End Port. Value": [],"End Date": [],"Shares": [],"Share Price": [],"Trade Value": [],"Profit per Share": [],"Total Profit": [],"Stop-Loss Triggered": []})
port_value = 1
batch = 100
stoploss = .2
for index, row in apple_adj_long_profits.iterrows():# Maximum number of batches of stocks invested in# The arithmetic operator "//" represents an integer division that returns a maximum integer that is not greater than the resultbatches = np.floor(cash * port_value) // np.ceil(batch * row["Price"])trade_val = batches * batch * row["Price"]if row["Low"] < (1 - stoploss) * row["Price"]:   # Account for the stop-loss#share_profit = np.round((1 - stoploss) * row["Price"], 2)share_profit = np.round(- stoploss * row["Price"], 2) # ??? I think this line need to be modified as left showsstop_trig = Trueelse:share_profit = row["Profit"]stop_trig = Falseprofit = share_profit * batches * batchapple_backtest = apple_backtest.append(pd.DataFrame({"Start Port. Value": cash,"End Port. Value": cash + profit,"End Date": row["End Date"],"Shares": batch * batches,"Share Price": row["Price"],"Trade Value": trade_val,"Profit per Share": share_profit,"Total Profit": profit,"Stop-Loss Triggered": stop_trig}, index = [index]))cash = max(0, cash + profit)
print(apple_backtest)
apple_backtest["End Port. Value"].plot()
plt.show()

1-3移动均线交叉策略2相关推荐

  1. 1-2 移动均线交叉策略1

    第一阶段.一个简单策略入门量化投资 1-2 移动均线交叉策略1 第一阶段一个简单策略入门量化投资 1-2 移动均线交叉策略1 前言 获取数据 移动均线交叉策略 数据可视化 绘制折线图 绘制K线图 绘制 ...

  2. 量化交易学习(10)均线交叉策略

    均线交叉策略 均线介绍 均线交叉策略 回测策略 优化策略参数 代码 总结 均线介绍 均线计算: 在某一时间段的收盘价之和进行算术平均的方法,并随着时间的推移将这些平均值连成一条线便可得出SMA. 趋势 ...

  3. Python量化交易学习笔记(14)——均线交叉策略

    本文使用均线交叉策略,对平安银行自2018年1月1日至2020年2月28日的日线数据进行回测分析. 策略会用到短期移动均线及长期移动均线两个技术指标,在backtrader自定义策略init方法中,添 ...

  4. 用 Pandas 分析均线交叉策略收益率

    在这篇文章中,我们会利用上一篇文章中的均线交叉策略回测中获得的结果(<用 Python 基于均线交叉策略进行回测>),并花一些时间更深入地挖掘权益曲线并生成一些关键绩效指标和一些有趣的数据 ...

  5. 1-4移动均线交叉策略3

    第一阶段.一个简单策略入门量化投资 1-4移动均线交叉策略3 上一文1-3移动均线交叉策略2中,我们得到的结果是令人失望的.但我们的探索还要继续. 我们知道,使用投资组合的方式进行分散投资是降低风险的 ...

  6. 用 Python 基于均线交叉策略进行回测

    本篇文章中,我将用 Python 构建一个简单的移动平均线交叉交易策略进行回测,并使用 标准普尔 500 指数(S&P500) 进行测试. 一个简单的移动平均线交叉策略可能是使用技术指标的量化 ...

  7. 均线交叉策略、海龟策略:基于backtrader框架的实现

    原创文章第74篇,专注"个人成长与财富自由.世界运作的逻辑, AI量化投资". 前面系列文章,把backtrader的方方面面介绍了一下,如何使用,内部运作机制,如何扩展. 客观讲 ...

  8. 75 [backtrader期货策略]十大经典策略-分时均线交叉策略

    很多交易者进行日内交易的时候,一个很重要的参考依据就是分时均线,本文尝试构建一个新的指标来近似代替分时均线,然后尝试基于均线\分时均线\日内高低点\跟踪止损条件,构建了一个分时均线日内交易策略. 策略 ...

  9. mq5 EA模板及双均线交叉策略EAdemo

    //+------------------------------------------------------------------+ //| mt5_ea_demo.mq5 | //| Cop ...

最新文章

  1. AI一分钟 |世界上第一个无人驾驶出租车在迪拜投入使用,2030年无人驾驶将覆盖迪拜25%的交通行程
  2. ELK教程2:Kibana的安装
  3. 文本分类之特征简约算法说明
  4. 动软代码生成器连接Oracle 11g
  5. PyTips 0x03 - Python 列表推导
  6. elementUI table 表格表头居中 颜色、内容居左
  7. 2015最新Linkedin人才趋势报告
  8. 公众号题库搜题对接(提供免费接口)
  9. QT designer 控件自适应
  10. 史玉柱自述创业历程,我思故我在
  11. 如何打开CMD界面呢?打开CMD界面有四种方式。
  12. 【GANs学习笔记】目录
  13. 如何将excel表格导入word_如何将Excel中的数据写入Word表?
  14. uac管理员程序_在Windows 10中创建没有UAC提示的管理员模式快捷方式
  15. Python小鸟管道游戏源代码及素材
  16. 用opencv-python建立纯色图
  17. OFD格式的电子发票文件怎么免费转换成PDF
  18. 2019计算机学院年会主持稿,2019学校元旦联欢晚会主持词(开场白+结尾)
  19. iphone长截图哪个软件好_这可能是 iPhone 手机里最好用的长截图、拼图 APP。
  20. Codeforces:div3_719 记录

热门文章

  1. AOP和Spring AOP介绍
  2. UVA 1599 Ideal Path
  3. python 词云小demo
  4. textarea标签内的文字无缘故居中解决原因
  5. day2-元组 列表-赋值和深浅拷贝
  6. 【hihocoder 1312】搜索三·启发式搜索(启发式搜索写法)
  7. 用javascript生成指定范围的随机数
  8. 背景和弹出 Panel 都带有动画效果的 modal 效果
  9. Leetcode--238. 除自身以外数组的乘积
  10. python基础笔记_python基础学习笔记