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

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

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()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/499515.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

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

第一阶段、一个简单策略入门量化投资 1-4移动均线交叉策略3 上一文1-3移动均线交叉策略2中&#xff0c;我们得到的结果是令人失望的。但我们的探索还要继续。 我们知道&#xff0c;使用投资组合的方式进行分散投资是降低风险的好办法。尽管移动均线交叉策略的表现并不理想&a…

STM32学习及应用笔记一:SysTick定时器学习及应用

&#xfeff;&#xfeff; 这几年一直使用STM32的MCU&#xff0c;对ARM内核的SysTick计时器也经常使用&#xff0c;但几乎没有仔细了解过。最近正好要在移植一个新的操作系统时接触到了这块&#xff0c;据比较深入的了解了一下。 1、SysTick究竟是什么&#xff1f; 关于SysT…

使用Atom快速打造好用的Markdown编辑器

使用Atom快速打造好用的Markdown编辑器 Atom当前主流的跨平台的三大编辑器(Atom,sublime,vscode)之一 今天尝试了使用Atom来打造Markdown编辑器&#xff0c;快速上手且易用&#xff0c;墙裂推荐&#xff01; 下面直接进入正题&#xff0c;一步步介绍如何使用Atom快速打造好用…

PID控制器开发笔记之一:PID算法原理及基本实现

&#xfeff;&#xfeff; 在自动控制中&#xff0c;PID及其衍生出来的算法是应用最广的算法之一。各个做自动控制的厂家基本都有会实现这一经典算法。我们在做项目的过程中&#xff0c;也时常会遇到类似的需求&#xff0c;所以就想实现这一算法以适用于更多的应用场景。…

十分钟能学会的简单python爬虫

简单爬虫三步走&#xff0c;So easy~ 本文介绍一个使用python实现爬虫的超简单方法&#xff0c;精通爬虫挺难&#xff0c;但学会实现一个能满足简单需求的爬虫&#xff0c;只需10分钟&#xff0c;往下读吧~ 该方法不能用于带有反爬机制的页面&#xff0c;但对于我这样的非专业…

PID控制器开发笔记之二:积分分离PID控制器的实现

前面的文章中&#xff0c;我们已经讲述了PID控制器的实现&#xff0c;包括位置型PID控制器和增量型PID控制器。但这个实现只是最基本的实现&#xff0c;并没有考虑任何的干扰情况。在本节及后续的一些章节&#xff0c;我们就来讨论一下经典PID控制器的优化与改进。这一节我们首…

利用python实现短信和电话提醒功能

有时候&#xff0c;我们需要程序帮我们自动检测某些事件的发生 这个需求是广泛存在的 因此&#xff0c;这里整理了利用python实现短信和电话提醒功能的方法 主要需要完成以下4个步骤&#xff1a; - 安装核心库&#xff1a;twilio - 注册账号及配置 - 发送短信示例 - 电话…

PID控制器开发笔记之三:抗积分饱和PID控制器的实现

积分作用的引入是为了消除系统的静差&#xff0c;提高控制精度。但是如果一个系统总是存在统一个方向的偏差&#xff0c;就可能无限累加而进而饱和&#xff0c;极大影响系统性能。抗积分饱和就是用以解决这一问题的方法之一。这一节我们就来实现抗积分饱和的PID算法。 1、抗积…

如何获取STM32 MCU的唯一ID

前段时间由于应用需要对产品授权进行限制&#xff0c;所以研究了一下有关STM32 MCU的唯一ID的资料&#xff0c;并最终利用它实现了我们的目标。 1、基本描述 在STM32的全系列MCU中均有一个96位的唯一设备标识符。在ST的相关资料中&#xff0c;对其功能的描述有3各方面&#x…

SHA256算法原理详解

1. SHA256简介 SHA256是SHA-2下细分出的一种算法 SHA-2&#xff0c;名称来自于安全散列算法2&#xff08;英语&#xff1a;Secure Hash Algorithm 2&#xff09;的缩写&#xff0c;一种密码散列函数算法标准&#xff0c;由美国国家安全局研发&#xff0c;属于SHA算法之一&…

