├── README ├── gitStats ├── getstats.sh └── gitStats.R ├── HFD ├── README └── showHFD.R ├── various └── patriotas.R ├── 3_10_days_vol.R ├── politika ├── partijos.R └── savivaldybes.csv ├── kmeans └── kmeans.R ├── spread └── seasonal_spread.R ├── volatility ├── 2_high_days.R └── vix_futures.R ├── 3lowDays.R ├── omx └── corr.R ├── performance └── performance.R └── tradeCostAnalysis └── tradeCostAnalysis.R /README: -------------------------------------------------------------------------------- 1 | This project contains R-language source code for various data mining and statistical analysis projects. The descriptions of the problems can be found on www.investuotojas.eu 2 | -------------------------------------------------------------------------------- /gitStats/getstats.sh: -------------------------------------------------------------------------------- 1 | git log master --shortstat --pretty="format: %ai"|sed -e 's/\+[0-9]*/,/g'|sed ':a;N;$!ba;s/ ,\n/,/g'|sed 's/ files changed//g'|sed 's/ insertions(,)//g'|sed 's/ deletions(-)//g' >gitstats.csv 2 | -------------------------------------------------------------------------------- /HFD/README: -------------------------------------------------------------------------------- 1 | This script loads data from mongodb and plots some parts of the data. This should give you better intuition on collected data 2 | You can find more information following this link: 3 | http://www.investuotojas.eu/2012/03/01/i-see-high-frequency-data/ 4 | -------------------------------------------------------------------------------- /various/patriotas.R: -------------------------------------------------------------------------------- 1 | # result: http://dl.dropbox.com/u/6360678/Rproject_data/patriotai.png 2 | #@Autor Dzidorius Martinaitis 3 | #@Date 2011-03-21 4 | library(RColorBrewer) 5 | library(sp) 6 | #http://gadm.org/data/rda/LTU_adm1.RData 7 | #getData("GADM",country='LTU',level=2)#<-doesn't work on my machine 8 | load(file='~/tickers/LTU_adm2.RData') 9 | 10 | patriotas<-tail(read.table('http://dl.dropbox.com/u/6360678/Rproject_data/patriotas.csv',sep=',',header=T),-1) 11 | head(patriotas) 12 | factor<-as.factor(cut(as.numeric(sub(',','.',patriotas$X)),c(30,40,50,60,70))) 13 | 14 | gadm$col_no<-factor 15 | 16 | png('patriotai.png',width=500) 17 | spplot(gadm, "col_no", col=grey(.9), col.regions=brewer.pal(4,"Purples"),main='Patriotai Lietuvoje') 18 | dev.off() -------------------------------------------------------------------------------- /3_10_days_vol.R: -------------------------------------------------------------------------------- 1 | require('xts') 2 | require('quantmod') 3 | Sys.setenv(TZ="GMT") 4 | 5 | getSymbols(c('SPY','^VIX'),from='1995-01-01') 6 | 7 | spy.delta<-Delt(Cl(SPY)) 8 | 9 | short.vol<-as.xts(rollapply(spy.delta,3,sd,align='right')) 10 | long.vol<-as.xts(rollapply(spy.delta,10,sd,align='right')) 11 | 12 | future.vol<-(head(lag(short.vol,-3),-3)) 13 | 14 | past.vol<-short.vol/long.vol 15 | 16 | signal<-index(past.vol[past.vol<0.25])#ifelse(past.vol<0.3,1,0) 17 | 18 | 19 | 20 | temp<-cbind(future.vol,short.vol) 21 | temp<-(tail(temp,-1)) 22 | temp<-(head(temp,-3)) 23 | 24 | print('all days:') 25 | summary(as.double(temp[,1])/as.double(temp[,2])) 26 | 27 | print('days, then past volatility < 0.25:') 28 | summary(as.double(temp[,1][signal])/as.double(temp[,2][signal])) 29 | 30 | -------------------------------------------------------------------------------- /gitStats/gitStats.R: -------------------------------------------------------------------------------- 1 | #Author: Dzidorius Martinaitis 2 | #Date: 2011-07-13 3 | #Description: http://www.investuotojas.eu/2011/07/13/plotting-git-statistics/ 4 | 5 | require(ggplot2) 6 | require(xts) 7 | setwd('/home/git/Rproject/gitStats/') 8 | Sys.setenv(TZ="GMT") 9 | tmp=as.matrix(read.table('gitstats.csv',sep=',',header=FALSE)) 10 | commits=xts(cbind(as.double(tmp[,2]),as.double(tmp[,3]),as.double(tmp[,4])),order.by=as.POSIXct(strptime(tmp[,1],'%Y-%m-%d %H:%M:%S'))) 11 | 12 | colnames(commits)=c('Changes','Insertion','Deletion') 13 | tmp=data.frame(Date=as.Date(index(commits)),Changes=as.numeric(commits$Changes),Insertion=as.numeric(commits$Insertion),Deletion=as.numeric(commits$Deletion)) 14 | tmp=melt(tmp,id.vars=c('Date')) 15 | png('gitStats.png',width=500) 16 | print(ggplot(tmp,aes(Date,value,color=variable))+geom_jitter(alpha=.65,size=3)) 17 | dev.off() 18 | 19 | #############daily aggregated data############## 20 | factor=as.factor(format(index(commits),'%Y%m%d')) 21 | tmp=cbind(as.numeric(aggregate(commits$Changes,factor,sum)),as.numeric(aggregate(commits$Insertion,factor,sum)),as.numeric(aggregate(commits$Deletion,factor,sum))) 22 | tmp=data.frame(unique(as.Date(index(commits))),tmp) 23 | colnames(tmp)=c('Date','Changes','Insertion','Deletion') 24 | tmp=melt(tmp,id.vars=c('Date')) 25 | png('gitStats2.png',width=500) 26 | print(ggplot(tmp,aes(Date,value,color=variable))+geom_jitter(alpha=.65,size=3)) 27 | dev.off() -------------------------------------------------------------------------------- /politika/partijos.R: -------------------------------------------------------------------------------- 1 | #Author: Dzidorius Martinaitis 2 | #Date: 2011-04-4 3 | #Description: http://www.investuotojas.eu/?p=471 4 | require('ggplot2') 5 | 6 | setwd('/home/git/Rproject/politika/') 7 | partijos<-(read.table('savivaldybes.csv',header=TRUE,sep=',')) 8 | 9 | png('log_gyventojai_islaidos.png',width=650) 10 | ggplot(partijos,aes(log(Gyventoju.skaicius),Islaidos))+geom_point(col='red',alpha=0.5,size=4)+geom_smooth()+ylab('Išlaidos')+xlab('Gyventojų sk. log. skalėje') 11 | dev.off() 12 | 13 | rez1<-droplevels(subset(partijos,partijos$Partija!='')) 14 | levels(rez1$Partija)<-c("Dešinė","Centras","Dešinė","Kairė","Kairė","Centras","Centras","Dešinė","Centras") 15 | 16 | png('kaire_desine_sk.png',width=650) 17 | ggplot(rez1,aes(Partija,Gyventoju.skaicius,fill=Partija))+geom_bar(stat = "identity",alpha=0.9)+ scale_fill_manual(value=c("blue3","white","red3"))+opts(legend.position = "none")+ ylab('Gyventojų skaičius')+xlab('') 18 | dev.off() 19 | 20 | 21 | rez<-aggregate(partijos,list(partijos$Partija),length)[,1:2] 22 | rez1<-subset(partijos,(partijos$Partija)%in% (rez[,1][rez[,2]>1])) 23 | rez1<-droplevels(rez1) 24 | 25 | png('gyv_sk_sum.png',width=650) 26 | ggplot(rez1,aes(Partija,Gyventoju.skaicius,fill=Partija))+geom_bar(stat = "identity")+ylab('Gyventojų skaičius') 27 | dev.off() 28 | 29 | png('gyv_sk_taskai.png',width=650) 30 | ggplot(rez1,aes(Partija,Gyventoju.skaicius/100000,col=Partija))+geom_jitter(size=4)+ylab('Gyventojų skaičius tūkst.') 31 | dev.off() 32 | 33 | png('islaidos_partijos.png',width=650) 34 | ggplot(rez1,aes(Partija,Islaidos,col=Partija))+geom_jitter(size=4)+stat_summary(fun.y='mean',ymin=mean(rez1$Islaidos),ymax=mean(rez1$Islaidos),color='black',size=1.2) 35 | dev.off() 36 | 37 | png('islaidos_density.png',width=650) 38 | ggplot(partijos,aes(Islaidos))+geom_density(col='blue4',fill='steelblue',size=1.2)+xlab('Išlaidos') 39 | dev.off() 40 | -------------------------------------------------------------------------------- /kmeans/kmeans.R: -------------------------------------------------------------------------------- 1 | #Author Dzidorius Martinaitis 2 | #Date 2011-07-06 3 | #Description http://www.investuotojas.eu/?p=500 4 | 5 | setwd('/home/git/Rproject/kmeans/') 6 | require(quantmod) 7 | require(ggplot2) 8 | Sys.setenv(TZ="GMT") 9 | getSymbols('SPY',from='2000-01-01') 10 | 11 | 12 | x=data.frame(d=index(Cl(SPY)),return=as.numeric(Delt(Cl(SPY)))) 13 | png('daily_density.png',width=500) 14 | ggplot(x,aes(return))+stat_density(colour="steelblue", size=2, fill=NA)+xlab(label='Daily returns') 15 | dev.off() 16 | 17 | nasa=tail(cbind(Delt(Op(SPY),Hi(SPY)),Delt(Op(SPY),Lo(SPY)),Delt(Op(SPY),Cl(SPY))),-1) 18 | 19 | ###################if you want uniform distribution - uncomment the following lines############## 20 | #rez=apply( 21 | # (nasa),2,function(x){ 22 | # y=(xts(x,order.by=as.POSIXct(as.Date(attr(x,'names'))))) 23 | # 24 | # print(xts(rollapply(y,20,function(z){which(order(z)==20)/20},align='right'))) 25 | # } 26 | #) 27 | #nasa=xts(rez,order.by=as.POSIXct(tail(index(nasa),-19))) 28 | #colnames(nasa)=c('High','Low','Close') 29 | #######################uniform distribution END############################## 30 | 31 | #optimal number of clusters 32 | wss = (nrow(nasa)-1)*sum(apply(nasa,2,var)) 33 | for (i in 2:15) wss[i] = sum(kmeans(nasa, centers=i)$withinss) 34 | wss=(data.frame(number=1:15,value=as.numeric(wss))) 35 | 36 | png('numberOfClusters.png',width=500) 37 | ggplot(wss,aes(number,value))+geom_point()+ 38 | xlab("Number of Clusters")+ylab("Within groups sum of squares")+geom_smooth() 39 | dev.off() 40 | 41 | kmeanObject=kmeans(nasa,5,iter.max=10) 42 | kmeanObject$centers 43 | autocorrelation=head(cbind(kmeanObject$cluster,lag(as.xts(kmeanObject$cluster),-1)),-1) 44 | xtabs(~autocorrelation[,1]+(autocorrelation[,2])) 45 | 46 | y=apply(xtabs(~autocorrelation[,1]+(autocorrelation[,2])),1,sum) 47 | x=xtabs(~autocorrelation[,1]+(autocorrelation[,2])) 48 | z=x 49 | for(i in 1:5) 50 | { 51 | z[i,]=(x[i,]/y[i]) 52 | } 53 | round(z,2) 54 | 55 | -------------------------------------------------------------------------------- /spread/seasonal_spread.R: -------------------------------------------------------------------------------- 1 | #Author: Dzidorius Martinaitis 2 | #Date: 2011-01-11 3 | #Description: http://www.investuotojas.eu/?p=447 4 | 5 | require('xts') 6 | require('quantmod') 7 | Sys.setenv(TZ="GMT") 8 | 9 | require('PerformanceAnalytics') 10 | 11 | tmp<-as.matrix(read.table('tickers/various_day_close/rb_contract1.csv',sep=',',header=FALSE)) 12 | rb<-as.xts(as.double(tmp[,2]),order.by=as.POSIXct(strptime(tmp[,1],'%Y-%m-%d'))) 13 | 14 | rb<-tail(rb,-3)['::2010-11'] 15 | 16 | 17 | tmp<-as.matrix(read.table('tickers/various_day_close/cl_contract1.csv',sep=',',header=FALSE)) 18 | cl<-as.xts(as.double(tmp[,2]),order.by=as.POSIXct(strptime(tmp[,1],'%Y-%m-%d'))) 19 | cl<-tail(cl,-3)['::2010-11'] 20 | 21 | 22 | rb.delta<-Delt(((rb)))['1997-01::'] 23 | cl.delta<-Delt(((cl)))['1997-01::'] 24 | 25 | rb.delta[is.na(rb.delta)]<-0 26 | cl.delta[is.na(cl.delta)]<-0 27 | 28 | spread<-cl.delta*50000-rb.delta*50000 29 | 30 | png('spread_cl_prices.png',width=650) 31 | chart.CumReturns(cbind(cl.delta,rb.delta),col=c(2,3),main='Oil & Gasoline prices') 32 | dev.off() 33 | 34 | png('spread_cl_rb.png',width=650) 35 | chart.TimeSeries(cumsum(spread),main='Seasonal spread: CL vs RB') 36 | dev.off() 37 | 38 | spread<-cl.delta-rb.delta 39 | 40 | png('spread_cl_rb_prc.png',width=650) 41 | chart.CumReturns((spread),main='Seasonal spread %: CL vs RB') 42 | dev.off() 43 | 44 | spread.factor<-as.factor(format(index(spread),'%m')) 45 | aggregate(spread, spread.factor,mean) 46 | summary(lm(as.double(spread)~(spread.factor))) 47 | 48 | 49 | 50 | rb.delta.monthly<-Delt(Cl(to.monthly(rb,indexAt='endof')))['1997-01::'] 51 | cl.delta.monthly<-Delt(Cl(to.monthly(cl,indexAt='endof')))['1997-01::'] 52 | 53 | rb.delta.monthly[is.na(rb.delta.monthly)]<-0 54 | cl.delta.monthly[is.na(cl.delta.monthly)]<-0 55 | 56 | factor<-as.factor(format(index(cl.delta.monthly-rb.delta.monthly),'%m')) 57 | tmp<-data.frame(as.double(cl.delta.monthly-rb.delta.monthly),as.numeric(factor)) 58 | 59 | require('ggplot2') 60 | png('monthly_averages.png',width=650) 61 | qplot(factor(as.numeric(factor)),as.double(cl.delta.monthly-rb.delta.monthly),data=tmp,geom = "boxplot",ylab='Monthly average returns',xlab='Months') 62 | dev.off() 63 | 64 | png('march_cumulative.png',width=650) 65 | chart.CumReturns(spread[spread.factor=='03'],main='March cumulative return') 66 | dev.off() 67 | 68 | png('yearly_diff.png',width=650) 69 | chart.TimeSeries(cbind(as.xts(rollapply(rb.delta,250,sd,align='right'))-as.xts(rollapply(cl.delta,250,sd,align='right'))),main='Yearly difference of vol. between CL & RB') 70 | dev.off() -------------------------------------------------------------------------------- /volatility/2_high_days.R: -------------------------------------------------------------------------------- 1 | #If during the last two days VIX return was above 6%, then there is high probability, that return of S&P500 index will be positive on third day 2 | #author Dzidorius Martinaitis 3 | #2010-12-29 4 | # http://www.investuotojas.eu/?p=439 5 | require('xts') 6 | require('quantmod') 7 | require('blotter') 8 | require('PerformanceAnalytics') 9 | require('FinancialInstrument') 10 | Sys.setenv(TZ="GMT") 11 | 12 | #data part 13 | getSymbols(c('SPY','^VIX'),from='1995-01-01',index.class=c("POSIXt","POSIXct")) 14 | dividends<-getDividends('SPY',from='1995-01-01',index.class=c("POSIXt","POSIXct")) 15 | 16 | temp<-cbind(dividends,SPY) 17 | temp[,1][is.na(temp[,1])]<-0 18 | 19 | SPY<-cbind(temp[,2],temp[,3],temp[,4],temp[,1]+temp[,5]) 20 | colnames(SPY)<-c('Open','High','Low','Close') 21 | spy.delta<-Delt(Cl(SPY)) 22 | 23 | vix.delta<-Delt(Cl(VIX)) 24 | 25 | signal<-ifelse(vix.delta>0.06& lag(vix.delta>0.06,1),1,0) 26 | png('2highdays.png',width=650) 27 | chart.CumReturns(lag(signal,1)*spy.delta,main='when VIX >6% during two days') 28 | dev.off() 29 | 30 | #blotter code 31 | symbols<-c('SPY') 32 | SPY<-Cl(SPY) 33 | initDate=time(get(symbols)[1]) 34 | initEq=50000 35 | rm(list=ls(envir=.blotter),envir=.blotter) 36 | ltportfolio='2high' 37 | ltaccount='2high' 38 | initPortf(ltportfolio,symbols, initDate=initDate) 39 | initAcct(ltaccount,portfolios=c(ltportfolio), initDate=initDate,initEq=initEq) 40 | currency("USD") 41 | stock(symbols[1],currency="USD",multiplier=1) 42 | 43 | signal[is.na(signal)]<-0 44 | 45 | 46 | for(i in 2:length(signal)) 47 | { 48 | currentDate= time(signal)[i] 49 | equity = initEq #getEndEq(ltaccount, currentDate) 50 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 51 | print(position) 52 | print(currentDate) 53 | if(position==0) 54 | { 55 | #open a new position if signal is >0 56 | if(signal[i]>0 ) 57 | { 58 | print('open position') 59 | closePrice<-as.double(Cl(SPY[currentDate])) 60 | print(closePrice) 61 | unitSize = as.numeric(trunc((equity/closePrice))) 62 | print(unitSize) 63 | commssions=-unitSize*closePrice*0.0003 64 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = unitSize , TxnFees=commssions, verbose=T) 65 | 66 | } 67 | 68 | } 69 | else 70 | { 71 | #position is open. If signal is 0 - close it. 72 | if(position>0 &signal[i] ==0) 73 | { 74 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 75 | closePrice<-as.double((Cl(SPY[currentDate])))#as.double(get(symbols[1])[i+100]) 76 | commssions=-position*closePrice*0.0003 77 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = -position , TxnFees=commssions, verbose=T) 78 | 79 | } 80 | 81 | } 82 | updatePortf(ltportfolio, Dates = currentDate) 83 | updateAcct(ltaccount, Dates = currentDate) 84 | updateEndEq(ltaccount, Dates = currentDate) 85 | } 86 | rez1<-(getPortfolio(ltaccount)) 87 | png('2highdays_2.png',width=650) 88 | chart.CumReturns(rez1$symbols$SPY$txn[,7]/initEq) 89 | dev.off() 90 | -------------------------------------------------------------------------------- /3lowDays.R: -------------------------------------------------------------------------------- 1 | #Description: http://www.investuotojas.eu/?p=409 2 | # author: Dzidorius Martinaitis 3 | 4 | require('xts') 5 | require('quantmod') 6 | require('blotter') 7 | require('PerformanceAnalytics') 8 | require('FinancialInstrument') 9 | Sys.setenv(TZ="GMT") 10 | 11 | getSymbols('SPY',from='1995-01-01',index.class=c("POSIXt","POSIXct")) 12 | dividends<-getDividends('SPY',from='1995-01-01',index.class=c("POSIXt","POSIXct")) 13 | 14 | temp<-cbind(dividends,SPY) 15 | temp[,1][is.na(temp[,1])]<-0 16 | 17 | SPY<-cbind(temp[,2],temp[,3],temp[,4],temp[,1]+temp[,5]) 18 | colnames(SPY)<-c('Open','High','Low','Close') 19 | 20 | #one day before 21 | lag1<-lag((SPY),1) 22 | 23 | #two days defore 24 | lag2<-lag((SPY),2) 25 | 26 | signal<-ifelse( (Cl(lag2)>Cl(lag1) & Cl(lag1)>Cl(SPY))& 27 | (Hi(lag2)>Hi(lag1) & Hi(lag1)>Hi(SPY)) & 28 | (Op(lag2)>Op(lag1) & Op(lag1)>Op(SPY)), 29 | 1,0 30 | ) 31 | #one day later 32 | lag3<-lag(Cl(SPY),-1) 33 | 34 | 35 | profit<-(lag3/Cl(SPY)-1)*signal 36 | chart.CumReturns(profit) 37 | 38 | #------------------ 39 | tmp<-(Hi(lag2)/Lo(SPY)-1)*signal 40 | 41 | #blotter code 42 | symbols<-c('SPY') 43 | SPY<-Cl(SPY) 44 | initDate=time(get(symbols)[1]) 45 | initEq=10000 46 | rm(list=ls(envir=.blotter),envir=.blotter) 47 | ltportfolio='3days' 48 | ltaccount='3days' 49 | initPortf(ltportfolio,symbols, initDate=initDate) 50 | initAcct(ltaccount,portfolios=c(ltportfolio), initDate=initDate,initEq=initEq) 51 | currency("USD") 52 | stock(symbol,currency="USD",multiplier=1) 53 | 54 | signal[is.na(signal)]<-0 55 | 56 | 57 | counter<-0 58 | 59 | for(i in 2:length(signal)) 60 | { 61 | currentDate= time(signal)[i] 62 | equity = 10000 #getEndEq(ltaccount, currentDate) 63 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 64 | print(position) 65 | print(currentDate) 66 | if(position==0) 67 | { 68 | #open a new position if signal is >0 69 | if(signal[i]>0 &counter ==0) 70 | { 71 | print('open position') 72 | closePrice<-as.double(Cl(SPY[currentDate])) 73 | print(closePrice) 74 | unitSize = as.numeric(trunc((equity/closePrice))) 75 | print(unitSize) 76 | commssions=-unitSize*closePrice*0.0003 77 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = unitSize , TxnFees=commssions, verbose=T) 78 | counter<-1 79 | } 80 | 81 | } 82 | else 83 | { 84 | #position is open. If signal is 0 - close it. 85 | if(position>0 &counter>=1) 86 | { 87 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 88 | closePrice<-as.double((Cl(SPY[currentDate])))#as.double(get(symbols[1])[i+100]) 89 | commssions=-position*closePrice*0.0003 90 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = -position , TxnFees=commssions, verbose=T) 91 | counter<-0 92 | } 93 | else 94 | { 95 | print(counter) 96 | counter<-counter+1 97 | } 98 | } 99 | updatePortf(ltportfolio, Dates = currentDate) 100 | updateAcct(ltaccount, Dates = currentDate) 101 | updateEndEq(ltaccount, Dates = currentDate) 102 | } 103 | rez1<-(getPortfolio(ltaccount)) 104 | plot(cumsum(rez1$symbols$SPY$txn[,9])) 105 | 106 | #gross profit 107 | result<-rez1$symbols$SPY$txn[,7] 108 | result<-result[result!=0] 109 | 110 | #fix commission rate 2*3 111 | plot(cumsum(result-6)) 112 | 113 | chart.CumReturns(cbind((result)/10000,(result-6)/10000)) 114 | 115 | -------------------------------------------------------------------------------- /omx/corr.R: -------------------------------------------------------------------------------- 1 | #@Author: Dzidorius Martinaitis 2 | #@Date: 2011-03-22 3 | #@Description: http://www.investuotojas.eu/?p=464 4 | 5 | require(xts) 6 | require(quantmod) 7 | loadOMX<-function(path, name) 8 | { 9 | 10 | filename<-paste(path,sep='') 11 | print(filename) 12 | temp<-as.matrix(read.table(file=filename,sep=',',quote = "",header=TRUE)) 13 | 14 | #result[counter]<-temp 15 | graph<-as.POSIXct(as.Date(temp[,3],'%Y%m%d'),tz='GMT') 16 | tempxts<-xts(as.double(temp[,8]),order.by=graph) 17 | 18 | tempxts<-tempxts[!is.na(tempxts)] 19 | 20 | colnames(tempxts)<-c('Close') 21 | 22 | if(length(name)>0) 23 | { 24 | print(name) 25 | assign(name, tempxts,envir = .GlobalEnv) 26 | } 27 | #print(tail(tempxts)) 28 | return(tempxts) 29 | 30 | } 31 | mergeData<-function(tickers) 32 | { 33 | mergedList<-'' 34 | #print(length(tickers)) 35 | for (counter in 1:length(tickers)) 36 | { 37 | print(tickers[counter]) 38 | if(counter == 1) 39 | { 40 | mergedList=Cl(get(tickers[counter])) 41 | } else 42 | { 43 | mergedList=cbind(mergedList,Cl(get(tickers[counter]))) 44 | } 45 | } 46 | 47 | #colnames(mergedList)<-tickers 48 | return(mergedList) 49 | } 50 | 51 | tickers<-c('TEO1L', 'IVL1L','APG1L','SRS1L','UKB1L', 'SAB1L','LDJ1L','GRG1L','KNF1L','CTS1L', 52 | 'RSU1L','PZV1L','DKR1L','KBL1L','STU1L','SNG1L','UTR1L','VBL1L','SAN1L','PTR1L','LFO1L') 53 | 54 | for (counter in 1:length(tickers)) 55 | { 56 | # print(tickers[counter]) 57 | loadOMX(paste('~/tickers/qoutes/',tickers[counter],'.txt',sep=''),tickers[counter]) 58 | } 59 | 60 | #merge all tickers into one 61 | tmp<-mergeData(tickers) 62 | colnames(tmp)<-(tickers) 63 | 64 | 65 | cor_mat<-matrix(ncol=NCOL(tmp),nrow=NCOL(tmp)) 66 | colnames(cor_mat)<-tickers 67 | rownames(cor_mat)<-tickers 68 | 69 | for (i in 1:NCOL(tmp)) 70 | { 71 | for (y in 1:NCOL(tmp)) 72 | { 73 | if(i!=y) 74 | { 75 | cor_mat[i,y]<-cor(tail(tail(na.locf(tmp[,i])['2010::']/lag(na.locf(tmp[,i])['2010::'],1)-1,-1),60),tail(tail(na.locf(tmp[,y])['2010::']/lag(na.locf(tmp[,y])['2010::'],1)-1,-1),60)) 76 | } 77 | else 78 | { 79 | cor_mat[i,y]<-0 80 | } 81 | } 82 | } 83 | 84 | require(igraph) 85 | #cor_mat<- matrix( runif(100), nr=10 ) 86 | cor_mat[ lower.tri(cor_mat, diag=TRUE) ]<- 0 87 | cor_mat[ abs(cor_mat) < 0.5] <- 0 88 | 89 | graph <- graph.adjacency(cor_mat>0.5, weighted=TRUE, mode="upper") 90 | E(graph)$weight<-t(cor_mat)[abs(t(cor_mat))>0.5] 91 | E(graph)[ weight>0.7 ]$color <- "black" 92 | E(graph)[ weight>=0.65 & weight<0.7 ]$color <- "red" 93 | E(graph)[ weight>=0.6 &weight<0.65 ]$color <- "green" 94 | E(graph)[ weight>=0.55 &weight<0.6 ]$color <- "blue" 95 | E(graph)[ weight<0.55 ]$color <- "yellow" 96 | V(graph)$label<- V(graph)$name 97 | graph$layout <- layout.fruchterman.reingold 98 | factor<-as.factor(cut(E(graph)$weight*10,c(4,5,6,7,8),labels=c(1,10,20,30))) 99 | V(graph)$size<-degree(graph) 100 | png('corr_network.png',width=500) 101 | plot(decompose.graph(graph)[[which.max(sapply(decompose.graph(graph), vcount))]],edge.width =as.numeric(factor)*1.5,frame=T) 102 | legend("bottomleft", title="Colors", cex=0.75, pch=16, col=c("black", "blue","red", "green","pink"), legend=c(">70%", "65-70","60-65","55-60","50-55"), ncol=2) 103 | dev.off() -------------------------------------------------------------------------------- /performance/performance.R: -------------------------------------------------------------------------------- 1 | #Author Dzidorius Martinaitis 2 | #Date 2012-02-01 3 | #Description http://www.investuotojas.eu/2012/02/01/vectorized-r-vs-rcpp 4 | 5 | bid = runif(50000000,5,9) 6 | ask = runif(50000000,5,9) 7 | close = runif(50000000,5,9) 8 | 9 | x=data.frame(bid=bid,ask=ask,last_price=close) 10 | rez=0 11 | 12 | ########### ifelse R ################# 13 | answ=as.vector(system.time( 14 | { 15 | rez = ifelse(x$last_price>0,ifelse(x[, "bid"] > x[, "last_price"], x[, "bid"], ifelse((x[, "ask"] > 0) & (x[, "ask"] < x[, "last_price"]), x[, "ask"], x[, "last_price"])), 0.5*(x[, "ask"] + x[,"bid"])) 16 | })[1]) 17 | ########### end ifelse R ################# 18 | 19 | ########### vectorized R ################# 20 | 21 | answ=append(answ,system.time( 22 | { 23 | lgt0 = x$last_price > 0 24 | bgtl = x$bid > x$last_price 25 | agt0 = x$ask > 0 26 | altl = x$ask > x$last_price 27 | rez = x$last_price 28 | rez[lgt0 & agt0 & altl] = x$ask[lgt0 & agt0 & altl] 29 | rez[lgt0 & bgtl] = x$bid[lgt0 & bgtl] 30 | rez[!lgt0] = (x$ask[!lgt0]+x$bid[!lgt0])/2 31 | } 32 | )[1]) 33 | ########### end vectorized R ################# 34 | 35 | ########### Louis optimized R code ################ 36 | answ=append(answ,system.time( 37 | { 38 | rez = vector(mode="numeric", nrow(x)) 39 | lgt0 = x$last_price > 0 40 | bgtl = x$bid > x$last_price 41 | agt0 = x$ask > 0 42 | altl = x$ask > x$last_price 43 | rez = x$last_price 44 | xx <- which(lgt0 & agt0 & altl) 45 | rez[xx] = x$ask[xx] 46 | xx <- which(lgt0 & bgtl) 47 | rez[xx] = x$bid[xx] 48 | xx <- which(!lgt0) 49 | rez[xx] = (x$ask[xx]+x$bid[xx])/2 50 | } 51 | )[1]) 52 | ########### Louis optimized R code ################ 53 | 54 | #C++ code starts here 55 | 56 | library(inline) 57 | library(Rcpp) 58 | 59 | ########### pure C++ ################# 60 | 61 | code=' 62 | NumericVector bid(bid_);NumericVector ask(ask_);NumericVector close(close_); 63 | int bid_size = bid.size(); 64 | NumericVector ret(bid_size); 65 | for(int i =0;i0) 68 | { 69 | if(bid[i]>close[i]) 70 | { 71 | ret[i] = bid[i]; 72 | } 73 | else if(ask[i]>0 && ask[i]count)break; 44 | }) 45 | size=xts(size[,1:2],order.by=as.POSIXct(size[,3]/1000,origin='1970-01-01',tz='Europe/Paris')) 46 | colnames(size)=c('field','size') 47 | 48 | 49 | buf <- mongo.bson.buffer.create() 50 | mongo.bson.buffer.append(buf, "tickerId", 26L) 51 | mongo.bson.buffer.start.object(buf, "price") 52 | mongo.bson.buffer.append(buf, "$exists", "true") 53 | mongo.bson.buffer.finish.object(buf) 54 | 55 | query <- mongo.bson.from.buffer(buf) 56 | count = mongo.count(mongo,'quotes.trinti',query) 57 | 58 | cursor<-mongo.find(mongo,'quotes.trinti',query) 59 | price=matrix(nrow=count,ncol=3) 60 | counter=1 61 | system.time( 62 | while(mongo.cursor.next(cursor)) 63 | { 64 | temp=(mongo.cursor.value(cursor)); 65 | price[counter,1]=mongo.bson.value(temp,"field"); 66 | price[counter,2]=mongo.bson.value(temp,"price"); 67 | price[counter,3]=mongo.bson.value(temp,"tstamp"); 68 | counter=counter+1; 69 | if(counter>count)break; 70 | }) 71 | price=xts(price[,1:2],order.by=as.POSIXct(price[,3]/1000,origin='1970-01-01',tz='Europe/Paris')) 72 | price=(price[which(price[,2]>0)]) 73 | 74 | colnames(price)=c('field','price') 75 | 76 | quotes<-cbind(price[,2][price[,1]==1], 77 | #cac40.volume[,2][cac40.volume[,1]==0], 78 | price[,2][price[,1]==2], 79 | #cac40.volume[,2][cac40.volume[,1]==3], 80 | price[,2][price[,1]==4] 81 | ,size[,2][size[,1]==5] 82 | ) 83 | 84 | quotes[,1]=na.locf(quotes[,1]) 85 | quotes[,2]=na.locf(quotes[,2]) 86 | quotes[,3]=na.locf(quotes[,3]) 87 | quotes[which(is.na(quotes[,4])),3]=NA 88 | 89 | temp=tail(head(quotes,3000),400) 90 | temp=data.frame(ind=1:NROW(temp),trd=as.numeric(temp[,3]) 91 | ,bid=as.numeric(temp[,1]),ask=as.numeric(temp[,2]) 92 | ,size=as.numeric(temp[,4]) 93 | ) 94 | temp=melt(temp,id=c('ind'),na.rm=TRUE) 95 | x=temp[which(temp$variable=='trd'),] 96 | 97 | rez=temp[which(temp$variable!='trd'),] 98 | rez=rez[which(rez$variable!='size'),] 99 | a=temp[which(temp$variable=='size'),][,3] 100 | ggplot(rez,aes(x=ind,y=value,color=variable))+geom_line()+geom_point(data=x,aes(size=a)) -------------------------------------------------------------------------------- /politika/savivaldybes.csv: -------------------------------------------------------------------------------- 1 | "Savivaldybe","Plotas","Gyventoju skaicius","Tankumas","Meras","Partija","Islaidos" 2 | "Akmenės rajonas",844,28204,33.4,"Vitalijus Mitrofanovas","LSDP",7.29 3 | "Alytaus miestas",40,68835,1720.9,"Feliksas Džiautas","LSDP",4.63 4 | "Alytaus rajonas",1404,31420,22.4,"Algirdas Vrubliauskas","TS-LKD",10.17 5 | "Anykščių rajonas",1765,32629,18.5,"Sigutis Obelevičius","TS-LKD",8.4 6 | "Birštono savivaldybė",124,5256,42.4,"Antanas Zenkevičius","LSDP",16.48 7 | "Biržų rajonas",1476,33491,22.7,"Regimantas Ramonas","LSDP",7.16 8 | "Druskininkų savivaldybė",454,24507,54,"Ričardas Malinauskas","LSDP",9.24 9 | "Elektrėnų savivaldybė",509,28093,55.2,"Arvydas Vyšniauskas","LSDP",12.19 10 | "Ignalinos rajonas",1447,20624,14.3,"Bronis Ropė","LVLS",10.59 11 | "Jonavos rajonas",944,51941,55,"Bronislovas Liutkus","LVLS",6.88 12 | "Joniškio rajonas",1152,30429,26.4,"Romaldas Gadeikis","LSDP",10.01 13 | "Jurbarko rajonas",1507,35622,23.6,"Ričardas Juška","LICS",7.41 14 | "Kaišiadorių rajonas",1087,36290,33.4,"Romualdas Urmilevičius","LS",9.78 15 | "Kalvarijos savivaldybė",441,13490,30.6,"Jonas Ščeponis","LSDP",9.7 16 | "Kauno miestas",157,358111,2281,"Andrius Kupčinskas","TS-LKD",8.79 17 | "Kauno rajonas",1496,85721,57.3,"Valerijus Makūnas","LSDP",14.96 18 | "Kazlų Rūdos savivaldybė",555,14615,26.3,"Vytautas Kanevičius","LICS",9.72 19 | "Kėdainių rajonas",1677,63563,37.9,"Nijolė Naujokienė","PDP",7.21 20 | "Kelmės rajonas",1705,38615,22.6,"Kostas Arvasevičius","LSDP",7.7 21 | "Klaipėdos miestas",98,185936,1897.3,"Rimantas Taraškevičius","LICS",4.4 22 | "Klaipėdos rajonas",1336,49295,36.9,"Vaclovas Dačkauskas","LSDP",10.74 23 | "Kretingos rajonas",989,45956,46.5,"Juozas Mažeika","TS-LKD",11.48 24 | "Kupiškio rajonas",1080,23444,21.7,"Jonas Jarutis","LVLS",7.32 25 | "Lazdijų rajonas",1309,25233,19.3,"Artūras Margelis","TS-LKD",10.65 26 | "Marijampolės savivaldybė",755,69297,91.8,"Vidmantas Brazys","LSDP",7.95 27 | "Mažeikių rajonas",1220,65554,53.7,"Vilhelmas Džiugelis","TS-LKD",8.61 28 | "Molėtų rajonas",1367,23539,17.2,"Algimantas Žiukas","TS-LKD",11.13 29 | "Neringos savivaldybė",90,3132,34.8,"Vigantas Giedraitis","TS-LKD",24.76 30 | "Pagėgių savivaldybė",537,11577,21.6,"Virginijus Komskis","TT",18.3 31 | "Pakruojo rajonas",1316,27883,21.2,"Saulius Gegieckas","LSDP",8.83 32 | "Palangos miestas",79,17632,223.2,,,18.11 33 | "Panevėžio miestas",50,114582,2291.6,"Vitalijus Satkevičius","TS-LKD",6.98 34 | "Panevėžio rajonas",2179,43190,19.8,"Povilas Žagunis","LVLS",11.01 35 | "Pasvalio rajonas",1289,32961,25.6,"Vitalijus Satkevičius","TS-LKD",8.53 36 | "Plungės rajonas",1105,43580,39.4,"Elvyra Valerija Lapukienė","TS-LKD",8.26 37 | "Prienų rajonas",1031,34025,33,"Alvydas Vaicekauskas","LSDP",11.3 38 | "Radviliškio rajonas",1635,49705,30.4,"Antanas Čepononis","TS-LKD",6.83 39 | "Raseinių rajonas",1573,42377,26.9,"Dainius Šadauskis","LS",8.38 40 | "Rietavo savivaldybė",586,10208,17.4,"Antanas Černeckis","LICS",12.83 41 | "Rokiškio rajonas",1807,39451,21.8,"Almantas Blažys","TS-LKD",7.69 42 | "Skuodo rajonas",911,24148,26.5,"Stasys Vainoras","LS",11.45 43 | "Šakių rajonas",1453,36805,25.3,"Juozas Bertašius","LVLS",8.28 44 | "Šalčininkų rajonas",1491,37852,25.4,"Zdzislav Palevič","LLRA",12.2 45 | "Šiaulių miestas",81,128397,1585.1,"Genadijus Mikšys","LICS",6.91 46 | "Šiaulių rajonas",1807,50480,27.9,"Algimantas Gaubas","LSDP",10.03 47 | "Šilalės rajonas",1188,30431,25.6,"Albinas Ežerskis","LSDP",10.3 48 | "Šilutės rajonas",1706,53373,31.3,"Virgilijus Pozingis","LVLS",10.03 49 | "Širvintų rajonas",906,19367,21.4,"Kęstutis Pakalnis","LICS",13.08 50 | "Švenčionių rajonas",1692,31130,18.4,"Vytautas Vigelis","LSDP",10.54 51 | "Tauragės rajonas",1179,51049,43.3,"Pranas Petrošius","LSDP",8.85 52 | "Telšių rajonas",1439,55231,38.4,"Valdemaras Ramšas","TT",10.05 53 | "Trakų rajonas",1208,36429,30.2,"Edmundas Zenonas Malūkas","NS",12.61 54 | "Ukmergės rajonas",1395,46303,33.2,"Algirdas Kopūstas","LVLS",8.69 55 | "Utenos rajonas",1230,48378,39.3,"Alvydas Katinas","LSDP",6.89 56 | "Varėnos rajonas",2218,28960,13.1,"Vidas Mikalauskas","LICS",8.07 57 | "Vilkaviškio rajonas",1259,48380,38.4,"Algirdas Bagušinskas","LSDP",8.01 58 | "Vilniaus miestas",401,554409,1382.6,"Raimundas Alekna","TS-LKD",7.45 59 | "Vilniaus rajonas",2129,94171,44.2,"Marija Rekst","LLRA",16.73 60 | "Visagino savivaldybė",58,28576,492.7,"Vytautas Račkauskas","LS",9.09 61 | "Zarasų rajonas",1334,20997,15.7,"Arnoldas Abramavičius","TS-LKD",13.52 62 | -------------------------------------------------------------------------------- /volatility/vix_futures.R: -------------------------------------------------------------------------------- 1 | #Author Dzidorius Martinaitis 2 | #2011-01-21 3 | #Description: 4 | #status: case closed 5 | 6 | Sys.setenv(TZ="GMT") 7 | require('xts') 8 | require('quantmod') 9 | require('blotter') 10 | require('PerformanceAnalytics') 11 | 12 | tmp<-as.matrix(read.table('tickers/various_day_close/VIXc1.csv',sep=',',header=TRUE)) 13 | vix<-as.xts(as.double(tmp[,9]),order.by=as.POSIXct(strptime(tmp[,2],'%d-%b-%Y'),tz='GMT')) 14 | vix<-(vix[!is.na(vix)]) 15 | colnames(vix)<-c('Close') 16 | 17 | 18 | tmp<-as.matrix(read.table('tickers/various_day_close/ESc1.csv',sep=',',header=TRUE)) 19 | es<-as.xts(as.double(tmp[,9]),order.by=as.POSIXct(strptime(tmp[,2],'%d-%b-%Y'))) 20 | es<-(es[!is.na(es)]) 21 | colnames(es)<-c('Close') 22 | 23 | #-----------------data end----------------- 24 | 25 | 26 | #-----------------signal------------------- 27 | es.delta<-Delt(Cl(es)) 28 | delta<-Delt(Cl(vix))#Front contract 29 | 30 | #Historical volatility during 3 and 10 days 31 | short.vol<-as.xts(rollapply(es.delta,3,sd,align='right')) 32 | long.vol<-as.xts(rollapply(es.delta,10,sd,align='right')) 33 | 34 | past.vol<-short.vol/long.vol 35 | future.vol<-lag(past.vol,-3) 36 | future.delta<-lag(vix,-3)/vix-1 37 | 38 | signal<-ifelse(past.vol<0.25,1,0) 39 | 40 | #here we see, increase in historical volatility 41 | summary(as.double(future.vol[index(signal[signal!=0])]))/summary(as.double(past.vol[index(signal[signal!=0])])) 42 | 43 | #-----------------signal end------------------- 44 | 45 | #--------------blotter code------------------ 46 | symbols<-c('vix') 47 | 48 | initDate=time(get(symbols)[1]) 49 | initEq=50000 50 | rm(list=ls(envir=.blotter),envir=.blotter) 51 | ltportfolio='volatility' 52 | ltaccount='volatility' 53 | initPortf(ltportfolio,symbols, initDate=initDate) 54 | initAcct(ltaccount,portfolios=c(ltportfolio), initDate=initDate,initEq=initEq) 55 | currency("USD") 56 | future(symbols[1],currency="USD",1000,0.01) 57 | 58 | #signal<-signal[index(vix)] 59 | 60 | signal[is.na(signal)]<-0 61 | 62 | counter<-0 #date counter - exit on 3th day 63 | 64 | for(i in 2:length(signal)) 65 | { 66 | currentDate= time(signal)[i] 67 | equity = initEq #getEndEq(ltaccount, currentDate) 68 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 69 | print(position) 70 | print(currentDate) 71 | if(position==0 &counter==0) 72 | { 73 | #open a new position if signal is >0 74 | if(signal[i]>0) 75 | { 76 | print('open position') 77 | closePrice<-as.double(get(symbols[1])[currentDate]) 78 | print(closePrice) 79 | unitSize = 1#as.numeric(trunc((equity/closePrice))) 80 | print(unitSize) 81 | commssions=-2#unitSize*closePrice*0.0003 82 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice-0.02, TxnQty = unitSize , TxnFees=commssions, verbose=T) 83 | counter=1 84 | } 85 | 86 | } 87 | else 88 | { 89 | #position is open. If signal is 0 - close it. 90 | if(position!=0 & as.integer(signal[i])==0 &counter>=10) 91 | { 92 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 93 | closePrice<-as.double(get(symbols[1])[currentDate])#as.double(get(symbols[1])[i+100]) 94 | commssions=-2#position*closePrice*0.0003 95 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice+0.02, TxnQty = -position , TxnFees=commssions, verbose=T) 96 | counter<-0 97 | } 98 | else 99 | counter<-counter+1 100 | 101 | } 102 | print(paste('>>>>>>>>>>>>',counter)) 103 | updatePortf(ltportfolio, Dates = currentDate) 104 | updateAcct(ltaccount, Dates = currentDate) 105 | updateEndEq(ltaccount, Dates = currentDate) 106 | } 107 | rez1<-(getPortfolio(ltaccount)) 108 | 109 | #--------------blotter code end------------------ 110 | 111 | #----------------results------------------------ 112 | png('vix_front.png',width=650) 113 | #net profit - commissions, slipage excluded 114 | chart.TimeSeries(cumsum(rez1$symbols$vix$txn[,7]),main='VIX front contract') 115 | dev.off() 116 | #----------------results end------------------------ 117 | 118 | ################################################################################################### 119 | 120 | signal<-ifelse(past.vol<0.25,1,0) 121 | #signal<-signal[index(es)] 122 | 123 | 124 | 125 | #------------------------blotter code----------------------- 126 | symbols<-c('es') 127 | 128 | initDate=time(get(symbols)[1]) 129 | initEq=15000 130 | rm(list=ls(envir=.blotter),envir=.blotter) 131 | ltportfolio='volatility' 132 | ltaccount='volatility' 133 | initPortf(ltportfolio,symbols, initDate=initDate) 134 | initAcct(ltaccount,portfolios=c(ltportfolio), initDate=initDate,initEq=initEq) 135 | currency("USD") 136 | future(symbols[1],currency="USD",multiplier=50,1/4) 137 | 138 | signal[is.na(signal)]<-0 139 | 140 | counter<-0 141 | 142 | for(i in 2:length(signal)) 143 | { 144 | currentDate= time(signal)[i] 145 | equity = initEq #getEndEq(ltaccount, currentDate) 146 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 147 | print(position) 148 | print(currentDate) 149 | if(position==0 &counter==0) 150 | { 151 | #open a new position if signal is >0 152 | if(signal[i]>0) 153 | { 154 | print('open position') 155 | closePrice<-as.double(get(symbols[1])[currentDate]) 156 | print(closePrice) 157 | unitSize = 1#as.numeric(trunc((equity/closePrice))) 158 | print(unitSize) 159 | commssions=-2 160 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = unitSize , TxnFees=commssions, verbose=T) 161 | counter<-1 162 | } 163 | 164 | } 165 | else 166 | { 167 | #position is open. If signal is 0 - close it. 168 | if(position>0 & as.integer(signal[i])==0 &counter>=3) 169 | { 170 | position = getPosQty(ltportfolio, Symbol=symbols[1], Date=currentDate) 171 | closePrice<-as.double(get(symbols[1])[currentDate])#as.double(get(symbols[1])[i+100]) 172 | commssions=-2 173 | addTxn(ltportfolio, Symbol=symbols[1], TxnDate=currentDate, TxnPrice=closePrice, TxnQty = -position , TxnFees=commssions, verbose=T) 174 | counter<-0 175 | } 176 | else 177 | counter<-counter+1 178 | 179 | } 180 | 181 | updatePortf(ltportfolio, Dates = currentDate) 182 | updateAcct(ltaccount, Dates = currentDate) 183 | updateEndEq(ltaccount, Dates = currentDate) 184 | } 185 | rez1<-(getPortfolio(ltaccount)) 186 | #-------------------------results--------------------- 187 | #net profit 188 | png('vix.png',width=650) 189 | chart.TimeSeries(cumsum(rez1$symbols$es$txn[,9]),main='ES future contract') 190 | dev.off() 191 | -------------------------------------------------------------------------------- /tradeCostAnalysis/tradeCostAnalysis.R: -------------------------------------------------------------------------------- 1 | Sys.setenv(TZ="GMT") 2 | library(xts) 3 | library(quantmod) 4 | library("PerformanceAnalytics") 5 | require('ggplot2') 6 | 7 | 8 | 9 | ###############################average daily volume############################### 10 | 11 | avgDailyVolume<-function(x, window=100,plot=TRUE) 12 | { 13 | factor<-as.factor(format(index(x),'%Y%m%d')) 14 | rez<-aggregate(Vo(x),factor,sum) 15 | rez<-as.xts(rez[,1],order.by=as.POSIXct(as.Date(strptime(as.character(index(rez)),'%Y%m%d')))) 16 | rez<-as.xts(rollapply(rez,window,mean,align='right')) 17 | if(plot==TRUE) 18 | { 19 | tmp<-data.frame(as.Date(index(rez)),round(rez[,1])) 20 | colnames(tmp)<-c('Date','Volume') 21 | subs<-tail(tmp,1)#subset(tmp,Date==last(tmp[,1]),Volume) 22 | p<-ggplot(tmp,aes(Date,Volume))+geom_line(color='steelblue',size=1.5)+geom_text(hjust = 0.7, 23 | vjust = 1,size = 3.5,col='red',aes(label=paste('Last: ',Volume)),data=subs); 24 | p<-p+scale_x_date(major='month',format='%Y-%m')+opts(title='Avg. daily volume'); 25 | 26 | print(p); 27 | } 28 | return(last(rez)) 29 | } 30 | #rez<-avgDailyVolume(trade,20) 31 | 32 | volumeDensity<-function(x,q=0.05,plot=TRUE) 33 | { 34 | factor<-as.factor(format(index(x),'%Y%m%d')) 35 | rez<-aggregate(Vo(x),factor,sum) 36 | rez<-as.xts(rez[,1],order.by=as.POSIXct(as.Date(strptime(as.character(index(rez)),'%Y%m%d')))) 37 | rez<-data.frame(Date=index(rez),Volume=rez[,1]) 38 | if(plot==TRUE) 39 | { 40 | p<-ggplot(rez,aes(Volume))+geom_density(color='steelblue',size=1.5)+xlab('Volume') 41 | dens<-density(rez$Volume) 42 | rez1<-data.frame(x = dens$x, y = dens$y) 43 | 44 | p<-p+geom_area(data=subset(rez1,rez1$x