forked from systematicinvestor/SIT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.r
1336 lines (1224 loc) · 34.5 KB
/
utils.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###############################################################################
# Collection of General Utilities
# Copyright (C) 2012 Michael Kapler
#
# For more information please visit my blog at www.SystematicInvestor.wordpress.com
# or drop me a line at TheSystematicInvestor at gmail
###############################################################################
###############################################################################
# Convenience Utilities
###############################################################################
#' Split string into tokens using delim
#'
#' This function will split given string into tokens using delim
#'
#' @param s input string
#' @param delim delimiter, \strong{defaults to ","}
#'
#' @return array of tokens
#'
#' @examples
#' \dontrun{
#' spl('a,b,c')
#' }
#' @export
###############################################################################
spl <- function
(
s, # input string
delim = ',' # delimiter
)
{
return(unlist(strsplit(s,delim)));
}
###############################################################################
#' Join vector of strings into one string using delim
#'
#' This function will join vector of strings into one string using delim
#'
#' @param v vector of strings
#' @param delim delimiter, \strong{defaults to ","}
#'
#' @return resulting string
#'
#' @examples
#' \dontrun{
#' join(c('a','b','c'), ',')
#' }
#' @export
###############################################################################
join <- function
(
v, # vector of strings
delim = '' # delimiter
)
{
return(paste(v,collapse=delim));
}
###############################################################################
#' Remnove any leading and trailing spaces
#'
#' This function will remnove any leading and trailing spaces
#'
#' @param s string
#'
#' @return resulting string
#'
#' @examples
#' \dontrun{
#' trim(' a b c ')
#' }
#' @export
###############################################################################
trim <- function
(
s # string
)
{
s = sub(pattern = '^ +', replacement = '', x = s)
s = sub(pattern = ' +$', replacement = '', x = s)
return(s)
}
###############################################################################
#' Shortcut for length function
#'
#' This function is a shortcut for length function
#'
#' @param x vector / string / matrix
#'
#' @return number of elements in x
#'
#' @examples
#' \dontrun{
#' len(1:10)
#' }
#' @export
###############################################################################
len <- function
(
x # vector
)
{
return(length(x))
}
###############################################################################
#' Faster version of ifelse function
#'
#' This function is a faster version of ifelse function
#'
#' @param cond true / false condition
#' @param truepart resulting value(s) if condition is true
#' @param falsepart resulting value(s) if condition is false
#'
#' @return number of elements in x
#'
#' @examples
#' \dontrun{
#' iif(1:10 > 5, 1, 1:10)
#' }
#' @export
###############################################################################
iif <- function
(
cond, # condition
truepart, # true part
falsepart # false part
)
{
if(len(cond) == 1) { if(cond) truepart else falsepart }
else {
if(length(falsepart) == 1) {
temp = falsepart
falsepart = cond
falsepart[] = temp
}
if(length(truepart) == 1)
falsepart[cond] = truepart
else {
cond = ifna(cond,F)
falsepart[cond] = truepart[cond]
}
#falsepart[!is.na(cond)] = temp
return(falsepart);
}
}
###############################################################################
#' Replace NA, NaN, Inf values
#'
#' This function will replace all NA, NaN, Inf with given values
#'
#' @param x data to check for NA, NaN, Inf
#' @param y values(s) to be used in place of NA, NaN, Inf
#'
#' @return updated data
#'
#' @examples
#' \dontrun{
#' ifna(c(1,NA,2,Inf,3), 4)
#' }
#' @export
###############################################################################
ifna <- function
(
x, # check x for NA, NaN, Inf
y # if found replace with y
)
{
return(iif(is.na(x) | is.nan(x) | is.infinite(x), y, x))
}
#' @export
fast.na.omit <- function
(
x
)
{
x[!is.na(x)]
}
###############################################################################
#' Replace NULL values
#'
#' This function will replace all NULL with given value
#'
#' @param x data to check for NULL
#' @param y values to be used in place of NULL
#'
#' @return updated data
#'
#' @examples
#' \dontrun{
#' temp = list()
#' temp$val1 = ifnull(temp$val1, 4)
#' }
#' @export
###############################################################################
ifnull <- function
(
x, # check x for NULL
y # if found replace with y
) {
return(iif(is.null(x), y, x))
}
###############################################################################
#' Faster version of rep fucntion
#'
#' This function is a faster version of rep fucntion
#'
#' @param x data to be repeated
#' @param times number of times to repeat the data
#'
#' @return new data
#'
#' @examples
#' \dontrun{
#' fast.rep(c(1,NA,2,Inf,3), 4)
#' }
#' @export
###############################################################################
fast.rep <- function(x, times) {
length(x) = times
x[] = x[1]
x
}
fast.rep.test.speed <- function() {
#install.packages('rbenchmark_0.3.tar.gz', repos = NULL, type="source")
test1 <- function() {
rep(101,10000)
}
test2 <- function() {
fast.rep(101,10000)
}
require(rbenchmark)
benchmark(
test1(),
test2(),
columns = c("test", "replications", "elapsed", "relative"),
order = "relative",
replications = 10000
)
}
###############################################################################
#' Count number of non NA elements
#'
#' This function will count number of non NA elements in the given matrix
#'
#' @param x data matrix
#' @param side margin along which to count
#'
#' @return counts
#'
#' @examples
#' \dontrun{
#' count(matrix(c(1,NA,2,3),2,2))
#' }
#' @export
###############################################################################
count <- function(
x, # matrix with data
side = 2 # margin along which to count
)
{
if( is.null(dim(x)) ) {
sum( !is.na(x) )
} else {
apply(!is.na(x), side, sum)
}
}
###############################################################################
#' Running Count over given window
#'
#' This function will count number of non NA elements over given window
#'
#' @param x data matrix
#' @param window.len window length
#'
#' @return counts
#'
#' @examples
#' \dontrun{
#' run.count(matrix(1:9,3,3),2)
#' }
#' @export
###############################################################################
run.count <- function
(
x, # vector with data
window.len # window length
)
{
n = length(x)
xcount = cumsum( !is.na(x) )
ycount = xcount[-c(1 : (k-1))] - c(0, xcount[-c((n-k+1) : n)])
return( c( xcount[1:(k-1)], ycount))
}
###############################################################################
#' Dates Functions
#'
#' @param dates collection of dates
#'
#' @return transformed dates
#'
#' @examples
#' \dontrun{
#' date.dayofweek(Sys.Date())
#' }
#' @export
#' @rdname DateFunctions
###############################################################################
date.dayofweek <- function(dates)
{
return(as.double(format(dates, '%w')))
}
#' @export
#' @rdname DateFunctions
date.day <- function(dates)
{
return(as.double(format(dates, '%d')))
}
#' @export
#' @rdname DateFunctions
date.week <- function(dates)
{
return(as.double(format(dates, '%U')))
}
#' @export
#' @rdname DateFunctions
date.month <- function(dates)
{
return(as.double(format(dates, '%m')))
}
#' @export
#' @rdname DateFunctions
date.year <- function(dates)
{
return(as.double(format(dates, '%Y')))
}
###############################################################################
#' Dates Index Functions
#'
#' @param dates collection of dates
#'
#' @return location of the week/month/year ends
#'
#' @examples
#' \dontrun{
#' date.week.ends(seq(Sys.Date()-100, Sys.Date(), 1))
#' }
#' @export
#' @rdname DateFunctionsIndex
###############################################################################
date.week.ends <- function(dates, last.date=T)
{
ends = which(diff( 100*date.year(dates) + date.week(dates) ) != 0)
if(last.date)
ends.add.last.date(ends, len(dates))
else
ends
}
#' @export
#' @rdname DateFunctionsIndex
date.month.ends <- function(dates, last.date=T)
{
ends = which(diff( 100*date.year(dates) + date.month(dates) ) != 0)
if(last.date)
ends.add.last.date(ends, len(dates))
else
ends
}
#' @export
#' @rdname DateFunctionsIndex
date.year.ends <- function(dates, last.date=T)
{
ends = which(diff( date.year(dates) ) != 0)
if(last.date)
ends.add.last.date(ends, len(dates))
else
ends
}
# helper function to add last date
ends.add.last.date <- function(ends, last.date)
{
unique(c(ends, last.date))
}
# to ger proper month-end and a day before month-end
# !!!note holidayTSX() is missing CALabourDay
# http://www.tmx.com/en/about_tsx/market_hours.html
# load.packages('timeDate')
# from = as.Date('10Jun2013','%d%b%Y')
# to = as.Date('10Jan2014','%d%b%Y')
# holidays = holidayNYSE(date.year(from))
#' @export
business.days <- function(from, to = as.Date(from) + 31, holidays = NULL) {
from = as.Date(from)
to = as.Date(to)
require(timeDate)
dates = seq(from, to, by='day')
rm.index = date.dayofweek(dates) == 6 | date.dayofweek(dates) == 0
if(!is.null(holidays)) {
holidays = as.Date(holidays)
rm.index = rm.index | !is.na(match(dates, holidays))
}
dates[!rm.index]
}
# if date is month end, return zero
# from = as.Date('27Dec2013','%d%b%Y')
# holidays = holidayNYSE(date.year(from))
# dates = business.days(from, from + 40, holidays)
# business.days.till.end(from, holidays)
#' @export
business.days.till.end <- function(from, holidays = NULL, fn.ends = date.month.ends) {
from = as.Date(from)
dates = business.days(from, from + 40, holidays)
index = match.fun(fn.ends)(dates, F)
index[1] - 1
}
###############################################################################
#' Map given time series to monthly
#'
#' If frequency of observations in the given time series is less than monthly,
#' i.e. quaterly or annually, properly align this time series to monthly
#'
#' @param equity time series
#'
#' @return xts object
#'
#' @examples
#' \dontrun{
#' map2monthly(equity)
#' }
#' @export
###############################################################################
map2monthly <- function(equity)
{
#a = coredata(Cl(to.monthly(equal.weight$equity)))
if(compute.annual.factor(equity) >= 12) return(equity)
dates = index(equity)
equity = coredata(equity)
temp = as.Date(c('', 10000*date.year(dates) + 100*date.month(dates) + 1), '%Y%m%d')[-1]
new.dates = seq(temp[1], last(temp), by = 'month')
map = match( 100*date.year(dates) + date.month(dates), 100*date.year(new.dates) + date.month(new.dates) )
temp = rep(NA, len(new.dates))
temp[map] = equity
#range(a - temp)
return( make.xts( ifna.prev(temp), new.dates) )
}
###############################################################################
#' Create monthly table
#'
#' Transform given monthly time series into matrix with Months as columns and Years as rows
#'
#' @param monthly.data monthly time series
#'
#' @return matrix with Months as columns and Years as rows
#'
#' @examples
#' \dontrun{
#' create.monthly.table(monthly.ret)
#' }
#' @export
###############################################################################
create.monthly.table <- function(monthly.data)
{
nperiods = nrow(monthly.data)
years = date.year(index(monthly.data[c(1,nperiods)]))
years = years[1] : years[2]
# create monthly matrix
temp = matrix( double(), len(years), 12)
rownames(temp) = years
colnames(temp) = spl('Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec')
# align months
index = date.month(index(monthly.data[c(1,nperiods)]))
temp[] = matrix( c( rep(NA, index[1]-1), monthly.data, rep(NA, 12-index[2]) ), ncol=12, byrow = T)
return(temp)
}
###############################################################################
#' Compute the expiration date of stock options (3rd Friday of the month)
#'
#' @param year year
#' @param month month
#'
#' @return date for the third Friday of the given month and year
#'
#' @references
#' \url{http://bytes.com/topic/python/answers/161147-find-day-week-month-year}
#'
#' \url{http://www.mysmp.com/options/options-expiration-week.html}
#' The week beginning on Monday prior to the Saturday of options expiration is referred to as options expiration week.
#' Since the markets are closed on Saturday, the third Friday of each month represents options expiration.
#' If the third Friday of the month is a holiday, all trading dates are moved forward; meaning that Thursday will be the last trading day to exercise options.
#'
#' \url{http://www.cboe.com/TradTool/ExpirationCalendar.aspx}
#'
#' @examples
#' \dontrun{
#' third.friday.month(2012,1)
#' }
#' @export
###############################################################################
third.friday.month <- function(year, month)
{
day = date.dayofweek( as.Date(c('', 10000*year + 100*month + 1), '%Y%m%d')[-1] )
day = c(20,19,18,17,16,15,21)[1 + day]
return(as.Date(c('', 10000*year + 100*month + day), '%Y%m%d')[-1])
}
###############################################################################
#' Determine the index of subset of dates in the time series
#'
#' @param x xts time series
#' @param dates string represnting subset of dates i.e. '2010::2012'
#'
#' @return index of subset of dates in the time series
#'
#' @examples
#' \dontrun{
#' dates2index(data$prices, '2010::2012')
#'
#' data = textConnection('
#' date,Close
#' 2013-03-18, 154.97
#' 2013-03-19, 154.61
#' 2013-03-20, 155.69
#' 2013-03-21, 154.36
#' 2013-03-22, 155.60
#' 2013-03-25, 154.95')
#'
#' x = read.xts(data)
#' dates2index(x, '2013-03-19')
#'
#' }
#' @export
###############################################################################
dates2index <- function( x, dates = 1:nrow(x) ) {
dates.index = dates
if(!is.numeric(dates)) {
temp = x[,1]
temp[] = 1:nrow(temp)
dates.index = as.numeric(temp[dates])
}
return(dates.index)
}
###############################################################################
#' Load Packages that are available and install ones that are not available
#'
#' This function a convience wrapper for install.packages() function
#'
#' @param packages names of the packages separated by comma
#' @param repos default repository
#' @param dependencies type of dependencies to install
#' @param ... additional parameters for the \code{\link{install.packages}} function
#'
#' @return nothing
#'
#' @examples
#' \dontrun{
#' load.packages('quantmod')
#' }
#' @export
###############################################################################
load.packages <- function
(
packages, # names of the packages separated by comma
repos = "http://cran.r-project.org",# default repository
dependencies = c("Depends", "Imports"), # install dependencies
... # other parameters to install.packages
)
{
packages = spl(packages)
for( ipackage in packages ) {
if(!require(ipackage, quietly=TRUE, character.only = TRUE)) {
install.packages(ipackage, repos=repos, dependencies=dependencies, ...)
if(!require(ipackage, quietly=TRUE, character.only = TRUE)) {
stop("package", sQuote(ipackage), 'is needed. Stopping')
}
}
}
}
###############################################################################
#' Begin Timing
#'
#' @param identifier name for this timing session
#'
#' @return nothing
#'
#' @examples
#' \dontrun{
#' tic(1)
#' }
#' @export
#' @rdname TimingFunctions
###############################################################################
tic <- function
(
identifier # integer value
)
{
assign(paste('saved.time', identifier, sep=''), proc.time()[3], envir = .GlobalEnv)
}
###############################################################################
#' End Timing and report elapsed time
#'
#' @param identifier name for this timing session
#'
#' @return elapsed time
#'
#' @examples
#' \dontrun{
#' toc(1)
#' }
#' @export
#' @rdname TimingFunctions
###############################################################################
toc <- function
(
identifier # integer value
)
{
if( exists(paste('saved.time', identifier, sep=''), envir = .GlobalEnv) ) {
prevTime = get(paste('saved.time', identifier, sep=''), envir = .GlobalEnv)
diffTimeSecs = proc.time()[3] - prevTime
cat('Elapsed time is', round(diffTimeSecs, 2), 'seconds\n')
} else {
cat('Toc error\n')
}
return (paste('Elapsed time is', round(diffTimeSecs,2), 'seconds', sep=' '))
}
test.tic.toc <- function()
{
tic(10)
for( i in 1 : 100 ) {
temp = runif(100)
}
toc(10)
}
###############################################################################
#' Lag matrix or vector
#'
#' This function shifts elemnts in a vector or a mtrix by a given lag.
#' For example: mlag(x,1) - use yesterday's values and
#' mlag(x,-1) - use tomorrow's values
#'
#' @param x vector / matrix
#' @param nlag number of lags, \strong{defaults to 1}
#'
#' @return modified object
#'
#' @examples
#' \dontrun{
#' mlag(1:10)
#' }
#' @export
###############################################################################
mlag <- function
(
m, # matrix or vector
nlag = 1 # number of lags
)
{
# vector
if( is.null(dim(m)) ) {
n = len(m)
if(nlag > 0) {
m[(nlag+1):n] = m[1:(n-nlag)]
m[1:nlag] = NA
} else if(nlag < 0) {
m[1:(n+nlag)] = m[(1-nlag):n]
m[(n+nlag+1):n] = NA
}
# matrix
} else {
n = nrow(m)
if(nlag > 0) {
m[(nlag+1):n,] = m[1:(n-nlag),]
m[1:nlag,] = NA
} else if(nlag < 0) {
m[1:(n+nlag),] = m[(1-nlag):n,]
m[(n+nlag+1):n,] = NA
}
}
return(m);
}
###############################################################################
#' Replicate and tile a given vector
#'
#' @param v vector
#' @param n number of copies along rows
#' @param m number of copies along columns
#'
#' @return new matrix
#'
#' @references
#' \url{http://www.mathworks.com/help/techdoc/ref/repmat.html}
#'
#' @examples
#' \dontrun{
#' repmat(1:10,1,2)
#' }
#' @export
###############################################################################
repmat <- function
(
v, # vector
n, # number of copies along rows
m # number of copies along columns
)
{
kronecker( matrix(1, n, m), v )
}
###############################################################################
#' Repeat Rows
#'
#' @param m vector (row)
#' @param nr number of copies along rows
#'
#' @return new matrix
#'
#' @examples
#' \dontrun{
#' matrix(1:3, nr=5, nc=3, byrow=T)
#' rep.row(1:3, 5)
#' }
#' @export
###############################################################################
rep.row <- function
(
m, # vector (row)
nr # number of copies along rows
)
{
matrix(m, nr=nr, nc=len(m), byrow=T)
}
###############################################################################
#' Repeat Columns
#'
#' @param m vector (column)
#' @param nc number of copies along columns
#'
#' @return new matrix
#'
#' @examples
#' \dontrun{
#' matrix(1:5, nr=5, nc=3, byrow=F)
#' rep.col(1:5, 3)
#' }
#' @export
###############################################################################
rep.col <- function
(
m, # vector (column)
nc # number of copies along columns
)
{
matrix(m, nr=len(m), nc=nc, byrow=F)
}
###############################################################################
#' Find location: row, col in the matrix, given index of of observation
#'
#' @param data matrix
#' @param i index of observations
#' @param details flag to provide details, \strong{defaults to FALSE}
#'
#' @return new matrix
#'
#' @examples
#' \dontrun{
#' data = matrix(1:16,4,4)
#' lookup.index(data, which(data > 4))
#' }
#' @export
# play with following example: update 1 %% 4
###############################################################################
lookup.index <- function
(
data, # matrix
i, # index of observations
details = F # flag to return additional details
)
{
n = nrow(data)
irow = ((i - 1) %% n) + 1
icol = ((i - 1) %/% n) +1
if(details)
list(irow=irow,icol=icol,obs=data[irow,icol],obsr=data[max(0,irow-5):min(nrow(data),irow+5),icol])
else
list(irow=irow,icol=icol)
}
###############################################################################
#' Convert beta (slope of reggression line) to degrees
#'
#' @param beta slope of regression line
#'
#' @return angle
#'
#' @references
#' \url{http://r.789695.n4.nabble.com/slope-calculation-td858652.html }
#'
#' @examples
#' \dontrun{
#' beta.degree(1)
#' }
#' @export
###############################################################################
beta.degree <- function(beta)
{
atan(beta)*360/(2*pi)
}
###############################################################################
# XTS helper functions
###############################################################################
# must set timezone before any calls to xts
Sys.setenv(TZ = 'GMT')
#Sys.setenv(TZ = 'EST')
###############################################################################
#' The timezone is set to 'GMT' by defult
#'
#' The reason for setting the default timezone is because the following code
#' produces different results if the timezone is NOT set and if timezone has a value.
#'
#' @examples
#' \dontrun{
#
#' # We want to set the timezone, so that following code produces expected results
#' Sys.getenv('TZ')
#' test = as.POSIXct('2012-10-31', format='%Y-%m-%d')
#' as.numeric(test)
#' as.numeric(as.POSIXct(as.Date(test)))
#' as.numeric(as.POSIXct(as.Date(test))) - as.numeric(test)
#' test == as.POSIXct(as.Date(test))
#'
#' # Set Time Zone
#' Sys.setenv(TZ = 'GMT')
#' Sys.getenv('TZ')
#' test = as.POSIXct('2012-10-31', format='%Y-%m-%d')
#' as.numeric(test)
#' as.numeric(as.POSIXct(as.Date(test)))
#' as.numeric(as.POSIXct(as.Date(test))) - as.numeric(test)
#' test == as.POSIXct(as.Date(test))
#'
#' }
#' @export
#' @rdname XTSFunctions
###############################################################################
XTSFunctions <- function() {}
###############################################################################
#' Create \code{\link{xts}} object, faster version of \code{\link{xts}} fucntion
#'
#' @param x vector / matrix / data frame
#' @param order.by dates that correspond to rows of x
#'
#' @return \code{\link{xts}} object
#'
#' @examples
#' \dontrun{
#' make.xts(1:101,seq(Sys.Date()-100, Sys.Date(), 1))
#' }
#' @export
###############################################################################
make.xts <- function
(
x, # data
order.by # date
)
{
#Sys.setenv(TZ = 'GMT')
tzone = Sys.getenv('TZ')
orderBy = class(order.by)
index = as.numeric(as.POSIXct(order.by, tz = tzone))
# need to handle case for one row; i.e. len(orderBy) == 1
if( is.null(dim(x)) ) {
if( len(orderBy) == 1 )
x = t(as.matrix(x))
else
dim(x) = c(len(x), 1)
}
x = as.matrix(x)
x = structure(.Data = x,
index = structure(index, tzone = tzone, tclass = orderBy),
class = c('xts', 'zoo'), .indexCLASS = orderBy, tclass=orderBy, .indexTZ = tzone, tzone=tzone)
return( x )
}
###############################################################################
#' Write \code{\link{xts}} object to file
#'
#' @param x \code{\link{xts}} object
#' @param filename file name
#' @param append flag to inidicate if file is overwritten or appended, \strong{defaults to FALSE}
#' @param ... additional paramaeters to the \code{\link{format}} function
#'
#' @return nothing
#'
#' @examples
#' \dontrun{
#' write.xts(make.xts(1:101,seq(Sys.Date()-100, Sys.Date(), 1)), 'temp.csv')
#' }
#' @export
###############################################################################
write.xts <- function
(
x, # XTS object
filename, # file name
append = FALSE,
...
)
{
cat('Date', file = filename, append = append)
write.table(x, sep=',', row.names = format(index(x), ...),
col.names = NA, file = filename, append = T, quote = F)
#write.csv(x, row.names = format(index(x)), filename)
}
###############################################################################
#' Read \code{\link{xts}} object from file
#'
#' @param filename file name
#' @param date.fn function to preprocess string dates, \strong{defaults to \code{\link{paste}} - i.e. no preprocessing}
#' @param index.class class of the date object, \strong{defaults to 'Date'}
#' @param ... additional paramaeters to the \code{\link{as.POSIXct}} function
#'
#' @return \code{\link{xts}} object
#'
#' @examples
#' \dontrun{
#' write.xts(make.xts(1:101,seq(Sys.Date()-100, Sys.Date(), 1)), 'temp.csv')
#' read.xts('temp.csv')