本帖最后由 qinth 于 2012-4-29 07:44 编辑
实在是没有办法 求助各位大大
这本是我一个朋友的东西 他生病了
可是我看了半天也不了解这门语言
需要在写好的代码里面加一个函数 需要怎么加啊!
好像是在一个金融模型里面 添加一个止损函数
可是给的例子是一个数列的 数据库是一个数组的~
例子他都给我了,可是我不会~
求助各位大大~- # FOR A GENERAL EXPLANATION OF REQUIREMENTS ON getNewPosList see rsi.R
- # This strategy only trades on certain markets, which is encoded in params$series.
- # The strategy will be long (short) on contract whenever the close is below (above)
- # the lower (upper) Bollinger Band of the close.
- getNewPosList <- function(store, newRowList, params) {
- if (is.null(store))
- store <- initStore(newRowList,params$series)
- else
- store <- updateStore(store, newRowList, params$series)
-
- pos <- rep(0,length(newRowList))
- if (store$iter > params$lookback) {
- for (i in 1:length(params$series)) {
- cl <- newRowList[[params$series[i]]]$Close
- bbands <- BBands(store$cl[[i]],n=params$lookback,sd=params$sdParam)
- dn <- last(bbands$dn)
- up <- last(bbands$up)
- #cat("cl",cl,"dn",dn,"up",up,"\n")
- if (cl < dn) {
- pos[params$series[i]] <- 1
- }
- else if (cl > up) {
- pos[params$series[i]] <- -1
- }
- }
- }
- return(list(store=store,pos=pos))
- }
- initClStore <- function(newRowList,series) {
- return(lapply(series, function(x) newRowList[[x]]$Close))
- }
- updateClStore <- function(oldClStore, newRowList, series) {
- return(mapply(function(x,y) rbind(oldClStore[[x]],newRowList[[y]]$Close),
- 1:length(series),series, SIMPLIFY=FALSE))
- }
- initStore <- function(newRowList,series) {
- return(list(iter=1,cl=initClStore(newRowList,series)))
- }
- updateStore <- function(store, newRowList, series) {
- store$iter <- store$iter + 1
- store$cl <- updateClStore(store$cl,newRowList,series)
- return(store)
- }
复制代码 这是源代码~
要加进去的代码是这样的- run <- function(prices,n,sd,stoploss) { # stoploss is a simple return
- bbands <- BBands(prices[,"Open"],n=n,sd=sd)
- bbands <- lag(bbands)
- pos <- vector(mode="numeric",length=nrow(prices)) # all zeroes
- for (i in (n+1):nrow(prices)) {
- if (pos[i-1]==flat) {
- long <- ifelse(prices[i,"Open"]<bbands$dn,1,0)
- short <- ifelse(prices[i,"Open"]>bbands$up,-1,0)
- pos[i] <- long + short
- if (pos[i] != pos[i-1]) # we just entered a trade
- entry <- i # how long we have been in a trade
- } else if (getTradeReturn(prices,entry,exit=i,isTRUE(pos[i]<0)) > -stoploss) {
- pos[i] <- pos[i-1] # stay in trade
- }
- }
- return(pos)
- }
复制代码 |