请问大神,R语言使用laplace函数后验抽样函数的傅里叶变换出现如下错误是什么原因?

&figure&&img src=&https://pic1.zhimg.com/v2-b1efeab42ecb0cf0cc23613_b.jpg& data-rawwidth=&548& data-rawheight=&565& class=&origin_image zh-lightbox-thumb& width=&548& data-original=&https://pic1.zhimg.com/v2-b1efeab42ecb0cf0cc23613_r.jpg&&&/figure&&p&曾经有网友问我如何读取磁盘中数个文件的数据,并把这些数据合并到一张数据表中。这期就跟大家讲讲如何完成如下四种情况的文件批量读取:&/p&&br&&p&&strong&1、对于文件名有规律的情况&/strong&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-9c6dc147d4d2fad6fa8c8_b.jpg& data-rawwidth=&579& data-rawheight=&227& class=&origin_image zh-lightbox-thumb& width=&579& data-original=&https://pic3.zhimg.com/v2-9c6dc147d4d2fad6fa8c8_r.jpg&&&/figure&&p&&strong&解决方案:&/strong&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 设置R的工作空间
setwd('D:\\data file\\data1')
#res &- NULL
# 初始化数据框,用于后面的数据合并
data1 &- data.frame()
#通过循环完成数据合并
for (i in 1:4){
# 构造数据路径
path &- paste0(getwd(),'\\','test',i,'.xlsx')
#res &- c(res,path)
# 读取并合并数据
data1 &- rbind(data1,read_excel(path = path))
&/code&&/pre&&/div&&p&&strong&2、对于文件名没有规律的情况&/strong&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-ecb645f1b91c026decc66e5_b.jpg& data-rawwidth=&516& data-rawheight=&222& class=&origin_image zh-lightbox-thumb& width=&516& data-original=&https://pic1.zhimg.com/v2-ecb645f1b91c026decc66e5_r.jpg&&&/figure&&p&&strong&解决方案:&/strong&&br&&/p&&p&# 设置工作空间&/p&&p&setwd('D:\\data file\\data2')&/p&&p&# 读取该工作空间下的所有文件名&/p&&p&filenames &- dir()&/p&&p&# 初始化数据框,用于后面的数据合并&/p&&p&data2 &- data.frame()&/p&&p&#通过循环完成数据合并&/p&&p&for (i in filenames){&/p&&p&# 构造数据路径&/p&&p&
path &- paste0(getwd(),'\\',i)&/p&&p&
#res &- c(res,path)&/p&&p&# 读取并合并数据&/p&&p&
data2 &- rbind(data2,read_excel(path = path))&/p&&p&}&/p&&br&&p&&strong&3、对于文件名没有规律的情况,并且只读取某做后缀的文件&/strong&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-fe90c9fb13bac5f938a18_b.jpg& data-rawwidth=&546& data-rawheight=&275& class=&origin_image zh-lightbox-thumb& width=&546& data-original=&https://pic4.zhimg.com/v2-fe90c9fb13bac5f938a18_r.jpg&&&/figure&&br&&p&&strong&解决方案:&/strong&&br&&/p&&p&# 设置工作空间&/p&&p&setwd('D:\\data file\\data3')&/p&&p&# 读取该工作空间下的所有文件名&/p&&p&filenames &- dir()&/p&&p&# 通过正则,获取所有xlsx结尾的文件名&/p&&p&filenames2 &- grep('\\.xlsx', filenames, value = TRUE)&/p&&p&# 初始化数据框,用于后面的数据合并&/p&&p&data3 &- data.frame()&/p&&p&#通过循环完成数据合并&/p&&p&for (i in filenames2){&/p&&p&# 构造数据路径&/p&&p&
path &- paste0(getwd(),'\\',i)&/p&&p&
#res &- c(res,path)&/p&&p&# 读取并合并数据&/p&&p&
data3 &- rbind(data3,read_excel(path = path))&/p&&p&}&/p&&br&&p&&strong&4、文件内容结构不一致,但变量名称一致&/strong&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-c9f38ce52006dfb158ef1_b.jpg& data-rawwidth=&391& data-rawheight=&347& class=&content_image& width=&391&&&/figure&&br&&p&&strong&解决方案&/strong&&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 加载第三方扩展包,用于编写SQL语句
library(sqldf)
# 设置工作空间
setwd('D:\\data file\\data4')
# 读取该工作空间下的所有文件名
filenames &- dir()
# 通过正则,获取所有xlsx结尾的文件名
filenames2 &- grep('\\.xlsx', filenames, value = TRUE)
# 初始化数据框,用于后面的数据合并
data4 &- data.frame()
#通过循环完成数据合并
for (i in filenames2){
# 构造数据路径
path &- paste0(getwd(),'\\',i)
#res &- c(res,path)
# 使用read_excel函数读取xlsx文件
data &- read_excel(path = path)
# 使用sqldf函数编写SQL语句,并把结果合并起来
data4 &- rbind(data4, sqldf(&select id,name,gender,age from data&))
&/code&&/pre&&/div&&br&&p&以上四种情况是日常工作中最为常见的,这里通过R语言完成了这几种批量读取数据的落地,希望可以帮助到需要的朋友。&/p&&br&&p&下期预告:SVM理论与实战&/p&&p&----------------------------------------------&/p&&blockquote&&p&作者:刘顺祥&/p&&p&出处:&a href=&http://link.zhihu.com/?target=https%3A//ask.hellobi.com/blog/lsxxx2011& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&刘顺祥博客&i class=&icon-external&&&/i&&/a&&/p&&p&公众号:每天进步一点点2015&/p&&/blockquote&&p&&b&大家也可以加小编微信:tswenqu(备注:知乎),进R语言中文社区 交流群,可以跟各位老师互相交流。玩R的伙伴都在里面的,一起进来多交流&/b&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-1c7f23cb04_b.jpg& data-rawwidth=&353& data-rawheight=&66& class=&content_image& width=&353&&&/figure&&p&&b&官方公众号:R语言中文社区 (ID:R_shequ) 欢迎关注,持续连载。&/b&&/p&
曾经有网友问我如何读取磁盘中数个文件的数据,并把这些数据合并到一张数据表中。这期就跟大家讲讲如何完成如下四种情况的文件批量读取: 1、对于文件名有规律的情况解决方案:# 设置R的工作空间
setwd('D:\\data file\\data1')
#res &- NULL
# 初始化数据…
&figure&&img src=&https://pic3.zhimg.com/v2-152a1b65a9c7da8f40a0d5fd2a08aecc_b.jpg& data-rawwidth=&1080& data-rawheight=&1080& class=&origin_image zh-lightbox-thumb& width=&1080& data-original=&https://pic3.zhimg.com/v2-152a1b65a9c7da8f40a0d5fd2a08aecc_r.jpg&&&/figure&距离上一讲已经将近一个多月,这次&a href=&https://www.zhihu.com/people/c9b28ce4b50bf224cb06f& data-hash=&c9b28ce4b50bf224cb06f& class=&member_mention& data-hovercard=&p$b$c9b28ce4b50bf224cb06f& data-editable=&true& data-title=&@猴子&&@猴子&/a& 老师憋了很多内容,光直播就进行了两个多小时,布置的作业也非常有分量,在完成作业之前,很有必要对讲课内容作一个笔记整理,算是在完成作业之前的一个复习。&p&本次课程主要讲了四块内容,解决了一个问题,四块内容如下:&/p&&ol&&li&如何编写函数;&br&&/li&&li&用dpylr,ggplot2包进行数据处理和展示;&br&&/li&&li&如何编写业务模块;&br&&/li&&li&如何调试代码。&br&&/li&&/ol&&br&&p&解决的一个问题是用nycflight13包中的航班数据分析航班航行距离与延误时间之间的关系。&/p&&h2&&b&1 如何编写函数&/b&&/h2&&p&在编写函数之前,首先要知道什么是函数,按照数学上的定义,&/p&&p&&b&如果M是一个实数集,而对于每一个&img src=&https://www.zhihu.com/equation?tex=x%5Cin+M& alt=&x\in M& eeimg=&1&&都对应一个确定的值y,则程变量y=f(x)为定义在实数集M上的变量x的函数。&/b&&/p&&p&我们可以更加抽象一点的理解,x是输入,y是输出,而f则是x与y之间的一种映射,从编程的角度f就是你对输入x进行一系列的处理使得最终输出你想要的y,我们可以称之为&b&功能。&/b&&/p&&p&于是函数可以这样来定义:&/p&&p&&b&函数是实现一定功能的模块,通常接受一定的输入,并将相应的功能作用在输入上面,形成相关结果输出。&/b&&/p&&p&在R语言中按照一定的格式来编写函数:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&my_fun &- function(arg1, arg2){
return(data)
&/code&&/pre&&/div&&p&其中:&/p&&ul&&li&my_fun 为函数名称;&br&&/li&&li&function()为R中定义函数的关键字;&br&&/li&&li&arg1和arg2是需要输入的参数;&br&&/li&&li&body里面代表需要实现的具体功能,比如对输入参数的处理分析,或者数据可视化等等;&br&&/li&&li&return是R中的关键字,表示有数据需要返回;&br&&/li&&li&data是返回的数据,可以理解为狭义的输出,有时候函数并不一定返回数据。&br&&/li&&/ul&&p&函数定义好以后需要编译,在命令好窗口输入以后可以直接回车编译,如果编译通过在当前项目的运行环境(Global Environment)下会产生相应的函数。&/p&&p&&figure&&img src=&https://pic4.zhimg.com/v2-6ca2b2adb9b47e93c28ca772_b.jpg& data-rawwidth=&647& data-rawheight=&100& class=&origin_image zh-lightbox-thumb& width=&647& data-original=&https://pic4.zhimg.com/v2-6ca2b2adb9b47e93c28ca772_r.jpg&&&/figure&&figure&&img src=&https://pic4.zhimg.com/v2-70f95a2dc788aff313ef28_b.jpg& data-rawwidth=&548& data-rawheight=&204& class=&origin_image zh-lightbox-thumb& width=&548& data-original=&https://pic4.zhimg.com/v2-70f95a2dc788aff313ef28_r.jpg&&&/figure&编译完成以后便可以在当前环境中使用:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& d &- subtract(16,1)
&/code&&/pre&&/div&&p&接下来是关于R语言的流程控制,这部分内容在之前的&a href=&https://zhuanlan.zhihu.com/p/& class=&internal&&《R语言实战》第一部分第五章复习笔记 - 知乎专栏&/a&已经讲过,不过考虑到课程的完整性,这里再多说几句。&/p&&p&R语言作为一种编程语言,和其它编程语言(Java,C/C++,Python等)一样,也对流程控制有着很好的支持。通常,在计算机编程当中存在以下两种流程控制:&/p&&ol&&li&循环&br&&/li&&li&条件选择&br&&/li&&/ol&&br&&p&都比较好理解,循环就是让计算机重复做某一件事情,这是计算机最擅长的,举一个简单的例子,如果我们要打印“Hello World”十次,不采用循环语句的做法是:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
& print(&Hello World&)
[1] &Hello World&
&/code&&/pre&&/div&&p&显然,这样重复的输入比较麻烦,即便每次都可以复制粘贴,但是如果重复的次数是100次、1000次,那么就没有可操作性了。采用循环语句可以这么写:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& for(i in 1:10){
print(&Hello World&)
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
&/code&&/pre&&/div&&p&上面的10表示循环次数,你可以简单修改一个数字便可以获得不同的循环次数。以上是for语句的循环实现,此外还有一种while语句的实现如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& i &- 10
& while(i & 0){
print(&Hello World&)
i &- i - 1
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
[1] &Hello World&
&/code&&/pre&&/div&&p&while语句的循环逻辑是首先判断条件是否成立,比如? i & 0,如果i大于零则执行后面的语句,如果i不大于零,则循环退出。在使用while语句的时候需要注意的是在执行主体里面需要对前面的判断条件所涉及的参数进行修改,否则有可能导致死循环,条件判断条件永远为真。&br&&/p&&p&两种循环的模板如下:&/p&&figure&&img src=&https://pic3.zhimg.com/v2-dc134a2966_b.jpg& data-rawwidth=&541& data-rawheight=&297& class=&origin_image zh-lightbox-thumb& width=&541& data-original=&https://pic3.zhimg.com/v2-dc134a2966_r.jpg&&&/figure&&br&&figure&&img src=&https://pic4.zhimg.com/v2-aba1fba063_b.jpg& data-rawwidth=&511& data-rawheight=&253& class=&origin_image zh-lightbox-thumb& width=&511& data-original=&https://pic4.zhimg.com/v2-aba1fba063_r.jpg&&&/figure&&p&&br&如果能够理解while语句,其实条件语句就更好理解了。条件语句主要实现程序执行流程的选择,就好比你站在一个丁字路口,向左还是向右,如果向左的条件达成了就向左,否则就向右。在R语言当中主要通过if-else语句、ifelse语句以及switch语句来实现条件选择的功能。&/p&&h2&&b&2 数据处理:dpylr,ggplot2&/b&&/h2&&p&以下跟着课件的顺序重点讲讲如果用dpylr和ggplot2处理和分析并展示数据。&/p&&p&&b&2.1 理解数据&/b&&/p&&p&理解数据就是先了解一下数据的大致情况,数据的观测数,观测变量名,数据类型等等,对所要分析的数据有一个大致的了解,并初步判断在哪些角度着手可以获得较高的分析价值。本讲的分析对象是航班数据,观测数总计336, 776条,17个变量,数据类型设计时间、字符串等。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& install.packages(&dplyr&)
trying URL 'https://mirrors.tuna.tsinghua.edu.cn/CRAN/bin/windows/contrib/3.3/dplyr_0.5.0.zip'
Content type 'application/zip' length 2557208 bytes (2.4 MB)
downloaded 2.4 MB
package ‘dplyr’ successfully unpacked and MD5 sums checked
The downloaded binary packages are in
C:\Users\panhuayin\AppData\Local\Temp\Rtmp6feVlu\downloaded_packages
& library(nycflights13)
& library(dplyr)
载入程辑包:‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
# A tibble: 336,776 × 19
year month
day dep_time sched_dep_time dep_delay arr_time
&int& &int& &int&
# ... with 336,766 more rows, and 12 more variables: sched_arr_time &int&,
arr_delay &dbl&, carrier &chr&, flight &int&, tailnum &chr&,
origin &chr&, dest &chr&, air_time &dbl&, distance &dbl&, hour &dbl&,
minute &dbl&, time_hour &dttm&
&/code&&/pre&&/div&&p&&b&2.2 数据导入&/b&&br&&/p&&p&事实上,在本讲当中,安装完nycflights13包并载入已经完成了数据导入的过程,在其它情况下可能有更复杂的数据导入过程,可以具体参考《R语言实战》第二章的内容。&/p&&p&&b&2.3 数据预处理&/b&&/p&&p&数据预处理的主要步骤如下:&/p&&p&&figure&&img src=&https://pic4.zhimg.com/v2-67f745c4fee25f40d0ebc2e_b.jpg& data-rawwidth=&538& data-rawheight=&851& class=&origin_image zh-lightbox-thumb& width=&538& data-original=&https://pic4.zhimg.com/v2-67f745c4fee25f40d0ebc2e_r.jpg&&&/figure&子集的选择主要基于分析需求所确定的目标,在本讲当中主要分析航班航行距离与延误时间的关系,与此无关的变量可以剔除。与此相关的主要有以下几个字段:&/p&&figure&&img src=&https://pic1.zhimg.com/v2-9bedb074c1c81bdf5351ccf74b35e4f0_b.jpg& data-rawwidth=&548& data-rawheight=&452& class=&origin_image zh-lightbox-thumb& width=&548& data-original=&https://pic1.zhimg.com/v2-9bedb074c1c81bdf5351ccf74b35e4f0_r.jpg&&&/figure&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& myFlights &- select(flights, year,month, day,
dep_delay,arr_delay,distance,dest)
& myFlights
# A tibble: 336,776 × 7
year month
day dep_delay arr_delay distance
&int& &int& &int&
&dbl& &chr&
# ... with 336,766 more rows
&/code&&/pre&&/div&&br&&p&这里补充以下dplyr包中select()函数的用法,在Rstudio中查阅help(select),dplyr包的文档对它说明如下:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-d1984ddd1ee2_b.jpg& data-rawwidth=&637& data-rawheight=&691& class=&origin_image zh-lightbox-thumb& width=&637& data-original=&https://pic1.zhimg.com/v2-d1984ddd1ee2_r.jpg&&&/figure&这个说明还涵盖了rename()函数,一会儿还会用到,这里顺便一次带过。首先select()函数传入两组参数,首先.data指定一个待数据表格,后面“...”表示用逗号分离的无引用的表达式列表,可以是数据表中的变量名,如果是正的表示你要选择的,如果前面加一个负号表示你要舍弃的。比如:&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-1b3a6b9d715f61ebab5e_b.jpg& data-rawwidth=&541& data-rawheight=&641& class=&origin_image zh-lightbox-thumb& width=&541& data-original=&https://pic2.zhimg.com/v2-1b3a6b9d715f61ebab5e_r.jpg&&&/figure&此外,表达式还支持模糊查询,比如:&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-e54b451bc5e26daae4d3cd74c8c6a417_b.jpg& data-rawwidth=&549& data-rawheight=&784& class=&origin_image zh-lightbox-thumb& width=&549& data-original=&https://pic2.zhimg.com/v2-e54b451bc5e26daae4d3cd74c8c6a417_r.jpg&&&/figure&help文档也给出了很多的例子:&/p&&p&&figure&&img src=&https://pic4.zhimg.com/v2-e0edbaa23c91ef88ee9c67a1_b.jpg& data-rawwidth=&503& data-rawheight=&553& class=&origin_image zh-lightbox-thumb& width=&503& data-original=&https://pic4.zhimg.com/v2-e0edbaa23c91ef88ee9c67a1_r.jpg&&&/figure&rename()函数与select()函数主要的区别在于前者保留所有变量,后者只保留你提到的变量。下面将dest变量重命名为destination。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& myFlights &- rename(myFlights, destination = dest)
& myFlights
# A tibble: 336,776 × 7
year month
day dep_delay arr_delay distance
&int& &int& &int&
# ... with 336,766 more rows, and 1 more variables:
destination &chr&
&/code&&/pre&&/div&&p&接下来删除缺失数据,这次采用的是dplyr包中的filter()函数。老规矩,先看看文档里面是怎么说的。&br&&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-9c8d519c5c3536b9dbd6ff803ccf5f76_b.jpg& data-rawwidth=&598& data-rawheight=&799& class=&origin_image zh-lightbox-thumb& width=&598& data-original=&https://pic2.zhimg.com/v2-9c8d519c5c3536b9dbd6ff803ccf5f76_r.jpg&&&/figure&简单的描述就是返回满足条件的数据行,对于不满足条件的数据会进行整行的删除。传入的数据与select()函数相似,首先是需要处理的数据表,后面的一组参数有所不同,是一个逻辑判断表达式。R的逻辑运算符可以参考《R语言实战》第四章的内容,详见下表:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-af51ce42fff0c65ef6f412f7cc98dcbc_b.jpg& data-rawwidth=&727& data-rawheight=&328& class=&origin_image zh-lightbox-thumb& width=&727& data-original=&https://pic1.zhimg.com/v2-af51ce42fff0c65ef6f412f7cc98dcbc_r.jpg&&&/figure&值得一提的说,当有多个逻辑表达式时,可以用逗号隔开,不过R将多个表达式按照和(&)来对待,即只有满足所有逻辑表达式时才会被保留。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& myFlights &- filter(myFlights,
!is.na(dep_delay),
!is.na(arr_delay))
& myFlights
# A tibble: 327,346 × 7
year month
day dep_delay arr_delay distance destination
&int& &int& &int&
# ... with 327,336 more rows
&/code&&/pre&&/div&&p&filter()函数一共剔除了8255行数据。关于查找数据的例子,除了help文档中的,还可以再举其它几个例子,比如查找12月30日的航班:&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& filter(myFlights, month == 12, day == 30)
# A tibble: 953 × 7
year month
day dep_delay arr_delay distance destination
&int& &int& &int&
# ... with 943 more rows
&/code&&/pre&&/div&&p&延误和出发均大于2小时的航班:&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& filter(myFlights, arr_delay & 120 & dep_delay & 120)
# A tibble: 8,335 × 7
year month
day dep_delay arr_delay distance destination
&int& &int& &int&
# ... with 8,325 more rows
&/code&&/pre&&/div&&p&最后是数据预处理的最后一步,给即将接入下一道工序的数据排个序。dplyr包的arrange()函数用于排序也非常简单,默认的是升序,如果要降序的话在变量名前面加上desc函数。&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-9b5cbbd7b98be4c911e6ef8_b.jpg& data-rawwidth=&593& data-rawheight=&435& class=&origin_image zh-lightbox-thumb& width=&593& data-original=&https://pic1.zhimg.com/v2-9b5cbbd7b98be4c911e6ef8_r.jpg&&&/figure&本讲暂按降序考虑,代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& myFlights
&- arrange(myFlights, desc(dep_delay))
& myFlights
# A tibble: 327,346 × 7
year month
day dep_delay arr_delay distance destination
&int& &int& &int&
# ... with 327,336 more rows
&/code&&/pre&&/div&&p&&b&2.4 数据计算&/b&&br&&/p&&p&这一步才是真正发挥dplyr包强大功能的时候。而且不得不提的是数据计算的一种常规套路:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-dccffee1ddebb2ccb022117_b.jpg& data-rawwidth=&520& data-rawheight=&206& class=&origin_image zh-lightbox-thumb& width=&520& data-original=&https://pic1.zhimg.com/v2-dccffee1ddebb2ccb022117_r.jpg&&&/figure&一共分三步走:&/p&&ol&&li&数据分组:可以以某一个变量将数据进行分组,在本例中,可以以不同目的地对数据进行分组,假设有10个不同的目的地,此时有十组不同的数据;&br&&/li&&li&应用函数:对不同组的数据应用函数取得需要的统计指标,比如求各分组的行数、平均值、请标准差等等;&br&&/li&&li&组合结果:将第二步当中计算后的返回结果进行按第一步当中的分组进行组合。&br&&/li&&/ol&&p&以下结合讲义举一个北京、上海航班延误时间和距离的例子。原始预处理后的表格如下:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-fe00f839a2ff04e8910410c_b.jpg& data-rawwidth=&496& data-rawheight=&505& class=&origin_image zh-lightbox-thumb& width=&496& data-original=&https://pic1.zhimg.com/v2-fe00f839a2ff04e8910410c_r.jpg&&&/figure&第一步,按不同的目的地进行分组,分组后数据如下:&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-fe173c29aaf13a4adde70_b.jpg& data-rawwidth=&504& data-rawheight=&569& class=&origin_image zh-lightbox-thumb& width=&504& data-original=&https://pic2.zhimg.com/v2-fe173c29aaf13a4adde70_r.jpg&&&/figure&第二步,对分组后的数据应用函数,求取平均延误时间和平均航行距离,计算过程如下:&/p&&p&&figure&&img src=&https://pic4.zhimg.com/v2-d6af2adffeeeac7bb4e6687_b.jpg& data-rawwidth=&675& data-rawheight=&429& class=&origin_image zh-lightbox-thumb& width=&675& data-original=&https://pic4.zhimg.com/v2-d6af2adffeeeac7bb4e6687_r.jpg&&&/figure&第三步,将分组后的数据进行组合,形成新的数据表:&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-c975a6c71321dffcd1c81e18_b.jpg& data-rawwidth=&705& data-rawheight=&383& class=&origin_image zh-lightbox-thumb& width=&705& data-original=&https://pic2.zhimg.com/v2-c975a6c71321dffcd1c81e18_r.jpg&&&/figure&以上三个步骤在dplyr包中有相应的函数进行处理。首先分组由group_by()函数进行处理,help文档如下:&/p&&p&&figure&&img src=&https://pic4.zhimg.com/v2-3eba8ba9e162a981fad1_b.jpg& data-rawwidth=&576& data-rawheight=&346& class=&origin_image zh-lightbox-thumb& width=&576& data-original=&https://pic4.zhimg.com/v2-3eba8ba9e162a981fad1_r.jpg&&&/figure&group_by()函数按照第二次参数的变量名对第一个参数的数据表进行分组,本讲当中首先对数据按不同destination进行分组,代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& by_dest &- group_by(myFlights, destination)
& class(by_dest)
[1] &grouped_df& &tbl_df&
&data.frame&
Source: local data frame [327,346 x 7]
Groups: destination [104]
year month
day dep_delay arr_delay distance destination
&int& &int& &int&
# ... with 327,336 more rows
&/code&&/pre&&/div&&p&分组后一共有104组数据。&br&&/p&&p&dplyr包中的summarize()函数完成剩下应用函数和组合结果两步。summarize()函数的help文档如下:&/p&&p&&figure&&img src=&https://pic1.zhimg.com/v2-f50a307cb1a80a97d1222371bcb698ec_b.jpg& data-rawwidth=&572& data-rawheight=&564& class=&origin_image zh-lightbox-thumb& width=&572& data-original=&https://pic1.zhimg.com/v2-f50a307cb1a80a97d1222371bcb698ec_r.jpg&&&/figure&summarize()函数传入的第一个参数是分组后的数据表,同时是group_by()函数返回的grouped_df类型的数据对象,在上一步当中特地用class()函数查看了下by_dest的类型。&/p&&p&后面的参数是各种需要计算的表达式,表达式的通用格式如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&variable = appliedFunction(variables in the original grouped_df object)
&/code&&/pre&&/div&&p&等号左边的是summarize()所返回对象数据表中的变量名,appliedFunction是你需要计算的统计量,比如求平均就是mean(),标准差就是sd(),appliedFunction()中的参数就是在分组后的数据表中你要了解的变量名称,比如本例我们队飞行距离感兴趣就是distance, 对到达延误时间感兴趣就是arr_delay。具体代码如下:&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& delay_Tab &- summarise(by_dest,
count = n(),#统计各分组目的地的航班数
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE))
&/code&&/pre&&/div&&br&&p&原课件中summarize()函数是赋值给delay,这容易和summarize()函数当中定义的delay向混淆,其实函数中的delay只是函数返回数据表中的一个变量,为了避免混淆,这里取了delay_Tab以示区分,具体可以看下面的代码:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& head(delay_Tab)
# A tibble: 6 × 4
destination count
&chr& &int&
ATL 183 11.300113
& class(delay_Tab)
[1] &tbl_df&
&data.frame&
&/code&&/pre&&/div&&p&最后再利用filter()函数移除一些噪音数据,即数据量太少的组,这里设置为20。&br&&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&delay_Tab &- filter(delay_Tab, count & 20)
&/code&&/pre&&/div&&p&至此,数据计算的步骤完成,为了使得代码更加的整洁,我们尝试使用一个叫做管道的工具。在介绍管道之前,我们试着用一行代码完成上述数据计算过程:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& delay_Tab2 &- filter(summarise(group_by(myFlights,destination),
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)),
count & 20)
&/code&&/pre&&/div&&p&以上是多层函数的嵌套,即后面一个函数的输出为前面一个函数的输入,这样可以减少不必要中间变量的引入,为了使得层次更加分明一些,表达更加简洁一些,可以采用管道,格式如下:&br&&/p&&p&&b&
%&%&/b&&/p&&p&管道的思路很简单,将左边的值管道输出为右边调用的函数的第一个参数。举个例子:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& set.seed(1234)
& rnorm(3) %&% sum()
[1] 0.1548047
& set.seed(1234)
& rnorm(3)
[1] -1...0844412
&/code&&/pre&&/div&&p&此处第二行就是讲rnorm(3)生成的三个随机数作为sum()函数的输入进行求和,下面我设定相同的随机数种子进行了验证。&br&&/p&&p&如果采用管道,本例的数据计算可以用以下代码实现:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&delay_Tab &- myFlights %&%
group_by(destination) %&%
summarise(
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
filter(count & 20)
&/code&&/pre&&/div&&p&&b&2.5 数据显示&/b&&br&&/p&&p&本次的数据显示主要采用ggplot2包。ggplot2包功能强大,内容包罗万象,本文主要结合第四讲的内容简单讲讲如何用ggplot2包中的函数进行画图,向具体了解的可以进一步阅读该包作者Hadley Wichham的专著:&a href=&https://link.zhihu.com/?target=http%3A//libgen.io/book/index.php%3Fmd5%3D5B5FAFF2DE904D841A893D132D26C040& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&Library Genesis: Hadley Wickham (auth.)&i class=&icon-external&&&/i&&/a&&/p&&p&或者关注github ggplot2的代码库(&a href=&https://link.zhihu.com/?target=https%3A//github.com/tidyverse/ggplot2& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&tidyverse/ggplot2&i class=&icon-external&&&/i&&/a&),了解最新的开发情况。&/p&&br&&p&首先,需要安装并导入ggplot2包:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&install.packages(&ggplot2&)
library(ggplot2)
&/code&&/pre&&/div&&p&调用ggplot()函数进行绘图,ggplot()函数主要调用结构如下:&br&&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-51fc8fe2fabc53b2840ddb3f11517e25_b.jpg& data-rawwidth=&550& data-rawheight=&393& class=&origin_image zh-lightbox-thumb& width=&550& data-original=&https://pic2.zhimg.com/v2-51fc8fe2fabc53b2840ddb3f11517e25_r.jpg&&&/figure&首先用 data 参数设定好数据源,然后根据需要用ggplot2()包中的其他函数往图像当中添加图层。本讲中首先绘制了航程和延误时间的散点图,然后拟合了一条平滑曲线,代码如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&view &- ggplot(data = delay_Tab) +
geom_point(mapping = aes(x = dist, y = delay))+
geom_smooth(mapping = aes(x = dist, y = delay))
&/code&&/pre&&/div&&figure&&img src=&https://pic1.zhimg.com/v2-844f7dbf79ead85dcb4e9e8a379f3d48_b.jpg& data-rawwidth=&1040& data-rawheight=&900& class=&origin_image zh-lightbox-thumb& width=&1040& data-original=&https://pic1.zhimg.com/v2-844f7dbf79ead85dcb4e9e8a379f3d48_r.jpg&&&/figure&&h2&&b&3 编写业务模块&/b&&/h2&&p&本质上这是一个文件管理的问题,包括数据文件、代码文件、输出文件、日志文件等等,甚至还可以再细分,比如是实现业务逻辑的文件、实现数据输入输出的文件、实现视图输出的文件等等,每个人有每个人的风格,但是模块化的方法论是一通百通的。总之,大家多实践,多敲代码,如果一开始不知道怎么弄的话,按照&a href=&https://www.zhihu.com/people/c9b28ce4b50bf224cb06f& data-hash=&c9b28ce4b50bf224cb06f& class=&member_mention& data-editable=&true& data-title=&@猴子& data-hovercard=&p$b$c9b28ce4b50bf224cb06f&&@猴子&/a&的方法应该是个不错的选项。&/p&&h2&&b&4 代码调试&/b&&/h2&&p&这也是一个与实践紧密结合的话题,也是一个很大的话题,当下,首先应该熟悉一下Rstudio的一些调试手段。&/p&&p&最后,本讲内容还有两个作业,首先关于翻译,我觉得翻译下面这篇文章:&/p&&br&&p&&a href=&https://link.zhihu.com/?target=http%3A//vita.had.co.nz/papers/bigvis.pdf& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&bin-summarise-smooth: A framework for visualising large data&i class=&icon-external&&&/i&&/a&: 合并-分组应用-平滑:一种大数据可视化的框架&br&&/p&&p&然后关于数据,我想以&a href=&https://link.zhihu.com/?target=https%3A//www.kaggle.com/deepmatrix/imdb-5000-movie-dataset& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&IMDB 5000 Movie Dataset&i class=&icon-external&&&/i&&/a&选定一些角度进行分析,具体问题还没有想好,如果有好的建议欢迎留言。&/p&
距离上一讲已经将近一个多月,这次 老师憋了很多内容,光直播就进行了两个多小时,布置的作业也非常有分量,在完成作业之前,很有必要对讲课内容作一个笔记整理,算是在完成作业之前的一个复习。本次课程主要讲了四块内容,解决了一个问题,四块内容如…
&figure&&img src=&https://pic4.zhimg.com/v2-e08c63de3c040db72a46cdd40c9b6557_b.jpg& data-rawwidth=&618& data-rawheight=&300& class=&origin_image zh-lightbox-thumb& width=&618& data-original=&https://pic4.zhimg.com/v2-e08c63de3c040db72a46cdd40c9b6557_r.jpg&&&/figure&&h1&&strong&向数据框中添加新的列,以数据集Loblolly为例。&/strong&&br&&/h1&&p&该数据集包含了各种树的高度和年龄,以下通过三种方式加以实现新增变量:&/p&&p&&strong&方法一:使用一个$符&/strong&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-a11ac480db8_b.jpg& data-rawwidth=&473& data-rawheight=&352& class=&origin_image zh-lightbox-thumb& width=&473& data-original=&https://pic1.zhimg.com/v2-a11ac480db8_r.jpg&&&/figure&&p&&strong&方法二:within函数 必须在新添加的变量中加上花括号&/strong&&/p&&p&&figure&&img src=&https://pic3.zhimg.com/v2-1aae486cd8f6f86c3c6d5c5_b.jpg& data-rawwidth=&527& data-rawheight=&207& class=&origin_image zh-lightbox-thumb& width=&527& data-original=&https://pic3.zhimg.com/v2-1aae486cd8f6f86c3c6d5c5_r.jpg&&&/figure&&strong&也可以使用with函数,该函数可以用于任何表达式的计算,但每次只能生成一个计算字段,最后还需要结合使用cbind函数&/strong&&/p&&figure&&img src=&https://pic2.zhimg.com/v2-0034acc2f1fefd410f0720_b.jpg& data-rawwidth=&498& data-rawheight=&225& class=&origin_image zh-lightbox-thumb& width=&498& data-original=&https://pic2.zhimg.com/v2-0034acc2f1fefd410f0720_r.jpg&&&/figure&&p&&strong&方法三:transform函数&/strong&&/p&&figure&&img src=&https://pic2.zhimg.com/v2-67badd73618ffc3c1eaed_b.jpg& data-rawwidth=&635& data-rawheight=&206& class=&origin_image zh-lightbox-thumb& width=&635& data-original=&https://pic2.zhimg.com/v2-67badd73618ffc3c1eaed_r.jpg&&&/figure&&p&&strong&删除数据框中的某一列:&/strong&建议使用subset函数,只需在删除的列前添加负号即可。&/p&&figure&&img src=&https://pic2.zhimg.com/v2-fc076d1ebb02e99cc98cf6f_b.jpg& data-rawwidth=&601& data-rawheight=&182& class=&origin_image zh-lightbox-thumb& width=&601& data-original=&https://pic2.zhimg.com/v2-fc076d1ebb02e99cc98cf6f_r.jpg&&&/figure&&p&&strong&更改数据框中所有数值变量的值,可以考虑结合使用apply函数和sapply函数。&/strong&例如,现在想对x1和x2的列进行转换,转换为原来值的平方再对数。&/p&&figure&&img src=&https://pic1.zhimg.com/v2-4a2a2ca28bb8dd_b.jpg& data-rawwidth=&645& data-rawheight=&385& class=&origin_image zh-lightbox-thumb& width=&645& data-original=&https://pic1.zhimg.com/v2-4a2a2ca28bb8dd_r.jpg&&&/figure&&p&&strong&变量的重编码:即根据已有的变量重新编码,如连续变量的离散化。&/strong&例如,现在想把data9中的x变量重编码,x&13则编码为1,x&=13且x&15则编码为2,剩余的编码为3。&/p&&figure&&img src=&https://pic4.zhimg.com/v2-a50a5cc1f61_b.jpg& data-rawwidth=&524& data-rawheight=&271& class=&origin_image zh-lightbox-thumb& width=&524& data-original=&https://pic4.zhimg.com/v2-a50a5cc1f61_r.jpg&&&/figure&&p&实际上R中有专门的重编码函数,&strong&car包中recode的函数可以非常灵活的对某个已有的变量进行重新编码&/strong&。但我觉得&strong&在对连续变量进行分组操作时显得有点不方便,对于区间[1.2,5.5)表示成‘1.2:5.5 = 1’,但该函数会把5.5分配到该区间中。&/strong&&/p&&p&library(car)&/p&&p&&strong&语法:&/strong&&/p&&p&recode(var, recodes, as.factor.result, as.numeric.result=TRUE, levels)&/p&&p&var为一个数值向量,recodes为重编码的规则。&/p&&p&&strong&对于变量的重编码问题,相比较within和recode函数,我个人更喜欢使用within函数。&/strong&&/p&&p&&strong&有时在数据处理过程中需要将长型数据框转化为宽型数据框或者将宽型数据框转换为长型数据框。&/strong&&/p&&p&&strong&宽型数据框:一个观测(id)记录在一行中,没有重复的id出现&/strong&&/p&&p&&strong&长型数据框:一个观测(id)记录在多行中,会有重复的id出现&/strong&&/p&&p&例如以下的数据框df1为宽型,df2为长型&/p&&figure&&img src=&https://pic4.zhimg.com/v2-3cd74b1cbd310b942dd6a_b.jpg& data-rawwidth=&552& data-rawheight=&423& class=&origin_image zh-lightbox-thumb& width=&552& data-original=&https://pic4.zhimg.com/v2-3cd74b1cbd310b942dd6a_r.jpg&&&/figure&&p&&strong&对于宽型数据框转换为长型数据框可以使用reshape2包中的melt函数&/strong&&/p&&figure&&img src=&https://pic4.zhimg.com/v2-ed3cbd1e7bf_b.jpg& data-rawwidth=&638& data-rawheight=&295& class=&origin_image zh-lightbox-thumb& width=&638& data-original=&https://pic4.zhimg.com/v2-ed3cbd1e7bf_r.jpg&&&/figure&&p&&strong&对于长型数据框转化为宽型数据框可以使用stats包中的reshape函数。&/strong&&/p&&p&&strong&reshape函数&/strong&需要至少&strong&5个参数&/strong&,&strong&第一个参数&/strong&为被重塑的数据框,&strong&第二个参数&/strong&通过v.names指定非分组变量或观测值,&strong&第三个参数&/strong&timevar指定分组变量或因子,&strong&第四个参数&/strong&idvar指定重复出现的观测单位,&strong&最后一个参数&/strong&direction指定转换的类型,其值为'wide'和'long'两种。&strong&当然可能用到drop参数,指定不需要的观测值变量。&/strong&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-5a770bd54e_b.jpg& data-rawwidth=&611& data-rawheight=&139& class=&origin_image zh-lightbox-thumb& width=&611& data-original=&https://pic3.zhimg.com/v2-5a770bd54e_r.jpg&&&/figure&&p&再举一个例子,现在是两个观测变量x和y,将长型数据框变为宽型数据框&/p&&figure&&img src=&https://pic2.zhimg.com/v2-81bbf438fd319b1fb2a4_b.jpg& data-rawwidth=&653& data-rawheight=&210& class=&origin_image zh-lightbox-thumb& width=&653& data-original=&https://pic2.zhimg.com/v2-81bbf438fd319b1fb2a4_r.jpg&&&/figure&&p&但&strong&发现这样的宽型数据框的列x和y是交错重复出现的&/strong&,为了x和y分开存放,可以&strong&结合一下melt和cast函数&/strong&。&/p&&p&&figure&&img src=&https://pic2.zhimg.com/v2-51b8c3040ee34afe2d1e7cc295e85799_b.jpg& data-rawwidth=&651& data-rawheight=&222& class=&origin_image zh-lightbox-thumb& width=&651& data-original=&https://pic2.zhimg.com/v2-51b8c3040ee34afe2d1e7cc295e85799_r.jpg&&&/figure&&strong&注意这里派生列的名称是按公式中右边变量输入的顺序建立的&/strong&&/p&&p&&strong&数据框的合并&/strong&&/p&&p&普通情况下一般重用的有&strong&rbind函数、cbind函数和merge函数&/strong&。这里重点介绍一下&strong&plyr包中的join函数&/strong&,该函数在合并数据框时非常的方便,类似于数据库语言中的表连接。&/p&&p&&strong&语法:&/strong&&/p&&p&join(x, y, by = NULL, type = &left&, match = &all&)&/p&&p&其中x和y是被要合并的数据框;by为x和y中的连接字段;type为合并类型,有左连、右连、内连和全连四种;match用来数据合并过程中重复值的处理,默认情况下不排除重复值,当指定first时,则保留重复值中的第一个。&/p&&p&下面首先建立两个数据框。&br&&/p&&figure&&img src=&https://pic3.zhimg.com/v2-cf20bdab6a09b7bb98b6ad_b.jpg& data-rawwidth=&533& data-rawheight=&272& class=&origin_image zh-lightbox-thumb& width=&533& data-original=&https://pic3.zhimg.com/v2-cf20bdab6a09b7bb98b6ad_r.jpg&&&/figure&&p&接下来看一看join函数是如何合并数据框的。&/p&&p&左连和右连:&br&&/p&&figure&&img src=&https://pic1.zhimg.com/v2-449f6fc8f565ac_b.jpg& data-rawwidth=&550& data-rawheight=&313& class=&origin_image zh-lightbox-thumb& width=&550& data-original=&https://pic1.zhimg.com/v2-449f6fc8f565ac_r.jpg&&&/figure&&p&内连和全连&/p&&figure&&img src=&https://pic4.zhimg.com/v2-042e44de1d1d91da2658b4_b.jpg& data-rawwidth=&458& data-rawheight=&296& class=&origin_image zh-lightbox-thumb& width=&458& data-original=&https://pic4.zhimg.com/v2-042e44de1d1d91da2658b4_r.jpg&&&/figure&&p&&strong&其实这里的join函数,跟数据库中的表连接是一个意思。&/strong&&/p&&p&以上是对数据框的常见操作,最后再对用到的R包和函数做一个总结:&/p&&p&stats包&/p&&p&with()&/p&&p&within()&/p&&p&transform()&/p&&p&subset()&/p&&p&reshape()&/p&&p&rbind()&/p&&p&cbind()&/p&&p&merge()&/p&&p&car包&/p&&p&recode()&/p&&p&reshape包&/p&&p&melt()&/p&&p&cast()&/p&&p&plyr包&/p&&p&rename()&/p&&p&join()&/p&&br&&p&----------------------------------------------&/p&&p&作者:刘顺祥&/p&&p&出处:&a href=&https://link.zhihu.com/?target=https%3A//ask.hellobi.com/blog/lsxxx2011& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&刘顺祥博客&i class=&icon-external&&&/i&&/a&&/p&&p&公众号:每天进步一点点2015&/p&&p&&b&大家也可以加小编微信:tswenqu,进R语言中文社区 交流群,可以跟各位老师互相交流&/b&&/p&
向数据框中添加新的列,以数据集Loblolly为例。 该数据集包含了各种树的高度和年龄,以下通过三种方式加以实现新增变量:方法一:使用一个$符方法二:within函数 必须在新添加的变量中加上花括号也可以使用with函数,该函数可以用于任何表达式的计算,但每次…
&figure&&img src=&https://pic1.zhimg.com/v2-34a233b40a65dbef7cae98c565d02d8f_b.jpg& data-rawwidth=&930& data-rawheight=&585& class=&origin_image zh-lightbox-thumb& width=&930& data-original=&https://pic1.zhimg.com/v2-34a233b40a65dbef7cae98c565d02d8f_r.jpg&&&/figure&&p&&strong&前言&/strong&&/p&&p&久经股市的老股民,通常都会使用一种常见的交易策略,追涨杀跌交易法。追涨杀跌法,是股市操作的一个重要技巧,就是在股市上涨时买入股票,股市下跌时卖出股票。如果操作得当是很好的赢利手段,在中国股市2015年上半年的牛市中,追涨杀跌交易法就是交易神器法门。&/p&&p&&strong&目录&/strong&&/p&&ol&&li&什么是追涨杀跌?&/li&&li&追涨杀跌的建型和实现&/li&&li&模型优化&/li&&/ol&&h2&1. 什么是追涨杀跌?&/h2&&p&追涨杀跌是金融市场的专业术语,是金融技术派操盘的一种方式,与抄底摸顶的操作方式刚好相反。追涨杀跌的操作方法是,金融市场中在金融产品(股票,期货,外汇等)价格上涨的时候买入,以期待涨得更多,并以更高的价格卖出获利;在价格下跌的时候卖出进行止损,不管之前金融产品买入的价格是多少,都立刻卖出,以避免更大的损失。&/p&&p&下面以平安银行(000001)股票日K线图为例,截取2005年到2015年7月的股票数据,股价为向前复权的价格。&/p&&figure&&img src=&https://pic3.zhimg.com/v2-fb3cbf9a3cb19bb40b51e44c063ede5e_b.jpg& data-rawwidth=&1024& data-rawheight=&412& class=&origin_image zh-lightbox-thumb& width=&1024& data-original=&https://pic3.zhimg.com/v2-fb3cbf9a3cb19bb40b51e44c063ede5e_r.jpg&&&/figure&&br&&p&上图中有3条曲线,黑色线是平安银行向前复权后的每日股价,红色线为20日均线,蓝色线为60日均线。关于均线的介绍,请参考文章 &a href=&https://link.zhihu.com/?target=http%3A//blog.fens.me/finance-stock-ma/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&两条均线打天下&i class=&icon-external&&&/i&&/a&。图中还有一条红色的水平线虚线,是这10年的股价平均值等于7.14元。这10年间,平安银行股价起起落落,每次上涨都会持续一段时间,那么在我们可以上涨中段追入买进,在大幅下跌之前卖出,就是追涨杀跌法。&/p&&p&&strong&追涨&/strong&&/p&&p&追涨通常有2种情况,短线追涨和中线追涨。以股票交易为例。&/p&&ul&&li&短线追涨:当天股价已经涨了5个点或更多,这时追进去买入,期待当天收盘涨停,等下一个交易日高价卖出,这就是短线追涨。&/li&&li&中线追涨:某只股票的股价已经上涨了一段时间,走势很强,底部上涨已经有30%或更多,这个时追进去买入,期待后势持续上涨,是中线追涨。&/li&&/ul&&p&不论短线追涨还是中线追涨,我们追涨的理由和判断的标准都是一样的,“涨得好的股票说明走势很强,那么追强势股期待股票持续上涨”。但从另一个角度看,追涨的风险也是很大的,关键在于我们不知道它能涨到什么时候,到什么位置可能会回调,什么时候是庄家出货。所以说追涨技巧性很强,什么情况下能追,什么情况下不能追,都是很有讲究的。&/p&&p&&strong&杀跌&/strong&&/p&&p&杀跌也是一门较深的操作技巧,杀得好的话既可以回避风险。如果不能进行杀跌的准确判断,则很可能会发生硬性止损,导致严重的亏损。&/p&&p&采取杀跌战术,必须掌握以下操作要点:&/p&&ul&&li&杀跌的重要前提是知变,就是对消息、对量能、对周边各种因素的影响有一个准确的、快速的知变过程。&/li&&li&杀跌要善于观察盘面、形态、消息、舆论等方面的细微变化,在对大盘作出准确估量的基础上,迅速作出反应就是确定卖出哪支股票,卖出多少等。&/li&&li&杀跌要善于思考大盘与目标股之问的正向、反向的相关性,及目标股的能量能等方向的关系,从中找出变动的规律。&/li&&li&当市场利好消息接踵而至时,应随时准备卖出股票。当利好出尽就会转向利空,往往消息明朗时,股价早已下跌大半,导致措手不及。&/li&&/ul&&p&杀跌的后续操作就比较简单了,只需保持良好的心态,耐心等待见底信号后再抄底。一般只有在底部成功接回股票或换股才算成功的杀跌,否则杀跌会失去意义。应保持耐心,千万不要在股价反弹时贸然介入,否则屡买屡跌、会加大损失,应待股价反转时再介入。&/p&&p&&strong&追涨杀跌的技巧&/strong&&/p&&p&要观大势,看清整个市场多空对决的优势一方是谁。&/p&&p&追涨杀跌的假设条件:&/p&&ul&&li&市场处于强势交易格局。强势格局赋予个股良好的运作基础;相反,如果市场处于平衡状态,就不适合进行追涨杀跌,更适合高抛低吸。&/li&&li&市场形成了鲜明并有持续性上涨能力的热点或板块效应。&/li&&/ul&&p&追涨操作的对象:&/p&&ul&&li&市场形成鲜明的可持续性的热点时,可追涨这个热点。从理论上讲,只要把握热点板块就能获利,追涨时应重点关注龙头企业。比如:沪深300指数的成分股,就是不错的选择。&/li&&li&形成明显的上涨趋势的个股可以考虑追涨。个股突破重要的压力线,如头肩底形态的颈线位、整理箱体的箱顶位、三角形的上边眼、长期下降趋势线等,待回抽确认其突破的有效性后,可考虑追涨。&/li&&/ul&&p&追涨杀跌的注意事项:&/p&&ul&&li&追涨时应设好止盈位和止损位,确定自己的大致盈利目标。&/li&&li&追涨杀跌应该注意频率的减少,过于频繁的操作,一旦失误增多会严重影响情绪。&/li&&li&追涨杀跌中要多一分平和的心态,少一些侥幸;多一分理性,少一分感性。&/li&&/ul&&p&&strong&追涨杀跌的市场操作&/strong&&/p&&p&在弱市中,短线追涨往往容易被套,因为弱市里大部分股票的行情只有一天,当天追得高了,第二天多半没有获利逃出的机会。相反,弱市中,中线追涨比较可取,能够在弱市中保持强势的股票不多,但这种强势反而可以持续。但很多时候,弱市中这样的股票反倒不敢追了。&/p&&br&&p&有些人专门追涨停板,追新股开板,追次新股开板等,对于2015年上半年IPO的新股来说收获颇丰,如暴风科技,中超电缆等,其他的时候可能用这套追涨停策略就行不通了。&/p&&figure&&img src=&https://pic2.zhimg.com/v2-f8b16f7d30ad3cef98ad3d_b.jpg& data-rawwidth=&1051& data-rawheight=&629& class=&origin_image zh-lightbox-thumb& width=&1051& data-original=&https://pic2.zhimg.com/v2-f8b16f7d30ad3cef98ad3d_r.jpg&&&/figure&&p&我自己操作并不会盲目追涨,安全第一,虽然还没有吃过追涨的亏,但由于本人目前还不具备基本面的分析能力,也没有消息的渠道,仅仅从技术指标入手,投机性太重,很容易被庄家玩死的。道理很简单,因为如果追涨了,下跌的空间自然就大了,尤其中线追涨,庄家获利后随时可能出货。这时候就必须要做好杀跌的策略。庄股出货跌个50%太普遍了,而且跌下去就很难再起来,这种时候不杀跌就等于自杀。所以,追涨之前一定要想清楚,务必先设好止损位,不能只憧憬获利的美妙。&/p&&p&杀跌也有讲究,不是一跌就杀,震荡、洗盘是很常见的,问题在于正确地区别震仓与出货是很难的,所以很多人是硬性止损,即预先设定价位或百分比,到这个位置就坚决出局,不管它是震仓还是庄家出货。这个时候如果没有基本面的判断或第一手消息的来源,就容易被震荡出局。当然,和不确定的风险相比,我其实更愿意早点出来。&/p&&h2&2. 追涨杀跌的建型和实现&/h2&&p&既然我们要进行追涨杀跌的操作,就要定义什么是追涨,什么又是杀跌,需要把追涨杀跌的概念量化出来,从而进行建模和实现。对于短线追涨策略可以简单粗暴地选择当日涨幅超过5%的股票进行买入,第二日开盘卖出或到止损位卖出,并没有太多的技术细节,再计算一下胜率概率,就能知道我们要不要短线追涨。&/p&&p&下文我们将以中线追涨为例,进行建模和程序实现。&/p&&p&那么对于中线追涨的情况,我们核心的策略思路就可以转化为,当股价(成交量)向上突破最近20日最高价格(量)时买入,当股价向下突破最近10日最低价格卖出,并以沪深300成分股做为股票交易的标的。其中,为什么是20日最高和10日最低都是经验值,可以做为模型参数进行训练和优化。选择沪深300成分股为标的,是考虑到这些股票都是各个板块的强势股或龙头股,要符合追涨杀跌的假设条件。&/p&&p&计算公式:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&20日最高价 = max(T日股价,T-1日股价 ... , T-19日股价)
20日最高量 = max(T日成交量,T-1日成交量 ... , T-19日成交量)
10日最低价 = min(T日股价,T-1日股价 ... , T-9日股价)
&/code&&/pre&&/div&&p&当股价大于等于20日最高价时作为买入信号点,当股价小于等于10日最低价时作为卖出信号点。这样我们就把追涨杀跌的投资理论,变成了一个数学模型。&/p&&p&接下来,我们利用R语言对股票数据的进行操作,来实现一个追涨杀跌模型的实例,从而验证我的们投资理论,是否能发现赚钱的机会。&/p&&p&&strong&2.1 数据准备&/strong&&/p&&p&R语言本身提供了丰富的金融函数工具包,时间序列包zoo和xts,指标计算包TTR,数据处理包plyr,可视包ggplot2等,我们会一起使用这些工具包来完成建模、计算和可视化的工作。关于zoo包和xts包的详细使用可以参考文章,&a href=&https://link.zhihu.com/?target=http%3A//blog.fens.me/r-zoo/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&R语言时间序列基础库zoo&i class=&icon-external&&&/i&&/a&,&a href=&https://link.zhihu.com/?target=http%3A//blog.fens.me/r-xts/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&可扩展的时间序列xts&i class=&icon-external&&&/i&&/a&。&/p&&p&我本次用到的数据是从 况客 直接导出的,况客 会提供各种类型的金融数据API,让开发者可以免费下载。当然,你也可以用quantmod包从Yahoo财经下载数据。&/p&&p&本文用到的数据,包括A股日K线(向前复权)数据,从2014年7月到2015年日8月,以CSV格式保存到本地文件stock.csv。&/p&&p&数据格式如下:&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&000001.SZ,,8.14,8.18,8.10,8.17,
000002.SZ,,8.09,8.13,8.05,8.12,
000004.SZ,,13.9,13.99,13.82,13.95,1081139
000005.SZ,,2.27,2.29,2.26,2.28,4157537
000006.SZ,,4.57,4.57,4.50,4.55,5137384
000010.SZ,,6.6,6.82,6.5,6.73,9909143
&/code&&/pre&&/div&&p&一共7列:&/p&&ul&&li&第1列,股票代码,code,000001.SZ&/li&&li&第2列,交易日期,date,&/li&&li&第3列,开盘价,Open,8.14&/li&&li&第4列,最高价,High,8.18&/li&&li&第5列,最低价,Low,8.10&/li&&li&第6列,收盘价,Close,8.17&/li&&li&第7列,交易量,Volume,&/li&&/ul&&p&通过R语言加载股票数据,由于数据所有股票都是混合在一起的,而进行计算时又需要按每支票股计算,所以在数据加载时我就进行了转换,按股票代码进行分组,生成R语言的list对象,同时把每支股票的data.frame类型对象转成XTS时间序列类型对象,方便后续的数据处理。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&#加载工具包
& library(plyr)
& library(xts)
& library(TTR)
& library(ggplot2)
& library(scales)
# 读取CSV数据文件
& read&-function(file){
df&-read.table(file=file,header=FALSE,sep = &,&, na.strings = &NULL&) # 读文件
names(df)&-c(&code&,&date&,&Open&,&High&,&Low&,&Close&,&Volume&)
# 设置列名
dl&-split(df[-1],df$code)
# 按ccode分组
lapply(dl,function(row){
# 换成xts类型数据
xts(row[-1],order.by = as.Date(row$date))
# 加载数据
& data&-read(&stock.csv&)
# 查看数据类型
& class(data)
[1] &list&
# 查看数据的索引值
& head(names(data))
[1] &000001.SZ& &000002.SZ& &000004.SZ& &000005.SZ& &000006.SZ& &000007.SZ&
# 查看包括的股票数量
& length(data)
# 获得时间范围
dateArea&-function(sDate=Sys.Date()-365,eDate= Sys.Date(),before=0){
#开始日期,结束日期,提单开始时
if(class(sDate)=='character') sDate=as.Date(sDate)
if(class(eDate)=='character') eDate=as.Date(eDate)
return(paste(sDate-before,eDate,sep=&/&))
# 查看股票000001.SZ
& head(data[['000001.SZ']])
8....04171
8....90486
8....31126
8....06164
8....08702
8....89114
&/code&&/pre&&/div&&p&把数据准备好了,我们就可以来建立模型了。&/p&&p&&strong&2.2 追涨杀跌模型&/strong&&/p&&p&为了能拉近我们对市场的了解,我们取从日开始的数据,来创建追涨杀跌的模型。以乐视网(300104)的为例,画出乐视网自2015年以来的每日收盘价,20日最高价和10日最低价。乐视网作为创业板标杆的上市公司,在2015年7月首次被纳入沪深300指数。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 日K线数据
& title&-'300104.SZ'
& stock&-data[[title]]
# 获得股票数据
& sDate&-as.Date(&&)
# 开始日期
& eDate&-as.Date(&&)
# 结束日期
& cdata&-stock[dateArea(sDate,eDate,360)]$Close
# 获得收盘价
& vdata&-stock[dateArea(sDate,eDate,360)]$Volume
# 获得交易量
& names(cdata)&-&Value&
# 重置列名
& tail(cdata)
& tail(vdata)
&/code&&/pre&&/div&&p&定义画图函数drawLine(),支持画出多条曲线,包括收盘价,最高价,最低价。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 画图函数
& drawLine&-function(cdata,titie=&Stock&,sDate=min(index(cdata)),eDate=max(index(cdata)),breaks=&1 year&){
if(sDate&min(index(cdata))) sDate=min(index(cdata))
if(eDate&max(index(cdata))) eDate=max(index(cdata))
cdata&-na.omit(cdata)
g&-ggplot(aes(x=Index, y=Value),data=fortify(cdata[,1],melt=TRUE))
g&-g+geom_line()
if(ncol(cdata)&1){ # 多条线
g&-g+geom_line(aes(colour=Series),data=fortify(cdata[,-1],melt=TRUE))
g&-g+scale_x_date(labels=date_format(&%Y-%m&),breaks=date_breaks(breaks),limits = c(sDate,eDate))
g&-g+ylim(min(cdata$Value), max(cdata$Value))
g&-g+xlab(&&) + ylab(&Price&)+ggtitle(title)
# 画出收盘价
# drawLine(cdata,title,sDate,eDate,'1 month')
# 计算最近20日的最高价和10日的最低价
& minmax&-function(data,max=20,min=10){
d1&-na.locf(data,fromLast=TRUE)
d2&-merge(d1,min=runMin(d1,min),max=runMax(d1,max))
return(d2[,-1])
# 画出股价,最高价和最低价
& ldata&-cbind(cdata,minmax(cdata))
& drawLine(ldata,title,sDate,eDate,'1 month')
&/code&&/pre&&/div&&figure&&img src=&https://pic3.zhimg.com/v2-a6d0eefb37ac9addbc1b2_b.jpg& data-rawwidth=&1052& data-rawheight=&409& class=&origin_image zh-lightbox-thumb& width=&1052& data-original=&https://pic3.zhimg.com/v2-a6d0eefb37ac9addbc1b2_r.jpg&&&/figure&&br&&p&上图中有3条线,黑色线为乐视网的每日收盘价,蓝色线为最近20日最高价,红色线为最近10日最低价。&/p&&p&根据模型的计算公式,我们计算买入信号,当股价向上突破最近20日最高价格时买入。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 买入信号函数
& buyPoint&-function(ldata){
idx&-which(ldata$Value == ldata$max)
return(ldata[idx,])
# 计算买入的点
& buydata&-buyPoint(ldata)
17.64 17.43721
17.54 17.98709
19.54 19.53222
20.32 20.21389
22.49 22.23619
23.16 23.04056
23.16 23.89947
24.74 24.77656
25.43 25.16284
26.33 26.91247
28.33 28.68482
31.33 31.55239
31.33 31.87960
35.45 35.06983
38.13 38.57817
40.53 40.99130
41.53 41.07764
41.53 41.94564
45.93 45.34946
46.31 46.27199
50.31 50.89829
50.31 50.90283
55.31 55.44277
60.31 60.98705
62.95 62.25497
66.99 66.20413
67.29 67.23573
73.83 73.96157
81.77 81.36000
82.14 82.49000
&/code&&/pre&&/div&&p&画出买入的信号图,让我们可以直观的看到效果。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 画图函数
& drawPoint&-function(ldata,pdata,titie,sDate,eDate,breaks=&1 year&){
ldata&-na.omit(ldata)
g&-ggplot(aes(x=Index, y=Value),data=fortify(ldata[,1],melt=TRUE))
g&-g+geom_line()
g&-g+geom_line(aes(colour=Series),data=fortify(ldata[,-1],melt=TRUE))
if(is.data.frame(pdata)){
g&-g+geom_point(aes(x=Index,y=Value,colour=op),data=pdata,size=4)
g&-g+geom_point(aes(x=Index,y=Value,colour=Series),data=na.omit(fortify(pdata,melt=TRUE)),size=4)
g&-g+scale_x_date(labels=date_format(&%Y-%m&),breaks=date_breaks(breaks),limits = c(sDate,eDate))
g&-g+xlab(&&) + ylab(&Price&)+ggtitle(title)
& drawPoint(ldata,buydata$Value,title,sDate,eDate,'1 month')
&/code&&/pre&&/div&&figure&&img src=&https://pic4.zhimg.com/v2-24a267f72bb8d78c6e101df_b.jpg& data-rawwidth=&1040& data-rawheight=&445& class=&origin_image zh-lightbox-thumb& width=&1040& data-original=&https://pic4.zhimg.com/v2-24a267f72bb8d78c6e101df_r.jpg&&&/figure&&p&如上图所示,蓝色的点为股价大于等于最近20日最高价的点,作为买入信号。所有买入信号点,都是出现在单边上行的牛势中,对于2015年上半年以来的行情来说,追涨的信号会被大量触发。&/p&&p&接下来,我们继续计算卖出信号点,当股价小于等于最近10日最低价时作为卖出信号点。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& # 计算卖出的信号点
& stopPoint&-function(ldata,buydata){
idx&-which(ldata$Value == ldata$min)
idx&-idx[which(c(0,diff(idx))!=1)]
# 第一点用0表示
selldata&-ldata[idx,]
# 所有低于最小值的点
idx2&-sapply(index(buydata),function(e){
# 买后的卖点
head(which(index(selldata)&e),1)
return(selldata[unique(idx2),])
# 卖出信号
& selldata&-stopPoint(ldata,buydata)
& selldata
21.33 25.16284
34.53 40.99130
38.11 45.34946
64.00 82.49000
&/code&&/pre&&/div&&p&一共有4笔卖出信号,为了让数据更加直观,我们合并买入信号和卖出信号,进行画图可视化。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 买卖信号,画图
& bsdata&-merge(buydata$Value,selldata$Value)
& names(bsdata)&-c(&buy&,&sell&)
& drawPoint(ldata,bsdata,title,sDate,eDate,'1 month') #画图
&/code&&/pre&&/div&&figure&&img src=&https://pic3.zhimg.com/v2-cfebeb46ff9d9be5e39487_b.jpg& data-rawwidth=&1028& data-rawheight=&443& class=&origin_image zh-lightbox-thumb& width=&1028& data-original=&https://pic3.zhimg.com/v2-cfebeb46ff9d9be5e39487_r.jpg&&&/figure&&p&上图中,紫色点为卖出信号点,红色点为买入信号点。我们可以很明显的看出,如果根据交易信号在红色点买入,紫色点卖出,我们是应该赚钱的。那么具体赚了多少呢,我需要计算出来?&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& # 合并交易信号
& signal&-function(buy, sell){
selldf&-data.frame(sell,op=as.character(rep(&S&,nrow(sell))))
buydf&-data.frame(buy,op=as.character(rep(&B&,nrow(buy))))
sdata&-rbind(buydf,selldf)
# 交易信号数据
sdata[order(as.Date(row.names(sdata))),]
# 合并交易信号
& sdata&-signal(buydata,selldata)
17.64 17.43721
17.54 17.98709
19.54 19.53222
20.32 20.21389
22.49 22.23619
23.16 23.04056
23.16 23.89947
24.74 24.77656
25.43 25.16284
21.33 25.16284
26.33 26.91247
28.33 28.68482
31.33 31.55239
31.33 31.87960
35.45 35.06983
38.13 38.57817
40.53 40.99130
34.53 40.99130
41.53 41.07764
41.53 41.94564
45.93 45.34946
38.11 45.34946
46.31 46.27199
50.31 50.89829
50.31 50.90283
55.31 55.44277
60.31 60.98705
62.95 62.25497
66.99 66.20413
67.29 67.23573
73.83 73.96157
81.77 81.36000
82.14 82.49000
64.00 82.49000
&/code&&/pre&&/div&&p&接下来,我们利用交易信号数据,进行模拟交易。我们设定交易参数和规则:&/p&&ul&&li&以10万元人民币为本金。&/li&&li&买入信号出现时,以收盘价买入,每次买入价值1万元的股票。如果连续出现买入信号,则一直买入。若现金不足1万元时,则跳过买入信号。&/li&&li&卖出信号出现时,以收盘价卖出,一次性平仓信号对应的股票。&/li&&li&手续费为0元&/li&&/ul&&p&下面我们进行模拟交易。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& # 模拟交易
& trade&-function(sdata,capital=100000,fixMoney=10000){ # 交易信号,总资金,每次定投资金
cash&-capital
ticks&-data.frame()
for(i in 1:nrow(sdata)){
row&-sdata[i,]
if(row$op=='B'){
if(cash&fixMoney){
print(paste(row.names(row),&No enough cash&))
amount0&-floor(fixMoney/row$Value) # 本次交易量
amount&-amount+amount0
cash&-cash-amount0*row$Value
if(row$op=='S'){
cash&-cash+amount*row$Value
row$cash&-round(cash,2)
row$amount&-amount
row$asset&-round(cash+amount*row$Value,2)
ticks&-rbind(ticks,row)
ticks$diff&-c(0,round(diff(ticks$asset),2))
rise&-ticks[intersect(which(ticks$diff&0),which(ticks$op=='S')),]
# 赚钱的交易
fall&-ticks[intersect(which(ticks$diff&0),which(ticks$op=='S')),]
# 赔钱的交易
return(list(
ticks=ticks,
rise=rise,
# 交易结果
& result&-trade(sdata,00)
&/code&&/pre&&/div&&p&来看一下,每笔交易的明细。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& result$ticks
cash amount
17.64 17.43721
17.54 17.98709
19.54 19.53222
20.32 20.21389
22.49 22.23619
23.16 23.04056
23.16 23.89947
24.74 24.77656
25.43 25.16284
21.33 25.16284
26.33 26.91247
28.33 28.68482
31.33 31.55239
31.33 31.87960
35.45 35.06983
38.13 38.57817
40.53 40.99130
34.53 40.99130
41.53 41.07764
41.53 41.94564
45.93 45.34946
38.11 45.34946
46.31 46.27199
50.31 50.89829
50.31 50.90283
55.31 55.44277
60.31 60.98705
62.95 62.25497
66.99 66.20413
67.29 67.23573
73.83 73.96157
81.77 81.36000
64.00 82.49000
&/code&&/pre&&/div&&p&一共发生了34笔交易,其中30笔买入,4笔卖出。最后,资金剩余元,赚了11495元,收益率11.5%。&/p&&h2&3. 模型优化&/h2&&p&我们看到在强势格局的大牛市中,通过追涨能让我们获利颇丰。其实我们可以把模型再进一步优化的,在构建卖出信号时,是以最近10日最低价为卖出点来看,应该还有更好的卖出点可以选择。那么我们就要优化一下模型,比如按下面的优化条件。当股价低于前一个买入点价格的时进行卖出,把小于等于最近10日最低价设为止损点。按照这样的优化策略,我们是不是可以有更大的收益呢?&/p&&p&这样的优化思路,会让我们策略对波动更敏感,更容易被震荡出局;当然好外在于,可以更快的触发止盈和止损条件,牛市中收益更大。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 优化条件,当股价低于前一个买入点价格时进行卖出,小于10日最低价为止损点。
& # 计算卖出的信号点
& sellPoint&-function(ldata,buydata){
for(i in 1:nrow(buydata)){
if(i&1){ # 跳转第一个点
date&-index(buydata[i,])#;print(date)
# 价格 小于 上一次的买入的价格就卖出
last&-as.vector(buydata[i-1,]$Value) # 上一次买入的价格
lst&-ldata[paste(date,&/&,sep=&&)]$Value
idx&-head(which(lst & last),1)
if(length(idx)&0){
arr&-rbind(arr,index(lst[idx]))
selldata&-ldata[as.Date(unique(arr)),]
# 过滤多余的卖出点
bsdata&-merge(buydata$Value,selldata$Value)
names(bsdata)&-c(&buy&,&Value&)
idx1&-which(!is.na(bsdata$Value))
idx2&-idx1[which(c(0,diff(idx1))==1)]
bsdata$Value[idx2]&-NA
return(bsdata$Value[which(!is.na(bsdata$Value))])
# 卖出信号
& selldata&-sellPoint(ldata,buydata)
& selldata
&/code&&/pre&&/div&&p&我们重新生成了,卖出的信号点有7个,比上次多出3个点,画出交易信号的图形。&/p&&figure&&img src=&https://pic4.zhimg.com/v2-65a612c34d50e8b4eb0d7d50af34293f_b.jpg& data-rawwidth=&1056& data-rawheight=&449& class=&origin_image zh-lightbox-thumb& width=&1056& data-original=&https://pic4.zhimg.com/v2-65a612c34d50e8b4eb0d7d50af34293f_r.jpg&&&/figure&&p&合并买卖的交易信号。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&& sdata&-signal(buydata$Value,selldata$Value)
# 合并交易信号
&/code&&/pre&&/div&&p&一共发生了37笔交易,其中30笔买入,7笔卖出。最后,资金剩余元,赚了37483元,收益率37.5%。&/p&&p&我们把卖号信号和止损信号,合并画到一张图上。&/p&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 止损信号
& stopdata&-stopPoint(ldata,buydata)
# 合并买卖信号,止损信号
& bsdata&-merge(buydata$Value,selldata$Value,stopdata$Value)
& names(bsdata)&-c(&buy&,&sell&,&stop&)
& drawPoint(ldata,bsdata,title,sDate,eDate,'1 month') #画图
&/code&&/pre&&/div&&figure&&img src=&https://pic4.zhimg.com/v2-2056bc6bdff9a3dbbccd774fcb9dd721_b.jpg& data-rawwidth=&1047& data-rawheight=&457& class=&origin_image zh-lightbox-thumb& width=&1047& data-original=&https://pic4.zhimg.com/v2-2056bc6bdff9a3dbbccd774fcb9dd721_r.jpg&&&/figure&&p&图中红色点为买点,蓝色点为优化的卖点,紫色点为止损点。从图中可以非常清楚的看到,蓝色卖出点要优于紫色的止损点。这样就达到了,模型优化的目的了。虽然只是一个很小的优化,就可以给我们带来不错的收益。&/p&&p&接下来,通过况客平台,我来够建一个每日更新的交易列表,实现把静态图变成了动态图。&/p&&p&追涨杀跌策略在牛市中会让我们赚取非常大的利润,那么对于2015年下半年行情,牛市已经不复存在,震荡市会一直持续,那么我们可以使用&a href=&https://link.zhihu.com/?target=http%3A//blog.fens.me/finance-mean-reversion/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&均值回归策略,发现逆市中的投资机会&i class=&icon-external&&&/i&&/a&。&/p&&p&最后总结,本文从 追涨杀跌 的思路开始,到市场特征检验,再到数学公式,R语言建模,再到历史数据回测。通过R语言,很简单地就实现了一个我们脑子中的投资想法。类似的投资想法其实谁都有,利用IT人的技术优势,可以真正地与实际操作结合起来。&/p&&p&这样就可以更容易地实现,从IT技术到价值的转变。IT人,加油!&/p&&br&&p&------------------------&/p&&h2&&strong&作者介绍:&/strong&&/h2&&p&张丹,R语言中文社区专栏特邀作者,《R的极客理想》系列图书作者,民生银行大数据中心数据分析师,前况客创始人兼CTO。&/p&&p&10年IT编程背景,精通R ,Java, Nodejs 编程,获得10项SUN及IBM技术认证。丰富的互联网应用开发架构经验,金融大数据专家。个人博客 &a href=&https://link.zhihu.com/?target=http%3A//fens.me/& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&粉丝日志&i class=&icon-external&&&/i&&/a&, Alexa全球排名70k。&/p&&p&著有《R的极客理想-工具篇》、《R的极客理想-高级开发篇》,合著《数据实践之美》,新书《R的极客理想-量化投资篇》(即将出版)。&/p&&figure&&img src=&https://pic2.zhimg.com/v2-b51c6df3ae781e84da9b1ecb_b.jpg& data-rawwidth=&1061& data-rawheight=&256& class=&origin_image zh-lightbox-thumb& width=&1061& data-original=&https://pic2.zhimg.com/v2-b51c6df3ae781e84da9b1ecb_r.jpg&&&/figure&&br&&p&《R的极客理想-工具篇》京东购买快速通道:&a href=&https://link.zhihu.com/?target=https%3A//item.jd.com/.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&《数据分析技术丛书:R的极客理想·工具篇》(张丹 )【摘要 书评 试读】- 京东图书&i class=&icon-external&&&/i&&/a&&br&&/p&&p&《R的极客理想-高级开发篇》京东购买快速通道:&a href=&https://link.zhihu.com/?target=https%3A//item.jd.com/.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&《R的极客理想 高级开发篇》(张丹)【摘要 书评 试读】- 京东图书&i class=&icon-external&&&/i&&/a&&/p&&p&《数据实践之美》京东购买快速通道:&a href=&https://link.zhihu.com/?target=https%3A//item.jd.com/.html& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&《数据实践之美:31位大数据专家的方法、技术与思想》(天善智能)【摘要 书评 试读】- 京东图书&i class=&icon-external&&&/i&&/a&&/p&&p&博客专栏:&a href=&https://link.zhihu.com/?target=https%3A//ask.hellobi.com/blog/fensme& class=& wrap external& target=&_blank& rel=&nofollow noreferrer&&张丹的博客专栏&i class=&icon-external&&&/i&&/a&&/p&&br&&p&&b&大家也可以加小编微信:tswenqu(备注:知乎),进R语言中文社区 交流群,可以跟各位老师互相交流&/b&&/p&&p&&b&官方公众号:R语言中文社区 (ID:R_shequ) 欢迎关注,持续连载。&/b&&/p&
前言久经股市的老股民,通常都会使用一种常见的交易策略,追涨杀跌交易法。追涨杀跌法,是股市操作的一个重要技巧,就是在股市上涨时买入股票,股市下跌时卖出股票。如果操作得当是很好的赢利手段,在中国股市2015年上半年的牛市中,追涨杀跌交易法就是交易…
&figure&&img src=&https://pic3.zhimg.com/v2-1cfddbdb897e_b.jpg& data-rawwidth=&600& data-rawheight=&254& class=&origin_image zh-lightbox-thumb& width=&600& data-original=&https://pic3.zhimg.com/v2-1cfddbdb897e_r.jpg&&&/figure&&figure&&img src=&https://pic3.zhimg.com/v2-15e6cd21afd11b47f665_b.jpg& data-rawwidth=&601& data-rawheight=&397& class=&origin_image zh-lightbox-thumb& width=&601& data-original=&https://pic3.zhimg.com/v2-15e6cd21afd11b47f665_r.jpg&&&/figure&&h2&&b&概述&/b&&/h2&&p&和Python计算环境中的tushare包一样,在R中我们使用quantmod包接入第三方数据源,实现自定义量化分析平台的构建。&/p&&p&本文打算以陌陌的股票分析为背景,介绍如何通过quantmod包构建专属的量化分析平台。&/p&&h3&什么是quantmod&/h3&&p&quantmod就是提供给宽客们使用的专业模块,Quantmod本身提供强大的数据接入能力,默认是雅虎财经的数据源,此外quantmod还以绘制专业的行情分析图表以及各种技术指标计算等功能著称,常常只要几行函数就能完成从数据获取和处理到画图的复杂功能,其工作效率之高让行家里手都觉得膛目结舌。&/p&&figure&&img src=&https://pic3.zhimg.com/v2-7eba9e33f4e1b77f846057_b.jpg& data-rawwidth=&580& data-rawheight=&513& class=&origin_image zh-lightbox-thumb& width=&580& data-original=&https://pic3.zhimg.com/v2-7eba9e33f4e1b77f846057_r.jpg&&&/figure&&h2&&b&利用API读取在线行情&/b&&br&&/h2&&p&首先,我们利用雅虎财经的默认接口直接体验一下读取多只股票。&/p&&h3&原理&/h3&&p&利用API读取的方式,我们需要设定一个读取序列和对应的配置,获取行情函数getSymbols类似于原生的assign和get函数,用函数的方式将变量名传入后完成变量的赋值。&/p&&p&基于这个原理,我写了一个Quote函数来优化参数配置的体验。首先我们需要定义一个股票池序列,然后调用Quote函数获取某只股票的行情返回数据。&/p&&p&下面以美股的陌陌、360和A股的平安银行为例:&/p&&h3&代码&/h3&&h3&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 加载quantmod包
if(!require(quantmod)){
install.packages(&quantmod&)
# 股票行情匹配函数
Quote = function(code){
index = match(code,universes)
temp = lapply(universes,get)
return(temp[[index]])
# 基本配置
universes &&- c(&000001.SZ&,&QIHU&,&MOMO&)
to = Sys.Date() # 结束时间设为当前日期
src= &yahoo& # 来源雅虎财经
# 行情加载 速度有点慢,耐心等待
quantmod::getSymbols(universes,from=from,to=to,src=src)
# 绘制行情
quantmod::chartSeries(Quote(&MOMO&),up.col='red',dn.col='green',TA=&addVo(); addADX();addMACD(); addSMA(n=10);addBBands(n=14,sd=2,draw=\&bands\&)&)
&/code&&/pre&&/div&&/h3&&figure&&img src=&https://pic1.zhimg.com/v2-80fd3def46_b.jpg& data-rawwidth=&596& data-rawheight=&431& class=&origin_image zh-lightbox-thumb& width=&596& data-original=&https://pic1.zhimg.com/v2-80fd3def46_r.jpg&&&/figure&&h2&&b&利用CSV读取离线行情&/b&&br&&/h2&&p&接着,在离线模式或者网络访问缓慢的情况下,我们也可以用一些实现准备好的CSV文件来读取行情。&/p&&br&&h3&原理&/h3&&p&分析底层数据结构后,我们知道quantmod包读取后的数据格式是 xts 和 zoo,我们只需要将csv文件按一定的格式读取到内存后再进行相应变换,quantmod强大的分析和作图能力就可以为我们所用。&/p&&p&zoo本身是一种时间序列格式,而xts则是在这基础上一种时间序列格式的加强版。在读取csv的时候,我们需要用首行确定header。在转化为zoo时,我们则需要首列来确定时间序列对应的时间。最后通过xts转化为可以被quantmod识别的xts时间序列对象。下面以平安银行为例:&/p&&h3&代码&/h3&&h3&&div class=&highlight&&&pre&&code class=&language-text&&&span&&/span&# 加载 zoo 时间序列包
library(zoo)
library(quantmod)
# 配置文件路径
filePath = '/Users/harryzhu/temp.csv'
# 读取CSV并转化时间格式
csv &- read.csv(filePath,header=TRUE,sep=&,&)
csv$LZ_GPA_QUOTE_TCLOSE &- as.POSIXct(as.character(csv$LZ_GPA_QUOTE_TCLOSE),tz=&&,format=&%Y%m%d&)
# 转化为zoo类型
temp = read.zoo(csv)
# 转化我xts类型
payh =as.xts(temp[,1]);colnames(payh)=&Close&
chartSeries(payh,name=&000001.SZ&)
# 添加MACD曲线
&/code&&/pre&&/div&&strong&效果&/strong&&/h3&&figure&&img src=&https://pic4.zhimg.com/v2-c94a63e43eda3bb2c18280_b.jpg& data-rawwidth=&602& data-rawheight=&452& class=&origin_image zh-lightbox-thumb& width=&602& data-original=&https://pic4.zhimg.com/v2-c94a63e43eda3bb2c18280_r.jpg&&&/figure&&h3&&strong&指标计算&/strong&&/h3&&p&参考官方文档,我们知道,利用quantmod和TTR包,我们可以快速计算常见指标,下面是对应的计算列表。&/p&&figure&&img src=&https://pic1.zhimg.com/v2-25dd24c495b9159ecce4_b.jpg& data-rawwidth=&575& data-rawheight=&599& class=&origin_image zh-lightbox-thumb& width=&575& data-original=&https://pic1.zhimg.com/v2-25dd24c495b9159ecce4_r.jpg&&&/figure&&h3&&strong&Web应用构建&/strong&&/h3&&p&参考 Rich Harken大神 制作的 shiny app以及源码,我们可以将上述参数暴露为网页上的选项,利用shiny的ajax和websocket的实时链接特性定制我们的chartSeries函数,达到通过选项实时作图的功能。&/p&&h3&&strong&效果图&/strong&&/h3&&figure&&img src=&https://pic4.zhimg.com/v2-0eadee8d50ec5b769ccf506_b.jpg& data-rawwidth=&598& data-rawheight=&339& class=&origin_image zh-lightbox-thumb& width=&598& data-original=&https://pic4.zhimg.com/v2-0eadee8d50ec5b769ccf506_r.jpg&&&/figure&&p&&strong&尾注&/strong&&/p&&p&综上所述,我们可以发现,利用quantmod、shiny包,我们可以快速实现各种姿势的行情获取以及常见的关键指标的计算和绘制,并且转化为实时的Web应用,建立一个专属的量化分析Web平台。&/p&&br&&p&&strong&参考资料&/strong&&/p&&p&quantmod官方文档&/p&&p&Rich Harken: R quantmod Demonstration for Data Products Class&/p&&p&Shiny Tutorial:Use reactive expressions&/p&&p&大家也可以加小编微信:tswenqu,进R语言交流群。&/p&
概述和Python计算环境中的tushare包一样,在R中我们使用quantmod包接入第三方数据源,实现自定义量化分析平台的构建。本文打算以陌陌的股票分析为背景,介绍如何通过quantmod包构建专属的量化分析平台。什么是quantmodquantmod就是提供给宽客们使用的专业模…
&figure&&img src=&https://pic3.zhimg.com/v2-1cfddbdb897e_b.jpg& data-rawwidth=&600& data-rawheight=&254& class=&origin_image zh-lightbox-thumb& width=&600& data-original=&https:

我要回帖

更多关于 laplace先验 的文章

 

随机推荐