学习笔记:区块链概念入门

本文是100天区块链学习计划的第二篇学习笔记&#xff0c;其实就是按照阮一峰的网络日志-区块链入门教程的讲解进行的简单梳理。也是时间有点紧张的原因&#xff0c;相比于上一篇SHA256算法原理详解&#xff0c;个人感觉质量和原创程度明显下降。待对区块链有了更深的理解后&…

PID控制器开发笔记之四:梯形积分PID控制器的实现

从微积分的基本原理看&#xff0c;积分的实现是在无限细分的情况下进行的矩形加和计算。但是在离散状态下&#xff0c;时间间隔已经足够大&#xff0c;矩形积分在某些时候显得精度要低了一些&#xff0c;于是梯形积分被提出来以提升积分精度。 1、梯形积分基本思路 在PID控制…

SHA256 的C语言实现

前几天总结了SHA256的算法原理一文 SHA2系列的原理并不复杂&#xff0c;但是需要注意细节还是挺多的。不少中文博客贴出的代码都有错&#xff0c;这两天也踩了几个坑。 代码在这里&#xff01;&#xff01;&#xff01;SHA256的C Code 代码实现主要依照的这个git仓库crypto-…

信息摘要算法之一:MD5算法分析及实现

MD5即Message-DigestAlgorithm 5&#xff08;信息-摘要算法5&#xff09;&#xff0c;用于确保信息传输完整一致。是计算机广泛使用的杂凑算法之一&#xff08;又译摘要算法、哈希算法&#xff09;&#xff0c;主流编程语言普遍已有MD5实现。 1、MD5算法简介 MD5在90年代初由…

非对称加密概述

非对称加密概述 前言 在阅读《精通比特币》的过程中&#xff0c;我发现比特币系统中有两个重要的概念需要利用非对称加密技术&#xff1a; 比特币地址的生成 交易合法性的验证 因此&#xff0c;我用了几天时间学习了密码学基础知识&#xff0c;尤其是非对称加密技术的原理…

信息摘要算法之二:SHA1算法分析及实现

SHA算法&#xff0c;即安全散列算法&#xff08;Secure Hash Algorithm&#xff09;是一种与MD5同源的数据加密算法&#xff0c;该算法经过加密专家多年来的发展和改进已日益完善&#xff0c;现在已成为公认的最安全的散列算法之一&#xff0c;并被广泛使用。 1、概述 SHA算法…

2018数学建模A题的简单指导

之前写过一篇博客&#xff0c;介绍如何使用差分格式求解热传导方程 今天打开博客&#xff0c;突然发现评论区被这篇文章霸屏了 询问实验室的小伙伴才知&#xff0c;原来是被可爱的建模学子们攻占了 经过简单的了解&#xff0c;发现今年建模的A题的核心就是求解一个热传导方程…

PID控制器开发笔记之五:变积分PID控制器的实现

在普通的PID控制算法中&#xff0c;由于积分系数Ki是常数&#xff0c;所以在整个控制过程中&#xff0c;积分增量是不变的。然而&#xff0c;系统对于积分项的要求是&#xff0c;系统偏差大时&#xff0c;积分作用应该减弱甚至是全无&#xff0c;而在偏差小时&#xff0c;则应该…

使用SIFT匹配金馆长表情包

python使用opencv计算SIFT特征点的示例前言潜在的问题记录demo1&#xff1a;计算并绘制特征点demo2&#xff1a;使用SIFT匹配两幅图像参考文章地址前言 SIFT&#xff08;Scale-invariant feature transform&#xff09;是2004年提出的&#xff0c;至今已经经受住各种考验&…

PID控制器开发笔记之六:不完全微分PID控制器的实现

从PID控制的基本原理我们知道&#xff0c;微分信号的引入可改善系统的动态特性&#xff0c;但也存在一个问题&#xff0c;那就是容易引进高频干扰&#xff0c;在偏差扰动突变时尤其显出微分项的不足。为了解决这个问题人们引入低通滤波方式来解决这一问题。 1、不完全微分的基…