fts/0000755000176000001440000000000013346662421011105 5ustar ripleyusersfts/src/0000755000176000001440000000000013346655312011675 5ustar ripleyusersfts/src/Makevars0000644000176000001440000000004513346655317013375 0ustar ripleyusersPKG_CXXFLAGS = -I./tslib -I./helpers fts/src/helpers/0000755000176000001440000000000012317336722013335 5ustar ripleyusersfts/src/helpers/R.tseries.data.backend.hpp0000644000176000001440000001367512317330541020227 0ustar ripleyusers#ifndef R_TSERIES_DATA_BACKEND_HPP #define R_TSERIES_DATA_BACKEND_HPP #include #include #include #include #define R_NO_REMAP #include #include class BackendBase { public: SEXP Robject; ~BackendBase() { if(Robject!=R_NilValue) { UNPROTECT_PTR(Robject); } } BackendBase(): Robject(R_NilValue) {} // deep copy (do we need this)? // BackendBase(const BackendBase& t): Robject(PROTECT(duplicate(t.Robject))) {}; BackendBase(const BackendBase& t): Robject(PROTECT(t.Robject)) { if(Rf_getAttrib(Robject,R_ClassSymbol)==R_NilValue) { throw std::logic_error("BackendBase(const SEXP x): Object has no classname."); } if(strcmp(CHAR(STRING_ELT(Rf_getAttrib(Robject,R_ClassSymbol),0)),"fts")!=0) { throw std::logic_error("BackendBase(const SEXP x): not an fts object."); } if(Rf_getAttrib(Robject,Rf_install("index"))==R_NilValue) { throw std::logic_error("BackendBase(const SEXP x): Object has no index."); } } // SEXP constructor assumes an existing fts object // throw if fts class is missing or index is missing BackendBase(const SEXP x): Robject(PROTECT(x)) { if(Rf_getAttrib(Robject,R_ClassSymbol)==R_NilValue) { throw std::logic_error("BackendBase(const SEXP x): Object has no classname."); } if(strcmp(CHAR(STRING_ELT(Rf_getAttrib(Robject,R_ClassSymbol),0)),"fts")!=0) { throw std::logic_error("BackendBase(const SEXP x): not an fts object."); } if(Rf_getAttrib(Robject,Rf_install("index"))==R_NilValue) { throw std::logic_error("BackendBase(const SEXP x): Object has no index."); } } // use this constructor for new fts objects BackendBase(SEXPTYPE rtype, R_len_t nr, R_len_t nc): Robject(PROTECT(Rf_allocMatrix(rtype,nr,nc))) { // add fts class to Robject SEXP r_tseries_class = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(r_tseries_class, 0, Rf_mkChar("fts")); SET_STRING_ELT(r_tseries_class, 1, Rf_mkChar("zoo")); Rf_classgets(Robject, r_tseries_class); UNPROTECT(1); // r_tseries_class } R_len_t nrow() const { return Rf_nrows(Robject); } R_len_t ncol() const { return Rf_ncols(Robject); } void setColnames(const std::vector& cnames) { int protect_count(0); if(static_cast(cnames.size()) != Rf_ncols(Robject)) { REprintf("setColnames: colnames size does not match ncols(Robject)."); return; } // check if we have existing dimnames SEXP dimnames = Rf_getAttrib(Robject, R_DimNamesSymbol); if(dimnames == R_NilValue) { PROTECT(dimnames = Rf_allocVector(VECSXP, 2)); ++protect_count; SET_VECTOR_ELT(dimnames, 0, R_NilValue); } SEXP cnames_sexp = PROTECT(Rf_allocVector(STRSXP,cnames.size())); ++protect_count; for(size_t i = 0; i < cnames.size(); ++i) { SET_STRING_ELT(cnames_sexp, i, Rf_mkChar(cnames[i].c_str())); } SET_VECTOR_ELT(dimnames, 1, cnames_sexp); Rf_setAttrib(Robject, R_DimNamesSymbol, dimnames); UNPROTECT(protect_count); } std::vector getColnames() const { std::vector ans; if(Rf_getAttrib(Robject, R_DimNamesSymbol)!=R_NilValue && VECTOR_ELT(Rf_getAttrib(Robject, R_DimNamesSymbol), 1)!=R_NilValue) { SEXP cnames = VECTOR_ELT(Rf_getAttrib(Robject, R_DimNamesSymbol), 1); for(R_len_t i = 0; i < Rf_length(cnames);++i) { ans.push_back(CHAR(STRING_ELT(cnames,i))); } } return ans; } const size_t getColnamesSize() const { if(Rf_getAttrib(Robject, R_DimNamesSymbol)!=R_NilValue && VECTOR_ELT(Rf_getAttrib(Robject, R_DimNamesSymbol), 1)!=R_NilValue) { return Rf_length(VECTOR_ELT(Rf_getAttrib(Robject, R_DimNamesSymbol), 1)); } return 0; } }; template class PosixBackend : public BackendBase { public: PosixBackend() {} PosixBackend(const PosixBackend& t): BackendBase(t.Robject) {} PosixBackend(const TSDIM rows, const TSDIM cols): BackendBase(Rallocator::getType(),rows, cols) { // create dates SEXP R_dates = PROTECT(Rallocator::Vector(rows)); // create and add dates class to dates object SEXP r_dates_class = PROTECT(Rf_allocVector(STRSXP, 2)); SET_STRING_ELT(r_dates_class, 0, Rf_mkChar("POSIXct")); SET_STRING_ELT(r_dates_class, 1, Rf_mkChar("POSIXt")); Rf_classgets(R_dates, r_dates_class); // attach dates to Robject Rf_setAttrib(Robject,Rf_install("index"),R_dates); UNPROTECT(2); // R_dates, r_dates_class } PosixBackend(const SEXP x): BackendBase(x) {} TSDIM nrow() const { return BackendBase::nrow(); } TSDIM ncol() const { return BackendBase::ncol(); } TDATA* getData() const { return Rallocator::RdataPtr(Robject); } TDATE* getDates() const { return Rallocator::RdataPtr(Rf_getAttrib(Robject,Rf_install("index"))); } }; template class JulianBackend : public BackendBase { public: JulianBackend() {} JulianBackend(const JulianBackend& t): BackendBase(t.Robject) {} JulianBackend(const TSDIM rows, const TSDIM cols): BackendBase(Rallocator::getType(),rows, cols) { // create dates SEXP R_dates = PROTECT(Rallocator::Vector(rows)); // create and add dates class to dates object SEXP r_dates_class = PROTECT(Rf_allocVector(STRSXP, 1)); SET_STRING_ELT(r_dates_class, 0, Rf_mkChar("Date")); Rf_classgets(R_dates, r_dates_class); // attach dates to Robject Rf_setAttrib(Robject,Rf_install("index"),R_dates); UNPROTECT(2); // R_dates, r_dates_class } JulianBackend(const SEXP x): BackendBase(x) {} TSDIM nrow() const { return BackendBase::nrow(); } TSDIM ncol() const { return BackendBase::ncol(); } TDATA* getData() const { return Rallocator::RdataPtr(Robject); } TDATE* getDates() const { return Rallocator::RdataPtr(Rf_getAttrib(Robject,Rf_install("index"))); } }; #endif // R_TSERIES_DATA_BACKEND_HPP fts/src/helpers/time.window.template.hpp0000644000176000001440000001016012317300545020114 0ustar ripleyusers#ifndef TIME_WINDOW_TEMPLATE_HPP #define TIME_WINDOW_TEMPLATE_HPP #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy, template class windowFunction, template class windowFunctionTraits, template class> class PFUNC> SEXP timeWindowFun(SEXP x) { // define our answer type based on windowFunctionTraits return type typedef typename windowFunctionTraits::ReturnType ReturnTDATA; // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.template time_window(); return ans.getIMPL()->Robject; } template class windowFunction, template class windowFunctionTraits,template class> class PFUNC> SEXP timeWindowSpecializer(SEXP x) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return timeWindowFun(x); } else { //throw std::logic_error("unable to classify time series."); REprintf("timeWindowSpecializer: unable to classify time series."); return R_NilValue; } } #endif // TIME_WINDOW_TEMPLATE_HPP fts/src/helpers/freq.transform.template.hpp0000644000176000001440000000646312317300545020632 0ustar ripleyusers#ifndef FREQ_TRANSFORM_TEMPLATE_HPP #define FREQ_TRANSFORM_TEMPLATE_HPP #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy, template class> class PFUNC> SEXP freqFun(SEXP x) { // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.template freq(); return ans.getIMPL()->Robject; } template class> class PFUNC> SEXP freqSpecializer(SEXP x) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return freqFun(x); } else { //throw std::logic_error("unable to classify time series."); REprintf("transformSpecializer: unable to classify time series."); return R_NilValue; } } #endif // FREQ_TRANSFORM_TEMPLATE_HPP fts/src/helpers/Rsexp.allocator.templates.hpp0000644000176000001440000000536712317300545021130 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RSEXP_ALLOCATOR_TEMPLATES_HPP #define RSEXP_ALLOCATOR_TEMPLATES_HPP #define R_NO_REMAP #include template class Rallocator { public: static SEXPTYPE getType(); static SEXP Matrix(const R_len_t nr, const R_len_t nc); static SEXP Vector(const R_len_t len); static T* RdataPtr(const SEXP x); static T scalar(const SEXP x); }; template<> class Rallocator { public: static SEXPTYPE getType() { return REALSXP; } static SEXP Matrix(const R_len_t nr, const R_len_t nc) { return Rf_allocMatrix(REALSXP,nr,nc); } static SEXP Vector(const R_len_t len) { return Rf_allocVector(REALSXP,len); } static double* RdataPtr(const SEXP x) { return REAL(x); } static double scalar(const SEXP x) { return REAL(x)[0]; } }; template<> class Rallocator { public: static SEXPTYPE getType() { return INTSXP; } static SEXP Matrix(const R_len_t nr, const R_len_t nc) { return Rf_allocMatrix(INTSXP,nr,nc); } static SEXP Vector(const R_len_t len) { return Rf_allocVector(INTSXP,len); } static int* RdataPtr(const SEXP x) { return INTEGER(x); } static int scalar(const SEXP x) { return INTEGER(x)[0]; } }; template<> class Rallocator { public: static SEXPTYPE getType() { return LGLSXP; } static SEXP Matrix(const R_len_t nr, const R_len_t nc) { return Rf_allocMatrix(LGLSXP,nr,nc); } static SEXP Vector(const R_len_t len) { return Rf_allocVector(LGLSXP,len); } static int* RdataPtr(const SEXP x) { return LOGICAL(x); } static int scalar(const SEXP x) { return LOGICAL(x)[0]; } }; #endif // RSEXP_ALLOCATOR_TEMPLATES_HPP fts/src/helpers/window.intersection.template.hpp0000644000176000001440000001122512317300545021667 0ustar ripleyusers#ifndef WINDOW_INTERSECTION_TEMPLATE_HPP #define WINDOW_INTERSECTION_TEMPLATE_HPP #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy, template class windowFunction, template class windowFunctionTraits> SEXP windowFun(SEXP x_, SEXP y_, SEXP periods) { // define our answer type based on windowFunctionTraits return type typedef typename windowFunctionTraits::ReturnType ReturnTDATA; int p = Rtype::scalar(periods); if(p <= 0) { REprintf("windowFun: periods is not positive."); return R_NilValue; } // build tseries from SEXP x_ TSDATABACKEND x_backend(x_); TSeries x(x_backend); // build tseries from SEXP y_ TSDATABACKEND y_backend(y_); TSeries y(y_backend); TSeries ans = window_function(x,y,p); return ans.getIMPL()->Robject; } template class windowFunction, template class windowFunctionTraits> SEXP windowSpecializer(SEXP x, SEXP y, SEXP periods) { if(TYPEOF(periods)!=INTSXP) { REprintf("windowSpecializer: periods is not an integer."); }; const TsTypeTuple tsTypeInfoX(x); const TsTypeTuple tsTypeInfoY(y); if(tsTypeInfoX!=tsTypeInfoY) { REprintf("windowSpecializer_2args: x and y must be same time series types."); return R_NilValue; } if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==REALSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==INTSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==LGLSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==REALSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==INTSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==LGLSXP && tsTypeInfoX.datePolicy==dateT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==REALSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==INTSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==REALSXP && tsTypeInfoX.dataSEXPTYPE==LGLSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==REALSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==INTSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else if(tsTypeInfoX.dateSEXPTYPE==INTSXP && tsTypeInfoX.dataSEXPTYPE==LGLSXP && tsTypeInfoX.datePolicy==posixT) { return windowFun(x,y,periods); } else { //throw std::logic_error("unable to classify time series."); REprintf("windowSpecializer_2args: unable to classify time series."); return R_NilValue; } } #endif // WINDOW_INTERSECTION_TEMPLATE_HPP fts/src/helpers/fts.factory.hpp0000644000176000001440000000251612317300545016306 0ustar ripleyusers#ifndef FTS_FACTORY_HPP #define FTS_FACTORY_HPP #include #include #define R_NO_REMAP #include enum DatePolicyT { dateT, posixT, unknownDateTypeT }; class TsTypeTuple { public: static DatePolicyT getIndexPolicyType(SEXP x) { SEXP klass = Rf_getAttrib(x,R_ClassSymbol); if(klass==R_NilValue) return unknownDateTypeT; if(strcmp(CHAR(STRING_ELT(klass,0)),"Date")==0) return dateT; if(strcmp(CHAR(STRING_ELT(klass,0)),"POSIXct")==0) return posixT; if(Rf_length(klass)>1 && strcmp(CHAR(STRING_ELT(klass,1)),"POSIXct")==0) return posixT; return unknownDateTypeT; } SEXPTYPE dateSEXPTYPE; SEXPTYPE dataSEXPTYPE; DatePolicyT datePolicy; TsTypeTuple(SEXP x): dateSEXPTYPE(TYPEOF(Rf_getAttrib(x,Rf_install("index")))), dataSEXPTYPE(TYPEOF(x)), datePolicy(getIndexPolicyType(Rf_getAttrib(x,Rf_install("index")))) { if(Rf_getAttrib(x,Rf_install("index"))==R_NilValue) { REprintf("Object has no index."); } } bool operator==(const TsTypeTuple& other) const { if(dateSEXPTYPE == other.dateSEXPTYPE && dataSEXPTYPE == other.dataSEXPTYPE && datePolicy == other.datePolicy) { return true; } else { return false; } } bool operator!=(const TsTypeTuple& other) const { return !(*this == other); } }; #endif // FTS_FACTORY_HPP fts/src/helpers/window.template.hpp0000644000176000001440000001030512317300545017160 0ustar ripleyusers#ifndef WINDOW_TEMPLATE_HPP #define WINDOW_TEMPLATE_HPP #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy, template class windowFunction, template class windowFunctionTraits> SEXP windowFun(SEXP x, SEXP periods) { // define our answer type based on windowFunctionTraits return type typedef typename windowFunctionTraits::ReturnType ReturnTDATA; int p = Rtype::scalar(periods); if(p <= 0) { REprintf("windowFun: periods is not positive."); return R_NilValue; } // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.template window(p); return ans.getIMPL()->Robject; } template class windowFunction, template class windowFunctionTraits> SEXP windowSpecializer(SEXP x, SEXP periods) { if(TYPEOF(periods)!=INTSXP) { REprintf("windowSpecializer: periods is not an integer."); }; const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return windowFun(x,periods); } else { //throw std::logic_error("unable to classify time series."); REprintf("windowSpecializer: unable to classify time series."); return R_NilValue; } } #endif // WINDOW_TEMPLATE_HPP fts/src/helpers/transform.template.hpp0000644000176000001440000002001412317300545017662 0ustar ripleyusers#ifndef TRANSFORM_TEMPLATE_HPP #define TRANSFORM_TEMPLATE_HPP #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy, template class transformFunction, template class transformFunctionTraits> SEXP transformFun(SEXP x) { // define our answer type based on windowFunctionTraits return type typedef typename transformFunctionTraits::ReturnType ReturnTDATA; // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.template transform(); return ans.getIMPL()->Robject; } template class TSDATABACKEND, template class DatePolicy, template class transformFunction, template class transformFunctionTraits> SEXP transformFun(SEXP x, SEXP arg1) { // define our answer type based on windowFunctionTraits return type typedef typename transformFunctionTraits::ReturnType ReturnTDATA; // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); // use policy class to discover argument type typedef typename transformFunctionTraits::ArgType ArgType; TSeries ans = ts.template transform_1arg(Rallocator::scalar(arg1)); return ans.getIMPL()->Robject; } template class transformFunction, template class transformFunctionTraits> SEXP transformSpecializer(SEXP x) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x); } else { //throw std::logic_error("unable to classify time series."); REprintf("transformSpecializer: unable to classify time series."); return R_NilValue; } } template class transformFunction, template class transformFunctionTraits> SEXP transformSpecializer(SEXP x, SEXP arg1) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return transformFun(x,arg1); } else { //throw std::logic_error("unable to classify time series."); REprintf("transformSpecializer: unable to classify time series."); return R_NilValue; } } #endif // TRANSFORM_TEMPLATE_HPP fts/src/helpers/Rtype.hpp0000644000176000001440000000452012317300545015144 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RTYPE_HPP #define RTYPE_HPP #define R_NO_REMAP #include template class Rtype; template<> class Rtype { public: typedef double ValueType; static double& scalar(SEXP x) { return REAL(x)[0]; } static double& index(SEXP x, R_len_t i) { return REAL(x)[i]; } }; template<> class Rtype { public: typedef int ValueType; static int& scalar(SEXP x) { return INTEGER(x)[0]; } static int& index(SEXP x, R_len_t i) { return INTEGER(x)[i]; } }; template<> class Rtype { public: typedef int ValueType; static int& scalar(SEXP x) { return LOGICAL(x)[0]; } static int& index(SEXP x, R_len_t i) { return LOGICAL(x)[i]; } }; template<> class Rtype { public: typedef SEXP ValueType; static SEXP& scalar(SEXP x) { return STRING_PTR(x)[0]; } static SEXP& index(SEXP x, R_len_t i) { return STRING_PTR(x)[i]; } }; template<> class Rtype { public: typedef SEXP ValueType; static SEXP scalar(SEXP x) { return VECTOR_ELT(x,0); } static SEXP index(SEXP x, R_len_t i) { return VECTOR_ELT(x,i); } }; #endif // RTYPE_HPP fts/src/diff.cpp0000644000176000001440000000643613346655317013327 0ustar ripleyusers#define R_NO_REMAP #include #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy> SEXP diffFun(SEXP x, SEXP periods) { int p = Rtype::scalar(periods); if(p <= 0) { REprintf("diffFun: periods is not positive."); return R_NilValue; } // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.diff(p); return ans.getIMPL()->Robject; } SEXP diffSpecializer(SEXP x, SEXP p) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return diffFun(x,p); } else { //throw std::logic_error("unable to classify time series."); REprintf("diffSpecializer: unable to classify time series."); return R_NilValue; } } extern "C" SEXP diff(SEXP x, SEXP periods) { return diffSpecializer(x,periods); } fts/src/lead.cpp0000644000176000001440000000643613346655317013324 0ustar ripleyusers#define R_NO_REMAP #include #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy> SEXP leadFun(SEXP x, SEXP periods) { int p = Rtype::scalar(periods); if(p <= 0) { REprintf("leadFun: periods is not positive."); return R_NilValue; } // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.lead(p); return ans.getIMPL()->Robject; } SEXP leadSpecializer(SEXP x, SEXP p) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return leadFun(x,p); } else { //throw std::logic_error("unable to classify time series."); REprintf("diffSpecializer: unable to classify time series."); return R_NilValue; } } extern "C" SEXP lead(SEXP x, SEXP periods) { return leadSpecializer(x,periods); } fts/src/tslib/0000755000176000001440000000000012317336722013010 5ustar ripleyusersfts/src/tslib/Makefile0000644000176000001440000000035113346655317014456 0ustar ripleyusersINSTALL_DIR=/usr/include CFLAGS = -Wall -O0 -g -fpic CXXFLAGS = $(CFLAGS) LDFLAGS = CXX = g++ SUBDIRS = test .PHONY: subdirs $(SUBDIRS) subdirs: $(SUBDIRS) $(SUBDIRS): $(MAKE) -C $@ install: cp -r ./tslib $(INSTALL_DIR) fts/src/tslib/tslib/0000755000176000001440000000000012317336722014125 5ustar ripleyusersfts/src/tslib/tslib/vector.summary.hpp0000644000176000001440000000352611240355401017627 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef VECTOR_SUMMARY_HPP #define VECTOR_SUMMARY_HPP // taking 1 vector an argument #include #include #include #include #include #include #include #include #include // technical analysis #include // taking 2 vectors as arguments #include #include #endif // VECTOR_SUMMARY_HPP fts/src/tslib/tslib/tseries.data.hpp0000644000176000001440000001274312076257551017237 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TSERIES_DATA_HPP #define TSERIES_DATA_HPP #include #include namespace tslib { template class TSdataSingleThreaded { private: bool release_data_; std::vector colnames_; TSDIM rows_; TSDIM cols_; TDATE* dates_; TDATA* data_; public: ~TSdataSingleThreaded(); TSdataSingleThreaded(); TSdataSingleThreaded(const TSdataSingleThreaded& t); TSdataSingleThreaded(const TSDIM rows, const TSDIM cols); TSdataSingleThreaded(TDATA* external_data, TDATE* external_dates, const TSDIM rows, const TSDIM cols, const bool release = false); TSdataSingleThreaded& operator=(const TSdataSingleThreaded& rhs); TSDIM nrow() const; TSDIM ncol() const; TDATA* getData() const; TDATE* getDates() const; void setColnames(const std::vector& cnames); std::vector getColnames() const; const size_t getColnamesSize() const; }; template TSdataSingleThreaded::~TSdataSingleThreaded() { if(release_data_) { delete []dates_; delete []data_; } } template TSdataSingleThreaded::TSdataSingleThreaded(): release_data_(true), rows_(0), cols_(0), dates_(NULL), data_(NULL) {} template TSdataSingleThreaded::TSdataSingleThreaded(const TSdataSingleThreaded& t): release_data_(true), colnames_(t.colnames_), rows_(t.rows_), cols_(t.cols_), dates_(new TDATE[t.rows_]), data_(new TDATA[t.rows_*t.cols_]) { std::copy(t.dates_, t.dates_ + rows_, dates_); std::copy(t.data_, t.data_ + t.rows_*t.cols_, data_); } template TSdataSingleThreaded::TSdataSingleThreaded(const TSDIM rows, const TSDIM cols): release_data_(true), rows_(rows), cols_(cols), dates_(new TDATE[rows]), data_(new TDATA[rows*cols]) {} template TSdataSingleThreaded::TSdataSingleThreaded(TDATA* external_data, TDATE* external_dates, const TSDIM nrows, const TSDIM ncols, const bool release): release_data_(release), rows_(nrows), cols_(ncols), dates_(external_dates), data_(external_data) {} template TSdataSingleThreaded& TSdataSingleThreaded::operator=(const TSdataSingleThreaded& rhs) { // release old data if(release_data_) { delete []dates_; delete []data_; } release_data_ = true; colnames_ = rhs.colnames_; rows_ = rhs.rows_; cols_ = rhs.cols_; dates_ = new TDATE[rhs.rows_]; data_ = new TDATA[rhs.rows_*rhs.cols_]; std::copy(rhs.dates_, rhs.dates_ + rhs.rows_, dates_); std::copy(rhs.data_, rhs.data_ + rhs.rows_*rhs.cols_, data_); return *this; } template void TSdataSingleThreaded::setColnames(const std::vector& cnames) { colnames_ = cnames; } template inline std::vector TSdataSingleThreaded::getColnames() const { return colnames_; } template inline const size_t TSdataSingleThreaded::getColnamesSize() const { return colnames_.size(); } template inline TDATA* TSdataSingleThreaded::getData() const { return data_; } template inline TDATE* TSdataSingleThreaded::getDates() const { return dates_; } template inline TSDIM TSdataSingleThreaded::nrow() const { return rows_; } template inline TSDIM TSdataSingleThreaded::ncol() const { return cols_; } } // namespace tslib #endif // TSERIES_DATA_HPP fts/src/tslib/tslib/ts.opps/0000755000176000001440000000000011176645141015533 5ustar ripleyusersfts/src/tslib/tslib/ts.opps/ts.ts.opp.hpp0000644000176000001440000001315411176645141020120 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TS_TS_OPP_HPP #define TS_TS_OPP_HPP #include #include #include #include #include namespace tslib { template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> apply_opp(const TSeries& lhs, const TSeries& rhs, opptype opp) { typedef typename Promotion::ResultT ResultT; if(lhs.ncol() != rhs.ncol()) return TSeries(); // find date intersection RangeSpecifier range(lhs.getDates(), rhs.getDates(), lhs.nrow(), rhs.nrow() ); if(!range.getSize()) return TSeries(); // allocate new answer TSeries ans(range.getSize(),lhs.ncol()); // copy over dates std::copy(range.getDates(),range.getDates()+range.getSize(),ans.getDates()); // set new colnames std::vector lhs_cnames = lhs.getColnames(); std::vector rhs_cnames = rhs.getColnames(); std::vector ans_cnames; if(lhs_cnames==rhs_cnames) { ans_cnames = lhs_cnames; } else { // loop through and combine colnames from lhs and rhs if(lhs_cnames.size() && rhs_cnames.size()) { for(size_t i = 0; i < lhs_cnames.size(); i++) { ans_cnames.push_back( lhs_cnames[i] + rhs_cnames[i] ); } } else { ans_cnames = lhs_cnames.size() ? lhs_cnames : rhs_cnames; } } ans.setColnames(ans_cnames); ResultT* ans_data = ans.getData(); TDATA1* lhs_data = lhs.getData(); TDATA2* rhs_data = rhs.getData(); for(TSDIM col = 0; col < lhs.ncol(); col++) { RangeIterator lhs_iter(lhs_data, range.getArg1()); RangeIterator rhs_iter(rhs_data, range.getArg2()); for(TSDIM i = 0; i < range.getSize(); i++) { ans_data[i] = opp( static_cast(*lhs_iter++), static_cast(*rhs_iter++)); } // increment column ans_data+= ans.nrow(); lhs_data+= lhs.nrow(); rhs_data+= rhs.nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const std::vector apply_boolean_opp(const TSeries& lhs, const TSeries& rhs, opptype opp) { typedef typename Promotion::ResultT ResultT; std::vector ans; if(lhs.ncol() != rhs.ncol()) return ans; // find date intersection RangeSpecifier range(lhs.getDates(), rhs.getDates(), lhs.nrow(), rhs.nrow() ); if(!range.getSize()) return ans; // allocate new answer ans.reserve(range.getSize()*lhs.ncol()); std::vector::iterator ans_data = ans.begin(); TDATA1* lhs_data = lhs.getData(); TDATA2* rhs_data = rhs.getData(); for(TSDIM col = 0; col < lhs.ncol(); col++) { RangeIterator lhs_iter(lhs_data, range.getArg1()); RangeIterator rhs_iter(rhs_data, range.getArg2()); for(TSDIM i = 0; i < range.getSize(); i++) { ans_data[i] = opp( static_cast(*lhs_iter++), static_cast(*rhs_iter++)); } // increment column ans_data += range.getSize(); lhs_data += lhs.nrow(); rhs_data += rhs.nrow(); } return ans; } } // namespace tslib #endif // TS_TS_OPP_HPP fts/src/tslib/tslib/ts.opps/ts.promotion.hpp0000644000176000001440000000442111176645141020720 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. // // // // 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 . // /////////////////////////////////////////////////////////////////////////// /* The following code example is taken from the book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #ifndef TS_PROMOTION_HPP #define TS_PROMOTION_HPP #include namespace tslib { // primary template for type promotion template class Promotion { public: typedef typename IfThenElse<(sizeof(T1)>sizeof(T2)), T1, typename IfThenElse<(sizeof(T1)::ResultT >::ResultT ResultT; }; // partial specialization for two identical types template class Promotion { public: typedef T ResultT; }; } //namespace tslib #endif // TS_PROMOTION_HPP fts/src/tslib/tslib/ts.opps/ifthenelse.hpp0000644000176000001440000000432511176645141020376 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. // // // // 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 . // /////////////////////////////////////////////////////////////////////////// /* The following code example is taken from the book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #ifndef IFTHENELSE_HPP #define IFTHENELSE_HPP // primary template: yield second or third argument depending on first argument template class IfThenElse; // partial specialization: true yields second argument template class IfThenElse { public: typedef Ta ResultT; }; // partial specialization: false yields third argument template class IfThenElse { public: typedef Tb ResultT; }; #endif // IFTHENELSE_HPP fts/src/tslib/tslib/ts.opps/ts.scalar.opp.hpp0000644000176000001440000001326511176645141020742 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TS_SCALAR_OPP_HPP #define TS_SCALAR_OPP_HPP #include #include namespace tslib { template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> apply_opp(const TDATA1 lhs_scalar, const TSeries& rhs_TSeries, opptype opp) { typedef typename Promotion::ResultT ResultT; // allocate new answer TSeries ans(rhs_TSeries.nrow(),rhs_TSeries.ncol()); // copy over dates std::copy(rhs_TSeries.getDates(),rhs_TSeries.getDates()+rhs_TSeries.nrow(),ans.getDates()); ResultT* ans_data = ans.getData(); TDATA2* rhs_TSeries_data = rhs_TSeries.getData(); for(TSDIM i = 0; i < rhs_TSeries.nrow()*rhs_TSeries.ncol(); i++) ans_data[i] = opp(static_cast(lhs_scalar),static_cast(rhs_TSeries_data[i])); return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> apply_opp(const TSeries& lhs_TSeries, const TDATA2 rhs_scalar, opptype opp) { typedef typename Promotion::ResultT ResultT; // allocate new answer TSeries ans(lhs_TSeries.nrow(),lhs_TSeries.ncol()); // copy over dates std::copy(lhs_TSeries.getDates(),lhs_TSeries.getDates()+lhs_TSeries.nrow(),ans.getDates()); ResultT* ans_data = ans.getData(); TDATA1* lhs_TSeries_data = lhs_TSeries.getData(); for(TSDIM i = 0; i < lhs_TSeries.nrow()*lhs_TSeries.ncol(); i++) ans_data[i] = opp(static_cast(lhs_TSeries_data[i]),static_cast(rhs_scalar)); return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const std::vector apply_boolean_opp(const TDATA1 lhs_scalar, const TSeries& rhs, opptype opp) { typedef typename Promotion::ResultT ResultT; std::vector ans; // allocate new answer ans.reserve(rhs.nrow()*rhs.ncol()); std::vector::iterator ans_data = ans.begin(); TDATA2* rhs_data = rhs.getData(); for(TSDIM i = 0; i < rhs.nrow() * rhs.ncol(); i++) ans_data[i] = opp(static_cast(lhs_scalar),static_cast(rhs_data[i])); return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, class opptype> const std::vector apply_boolean_opp(const TSeries& lhs, const TDATA2 rhs_scalar, opptype opp) { typedef typename Promotion::ResultT ResultT; std::vector ans; // allocate new answer ans.reserve(lhs.nrow()*lhs.ncol()); std::vector::iterator ans_data = ans.begin(); TDATA1* lhs_data = lhs.getData(); for(TSDIM i = 0; i < lhs.nrow() * lhs.ncol(); i++) ans_data[i] = opp(static_cast(lhs_data[i]),static_cast(rhs_scalar)); return ans; } } // namespace tslib #endif // TS_SCALAR_OPP_HPP fts/src/tslib/tslib/ts.opps/ts.opps.hpp0000644000176000001440000001440511176645141017656 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TS_OPPS_HPP #define TS_OPPS_HPP #include #include #include #define DEFINE_TS_TS_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> function_name(const TSeries& lhs, const TSeries& rhs) { \ return apply_opp(lhs,rhs,opp::ResultT>()); \ } #define DEFINE_TS_SCALAR_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> function_name(const TSeries& lhs, const TDATA2 rhs) { \ return apply_opp(lhs,rhs,opp::ResultT>()); \ } #define DEFINE_SCALAR_TS_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ TSeries::ResultT,TSDIM,TSDATABACKEND,DatePolicy> function_name(const TDATA1 lhs, const TSeries& rhs) { \ return apply_opp(lhs,rhs,opp::ResultT>()); \ } #define DEFINE_TS_TS_BOOL_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ std::vector function_name(const TSeries& lhs, const TSeries& rhs) { \ return apply_boolean_opp(lhs,rhs,opp::ResultT>()); \ } #define DEFINE_SCALAR_TS_BOOL_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ std::vector function_name(const TDATA1 lhs, const TSeries& rhs) { \ return apply_boolean_opp(lhs,rhs,opp::ResultT>()); \ } #define DEFINE_TS_SCALAR_BOOL_OPP(function_name,opp) \ template class TSDATABACKEND, template class DatePolicy> \ std::vector function_name(const TSeries& lhs, const TDATA2 rhs) { \ return apply_boolean_opp(lhs,rhs,opp::ResultT>()); \ } namespace tslib { // pre-declare template friends template class TSDATABACKEND, template class DatePolicy> class TSeries; // predeclaration for friend template template class TSDATABACKEND, template class DatePolicy> std::ostream& operator<<(std::ostream& os, const TSeries& ts); DEFINE_TS_TS_OPP(operator+,std::plus) DEFINE_TS_SCALAR_OPP(operator+,std::plus) DEFINE_SCALAR_TS_OPP(operator+,std::plus) DEFINE_TS_TS_OPP(operator-,std::minus) DEFINE_TS_SCALAR_OPP(operator-,std::minus) DEFINE_SCALAR_TS_OPP(operator-,std::minus) DEFINE_TS_TS_OPP(operator*,std::multiplies) DEFINE_TS_SCALAR_OPP(operator*,std::multiplies) DEFINE_SCALAR_TS_OPP(operator*,std::multiplies) DEFINE_TS_TS_OPP(operator/,std::divides) DEFINE_TS_SCALAR_OPP(operator/,std::divides) DEFINE_SCALAR_TS_OPP(operator/,std::divides) DEFINE_TS_TS_BOOL_OPP(operator==,std::equal_to) DEFINE_SCALAR_TS_BOOL_OPP(operator==,std::equal_to) DEFINE_TS_SCALAR_BOOL_OPP(operator==,std::equal_to) DEFINE_TS_TS_BOOL_OPP(operator!=,std::not_equal_to) DEFINE_SCALAR_TS_BOOL_OPP(operator!=,std::not_equal_to) DEFINE_TS_SCALAR_BOOL_OPP(operator!=,std::not_equal_to) DEFINE_TS_TS_BOOL_OPP(operator>,std::greater) DEFINE_SCALAR_TS_BOOL_OPP(operator>,std::greater) DEFINE_TS_SCALAR_BOOL_OPP(operator>,std::greater) DEFINE_TS_TS_BOOL_OPP(operator>=,std::greater_equal) DEFINE_SCALAR_TS_BOOL_OPP(operator>=,std::greater_equal) DEFINE_TS_SCALAR_BOOL_OPP(operator>=,std::greater_equal) DEFINE_TS_TS_BOOL_OPP(operator<,std::less) DEFINE_SCALAR_TS_BOOL_OPP(operator<,std::less) DEFINE_TS_SCALAR_BOOL_OPP(operator<,std::less) DEFINE_TS_TS_BOOL_OPP(operator<=,std::less_equal) DEFINE_SCALAR_TS_BOOL_OPP(operator<=,std::less_equal) DEFINE_TS_SCALAR_BOOL_OPP(operator<=,std::less_equal) } // namespace tslib #endif // TS_OPPS_HPP fts/src/tslib/tslib/date.policies/0000755000176000001440000000000012312322232016632 5ustar ripleyusersfts/src/tslib/tslib/date.policies/date.partition.hpp0000644000176000001440000000777112312322232022304 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef DATE_PARTITION #define DATE_PARTITION #include #include namespace tslib { template class DatePolicy> class yyyy { public: yyyy() {} T operator()(const T date, const int n) { int year = DatePolicy::year(date); return DatePolicy::toDate(year - year % n, 1, 1); } }; template class DatePolicy> class yyyyqq { public: yyyyqq() {} T operator()(const T date, const int n) { int adj_month = (static_cast((DatePolicy::month(date) - 1)/3) + 1) * 3 - 2; return DatePolicy::toDate(DatePolicy::year(date), adj_month - adj_month % n, 1); } }; template class DatePolicy> class yyyymm { public: yyyymm() {} T operator()(const T date, const int n) { int month = DatePolicy::month(date); return DatePolicy::toDate(DatePolicy::year(date), month - month % n, 1); } }; template class DatePolicy> class yyyymmdd { public: yyyymmdd() {} T operator()(const T date, const int n) { int day = DatePolicy::dayofmonth(date); return DatePolicy::toDate(DatePolicy::year(date), DatePolicy::month(date), day - day % n); } }; template class DatePolicy> class yyyymmddHH { public: yyyymmddHH() {} T operator()(const T date, const int n) { int hour = DatePolicy::hour(date); return DatePolicy::toDate(DatePolicy::year(date), DatePolicy::month(date), DatePolicy::dayofmonth(date), hour - hour % n); } }; template class DatePolicy> class yyyymmddHHMM { public: yyyymmddHHMM() {} T operator()(const T date, const int n) { int minute = DatePolicy::minute(date); return DatePolicy::toDate(DatePolicy::year(date), DatePolicy::month(date), DatePolicy::dayofmonth(date), DatePolicy::hour(date), minute - minute % n); } }; template class DatePolicy> class yyyymmddHHMMSS { public: yyyymmddHHMMSS() {} T operator()(const T date, const int n) { int second = DatePolicy::second(date); return DatePolicy::toDate(DatePolicy::year(date), DatePolicy::month(date), DatePolicy::dayofmonth(date), DatePolicy::hour(date), DatePolicy::minute(date), second - second % n); } }; template class DatePolicy> class yyyyww { public: yyyyww() {} T operator()(const T date, const int n) { return DatePolicy::AddDays(date,6 - DatePolicy::dayofweek(date)); } }; } // namespace tslib #endif // DATE_PARTITION fts/src/tslib/tslib/date.policies/julian.date.policy.hpp0000644000176000001440000000642412312113127023046 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef JULIAN_DATE_POLICY_HPP #define JULIAN_DATE_POLICY_HPP #include namespace tslib { template class JulianDate { private: //static const boost::gregorian::date fromRDate(const T x) { return boost::gregorian::date(1970,1,1) + boost::gregorian::date_duration(x); } static const boost::gregorian::date fromRDate(const T x) { return boost::gregorian::date(1970,1,1) + boost::gregorian::days(x); } static const T toRDate(const boost::gregorian::date x) { return static_cast(boost::gregorian::date_period(boost::gregorian::date(1970,1,1),x).length().days()); } public: //static const T toDate(const char* date, const char* format); static const T toDate(const int year, const int month, const int day, const int hour = 0, const int minute = 0, const int second = 0, const int millisecond = 0) { return toRDate(boost::gregorian::date(year, month, day)); } static const std::string toString(const T x, const char* format); static const int second(const T x) { return 0; } static const int minute(const T x) { return 0; } static const int hour(const T x) { return 0; } static const int dayofweek(const T x) { return static_cast(fromRDate(x).day_of_week()); } static const int dayofmonth(const T x) { return static_cast(fromRDate(x).day()); } static const int month(const T x) { return static_cast(fromRDate(x).month()); } static const int year(const T x) { return static_cast(fromRDate(x).year()); } static const int last_day_of_month(const T x) { return toRDate(fromRDate(x).end_of_month()); } static const T AddYears(const T x, const int n) { return toRDate(fromRDate(x) + boost::gregorian::years(n)); } static const T AddMonths(const T x, const int n) { return toRDate(fromRDate(x) + boost::gregorian::months(n)); } static const T AddDays(const T x, const int n) { return toRDate(fromRDate(x) + boost::gregorian::days(n)); } static const double daily_distance(const T x, const T y) { return x - y; } }; } // namespace tslib #endif // JULIAN_DATE_POLICY_HPP fts/src/tslib/tslib/date.policies/posix.date.policy.hpp0000644000176000001440000002346311240355401022732 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef POSIX_DATE_POLICY_HPP #define POSIX_DATE_POLICY_HPP #include #include namespace tslib { template class PosixDate { private: static void to_time_tm(struct tm& posix_time_tm, const T x); static void check_day_of_month(struct tm& posix_time_tm); // needs to check for leapyears too static const int dst_shift_check(const T ans,const T x); // returns seconds from original hour and minute that has occurred static const bool is_leap_year(const int year); public: static const T toDate(const char* date, const char* format); static const T toDate(const int year, const int month, const int day, const int hour = 0, const int minute = 0, const int second = 0, const int millisecond = 0); static const std::string toString(const T x, const char* format); static const int second(const T x); static const int minute(const T x); static const int hour(const T x); static const int dayofweek(const T x); static const int dayofmonth(const T x); static const int month(const T x); static const int year(const T x); static const int last_day_of_month(const T x); static const T AddYears(const T x, const int n); static const T AddMonths(const T x, const int n); static const T AddDays(const T x, const int n); static const double daily_distance(const T x, const T y); }; template void PosixDate::to_time_tm(struct tm& posix_time_tm, const T x) { const time_t posix_time_t = static_cast(x); #ifdef WIN32 memcpy(static_cast(&posix_time_tm),localtime(&posix_time_t), sizeof(struct tm)); #else localtime_r(&posix_time_t,&posix_time_tm); #endif } // does not check for negative months, only running off the back of a month template void PosixDate::check_day_of_month(struct tm& posix_time_tm) { if(posix_time_tm.tm_mday < 28) { return; } // tm_mon is 0 to 11 switch(posix_time_tm.tm_mon + 1) { // case for Apr, June, Sep, Nov (30 day months) case 4: case 6: case 9: case 11: posix_time_tm.tm_mday = (posix_time_tm.tm_mday > 30) ? 30 : posix_time_tm.tm_mday; break; /* Do we need these cases? there is no way of creating a day of month 32 from the methods that would call this check, so don't do it. // case for Jan, March, May, July, Aug, Oct, Dec case 1: case 3: case 5: case 7: case 8: case 10: case 12: posix_time_tm.tm_mday = (posix_time_tm.tm_mday > 31) ? 31 : posix_time_tm.tm_mday; break; */ // special case for feb case 2: if(is_leap_year(posix_time_tm.tm_year + 1900)) { posix_time_tm.tm_mday = (posix_time_tm.tm_mday > 29) ? 29 : posix_time_tm.tm_mday; } else { posix_time_tm.tm_mday = (posix_time_tm.tm_mday > 28) ? 28 : posix_time_tm.tm_mday; } break; } } template const int PosixDate::dst_shift_check(const T shifted, const T original) { struct tm original_time_tm, shifted_time_tm; to_time_tm(original_time_tm, original); to_time_tm(shifted_time_tm, shifted); // hour = 60s/min * 60min = 3600 seconds int ans = (original_time_tm.tm_hour - shifted_time_tm.tm_hour) * 3600; // some zones have half hour shifts ans += (original_time_tm.tm_min - shifted_time_tm.tm_min) * 60; return ans; } // takes a year in the form YYYY // so you must add 1900 to tm_year before calling this func template const bool PosixDate::is_leap_year(const int year) { int mod_4 = year % 4; int mod_100 = year % 100; int mod_400 = year % 400; // mod_400 or mod_4 but not mod_100 return (mod_400 == 0 || (mod_4 && !(mod_100) ) ) ? 1 : 0; } #ifndef WIN32 /* strptime not available on windows */ template const T PosixDate::toDate(const char* date, const char* format) { struct tm posix_time_tm; memset(&posix_time_tm, '\0', sizeof(struct tm)); strptime(date,format,&posix_time_tm); posix_time_tm.tm_isdst = -1; return static_cast(mktime(&posix_time_tm)); } #endif template const T PosixDate::toDate(const int year, const int month, const int day, const int hour, const int minute, const int second, const int millisecond) { struct tm localtime_tm; // init struct memset(&localtime_tm, '\0', sizeof(struct tm)); // for years, 1970 is 70 localtime_tm.tm_year = year - 1900; // months are 0 to 11 localtime_tm.tm_mon = month - 1; // day of month is 1 to 31 localtime_tm.tm_mday = day; localtime_tm.tm_hour = hour; localtime_tm.tm_min = minute; localtime_tm.tm_sec = second; // have to do this so mktime will fix the dst field // do not remove this (it works) localtime_tm.tm_isdst = -1; // convert to POSIXct return static_cast(mktime(&localtime_tm)) + static_cast(millisecond/1000.0); } template const std::string PosixDate::toString(const T x, const char* format) { struct tm posix_time_tm; const int BUFFSIZE = 32; char ans_char[BUFFSIZE]; to_time_tm(posix_time_tm, x); strftime(ans_char,BUFFSIZE,format,&posix_time_tm); return std::string(ans_char); } template const int PosixDate::second(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_sec; } template const int PosixDate::minute(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_min; } template const int PosixDate::hour(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_hour; } template const int PosixDate::dayofweek(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_wday; // days since sunday 0 to 6 } template const int PosixDate::dayofmonth(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_mday; // no adjustment, it's already 1 to 31 } template const int PosixDate::month(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_mon + 1; // posix is 0 to 11, we want 1 to 12 } template const int PosixDate::year(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); return posix_time_tm.tm_year + 1900; // we want actual year instead of years since 1900 } template const int PosixDate::last_day_of_month(const T x) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); switch(posix_time_tm.tm_mon + 1) { // case for Apr, June, Sep, Nov (30 day months) case 4: case 6: case 9: case 11: return 30; break; // case for Jan, March, May, July, Aug, Oct, Dec case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; break; // special case for feb case 2: if(is_leap_year(posix_time_tm.tm_year + 1900)) { return 29; } else { return 28; } break; } } template const T PosixDate::AddYears(const T x, const int n) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); // adjust years posix_time_tm.tm_year+=n; // make sure we drop out Feb 29 if we go from leapyear to non-leapyear check_day_of_month(posix_time_tm); // convert to POSIXct return static_cast(mktime(&posix_time_tm)); } template const T PosixDate::AddMonths(const T x, const int n) { struct tm posix_time_tm; to_time_tm(posix_time_tm, x); int yrs_to_add = n / 12; // adjust years posix_time_tm.tm_year += yrs_to_add; // adjust months to add //n = ( std::abs(n) % 12 ) * std::sign(n); // adjust months posix_time_tm.tm_mon += (n % 12); // check day of month check_day_of_month(posix_time_tm); // because we can cross a DST boundry posix_time_tm.tm_isdst = -1; // convert to POSIXct return static_cast(mktime(&posix_time_tm)); } template const T PosixDate::AddDays(const T x, const int n) { // one day is 60*60*24 seconds = 86400 const int seconds_in_day = 86400; T ans = x + (seconds_in_day * n); // do DST shift check int shift_error = dst_shift_check(ans,x); return ans + shift_error; } template const double PosixDate::daily_distance(const T x, const T y) { const long seconds_in_day = 60*60*24; return (x - y)/seconds_in_day; } } // namespace tslib #endif // POSIX_DATE_POLICY_HPP fts/src/tslib/tslib/tseries.hpp0000644000176000001440000005211012317330726016311 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TSERIES_HPP #define TSERIES_HPP #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace tslib { class TSeriesError : public std::runtime_error { public: TSeriesError(const std::string& msg = "") : std::runtime_error(msg) {} }; template class TSDATABACKEND, template class DatePolicy> class TSeries { private: TSDATABACKEND tsdata_; const TSDIM offset(const TSDIM row, const TSDIM col) const { return row + col*nrow(); } public: // ctors dtors TSeries(); TSeries(TSDATABACKEND& tsdata); TSeries(const TSDIM rows, const TSDIM cols); TSeries(const TSeries& T); TSeries(TDATA* external_data, TDATE* external_dates, const TSDIM nrows, const TSDIM ncols, const bool release); // accessors const TSDATABACKEND* getIMPL() const; std::vector getColnames() const; const TSDIM nrow() const; const TSDIM ncol() const; TDATA* getData() const; TDATE* getDates() const; // mutators int setColnames(const std::vector& cnames); // transforms template class F> const TSeries window(const size_t window) const; template class F, template class> class PFUNC> const TSeries time_window(const int n = 1) const; template class F> const TSeries transform() const; template class F, typename T> const TSeries transform_1arg(T arg1) const; // frequency conversion (only highfreq to lowfreq conversion) template class> class PFUNC> const TSeries freq(const int n = 1) const; // subsets template const TSeries row_subset(T beg, T end) const; // pad template const TSeries pad(T beg, T end) const; //operators TSeries& operator=(const TSeries& x); TSeries& operator=(const TDATA x); // lag lead const TSeries operator() (const TSDIM n) const; const TSeries lag(const TSDIM n) const; const TSeries lead(const TSDIM n) const; const TSeries diff(const TSDIM n) const; // matix index const TDATA operator() (const TSDIM row, const TSDIM col) const; TDATA& operator() (const TSDIM row, const TSDIM col); friend std::ostream& operator<< <> (std::ostream& os, const TSeries& ts); }; template class TSDATABACKEND, template class DatePolicy> TSeries::TSeries() {} template class TSDATABACKEND, template class DatePolicy> TSeries::TSeries(TSDATABACKEND& tsdata): tsdata_(tsdata) {} template class TSDATABACKEND, template class DatePolicy> TSeries::TSeries(const TSDIM rows, const TSDIM cols): tsdata_(rows,cols) {} template class TSDATABACKEND, template class DatePolicy> TSeries::TSeries(const TSeries& T): tsdata_(T.tsdata_) {} template class TSDATABACKEND, template class DatePolicy> TSeries::TSeries(TDATA* external_data, TDATE* external_dates, const TSDIM nrows, const TSDIM ncols, const bool release): tsdata_(external_data, external_dates, nrows, ncols, release) {} template class TSDATABACKEND, template class DatePolicy> inline const TSDATABACKEND* TSeries::getIMPL() const { return &tsdata_; } template class TSDATABACKEND, template class DatePolicy> TSeries& TSeries::operator=(const TSeries& rhs) { // self assignment if(this == &rhs) { return *this; } // assign to new data tsdata_ = rhs.tsdata_; return *this; } template class TSDATABACKEND, template class DatePolicy> TSeries& TSeries::operator=(const TDATA rhs) { TDATA* data = getData(); for(TSDIM i = 0; i < nrow()*ncol(); i++) { data[i] = rhs; } return *this; } template class TSDATABACKEND, template class DatePolicy> const TSeries TSeries::operator() (const TSDIM n) const { if( n > 0 ) { return lag(n); } else if( n < 0) { return lead(abs(n)); } return *this; } template class TSDATABACKEND, template class DatePolicy> const TSeries TSeries::lag(const TSDIM n) const { if(n >= nrow()) { throw std::logic_error("lag: n > nrow of time series."); } const TSDIM new_size = nrow() - n; TSeries ans(new_size, ncol()); TDATA* ans_data = ans.getData(); const TDATA* data = getData(); // copy over dates std::copy(getDates() + n, getDates() + n + new_size, ans.getDates()); // set new colnames ans.setColnames(getColnames()); for(TSDIM c = 0; c < ncol(); c++) { std::copy(data, data + new_size, ans_data); ans_data += ans.nrow(); data += nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy> const TSeries TSeries::lead(const TSDIM n) const { if(n >= nrow()) { throw std::logic_error("lead: n > nrow of time series."); } const TSDIM new_size = nrow() - n; TSeries ans(new_size, ncol()); TDATA* ans_data = ans.getData(); const TDATA* data = getData(); // copy over dates std::copy(getDates(), getDates() + new_size, ans.getDates()); // set new colnames ans.setColnames(getColnames()); for(TSDIM c = 0; c < ncol(); c++) { std::copy(data + n, data + n + new_size, ans_data); ans_data += ans.nrow(); data += nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy> const TSeries TSeries::diff(const TSDIM n) const { if(n >= nrow()) { throw std::logic_error("diff: n > nrow of time series."); } const TSDIM new_size = nrow() - n; TSeries ans(new_size, ncol()); TDATA* ans_data = ans.getData(); const TDATA* data = getData(); // copy over dates std::copy(getDates() + n, getDates() + n + new_size, ans.getDates()); // set new colnames ans.setColnames(getColnames()); for(TSDIM c = 0; c < ncol(); c++) { for(TSDIM r = n; r < nrow(); r++) { if(numeric_traits::ISNA(data[r]) || numeric_traits::ISNA(data[r-n])) { ans_data[r-n] = numeric_traits::NA(); } else { ans_data[r-n] = data[r] - data[r-n]; } } ans_data += ans.nrow(); data += nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy> const TDATA TSeries::operator() (const TSDIM row, const TSDIM col) const { const TDATA* data = getData(); return data[offset(row, col)]; } template class TSDATABACKEND, template class DatePolicy> TDATA& TSeries::operator() (const TSDIM row, const TSDIM col) { TDATA* data = getData(); return data[offset(row, col)]; } template class TSDATABACKEND, template class DatePolicy> inline TDATE* TSeries::getDates() const { return tsdata_.getDates(); } template class TSDATABACKEND, template class DatePolicy> inline TDATA* TSeries::getData() const { return tsdata_.getData(); } template class TSDATABACKEND, template class DatePolicy> inline const TSDIM TSeries::nrow() const { return tsdata_.nrow(); } template class TSDATABACKEND, template class DatePolicy> inline const TSDIM TSeries::ncol() const { return tsdata_.ncol(); } template class TSDATABACKEND, template class DatePolicy> inline std::vector TSeries::getColnames() const { return tsdata_.getColnames(); } template class TSDATABACKEND, template class DatePolicy> int TSeries::setColnames(const std::vector& cnames) { if(static_cast(cnames.size()) == ncol()) { tsdata_.setColnames(cnames); return 0; // SUCCESS } else { return 1; // FAILURE } } template class TSDATABACKEND, template class DatePolicy> template class F> const TSeries TSeries::window(const size_t window) const { // allocate new answer TSeries ans(nrow() - (window - 1), ncol()); // copy over dates std::copy(getDates() + (window - 1), getDates()+nrow(), ans.getDates()); // set new colnames ans.setColnames(getColnames()); ReturnType* ans_data = ans.getData(); TDATA* data = getData(); for(TSDIM col = 0; col < ncol(); col++) { windowApply::apply(ans_data, data, data + nrow(), window); ans_data += ans.nrow(); data += nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy> template class F, template class> class PFUNC> const TSeries TSeries::time_window(const int n) const { // pre-allocate vector for transformed dates typename std::vector partitions; partitions.resize(nrow()); TDATE* dts = getDates(); // transform dates for(TSDIM row = 0; row < nrow(); row++) { partitions[row] = PFUNC()(dts[row],n); } //std::transform(getDates(), getDates() + nrow(), partitions.begin(), std::bind2nd(PFUNC(), n)); // vector for selected rows std::vector ans_rows; breaks(partitions.begin(),partitions.end(),std::back_inserter(ans_rows)); TSeries ans(ans_rows.size(), ncol()); ans.setColnames(getColnames()); TDATE* dates = getDates(); TDATE* ans_dates = ans.getDates(); for(size_t i = 0; i < ans_rows.size(); i++) { ans_dates[i] = dates[ans_rows[i]]; } ReturnType* ans_data = ans.getData(); TDATA* data = getData(); for(TSDIM ans_col = 0; ans_col < ans.ncol(); ans_col++, data+=nrow()) { size_t range_start = 0; for(size_t i = 0; i < ans_rows.size(); i++) { ans_data[ans.offset(i, ans_col)] = F::apply(data + range_start, data + ans_rows[i] + 1); range_start = ans_rows[i] + 1; } } return ans; } template class TSDATABACKEND, template class DatePolicy> template class F> const TSeries TSeries::transform() const { // allocate new answer TSeries ans(nrow(), ncol()); // copy over dates std::copy(getDates(),getDates()+nrow(),ans.getDates()); // set new colnames ans.setColnames(getColnames()); ReturnType* ans_data = ans.getData(); TDATA* data = getData(); for(TSDIM col = 0; col < ncol(); col++) { F::apply(ans_data, data, data + nrow()); ans_data += ans.nrow(); data += nrow(); } return ans; } template class TSDATABACKEND, template class DatePolicy> template class F, typename T> const TSeries TSeries::transform_1arg(T arg1) const { // allocate new answer TSeries ans(nrow(), ncol()); // copy over dates std::copy(getDates(),getDates()+nrow(),ans.getDates()); // set new colnames ans.setColnames(getColnames()); ReturnType* ans_data = ans.getData(); TDATA* data = getData(); for(TSDIM col = 0; col < ncol(); col++) { F::apply(ans_data, data, data + nrow(), arg1); ans_data += ans.nrow(); data += nrow(); } return ans; } // this is for a positive row subset (positive and negative rowsets cannot mix) template class TSDATABACKEND, template class DatePolicy> template const TSeries TSeries::row_subset(T beg, T end) const { TSDIM new_nrow = static_cast( std::distance(beg,end) ); TSDIM new_ncol = ncol(); // allocate new answer TSeries ans(new_nrow, new_ncol); // copy over colnames ans.setColnames(getColnames()); TDATE* dates = getDates(); TDATA* data = getData(); TDATE* ans_dates = ans.getDates(); TDATA* ans_data = ans.getData(); TSDIM ans_index = 0; while(beg!=end) { ans_dates[ans_index] = dates[*beg]; for(TSDIM c = 0; c < ncol(); c++) { ans_data[ans.offset(ans_index,c)] = data[offset(*beg,c)]; } ++beg; ++ans_index; } return ans; } // this is for a positive row subset (positive and negative rowsets cannot mix) template class TSDATABACKEND, template class DatePolicy> template const TSeries TSeries::pad(T beg, T end) const { std::set new_dts; // add existing dates for(TDATE* d = getDates(); d < getDates() + nrow(); d++) { new_dts.insert(*d); } // add new dates while(beg!=end) { new_dts.insert(static_cast(*beg++)); } // allocate new answer TSeries ans(new_dts.size(), ncol()); // copy colnames ans.setColnames(getColnames()); // init dates TDATE* dts = ans.getDates(); for(typename std::set::iterator iter = new_dts.begin(); iter != new_dts.end(); iter++) { *dts++ = *iter; } // init to NA for(TSDIM i = 0; i < ans.nrow() * ans.ncol(); i++) { ans.getData()[i] = numeric_traits::NA(); } RangeSpecifier range(getDates(),ans.getDates(),nrow(),ans.nrow()); const TSDIM* r1 = range.getArg1(); const TSDIM* r2 = range.getArg2(); TDATA* ans_data = ans.getData(); TDATA* this_data = getData(); for(TSDIM col = 0; col < ans.ncol(); col++) { for(TSDIM i = 0; i < range.getSize(); i++) { ans_data[ans.offset(r2[i],col)] = this_data[offset(r1[i],col)]; } } return ans; } template class TSDATABACKEND, template class DatePolicy> template class> class PFUNC> const TSeries TSeries::freq(const int n) const { // pre-allocate vector for transformed dates typename std::vector partitions; partitions.resize(nrow()); // transform dates TDATE* dts = getDates(); for(TSDIM row = 0; row < nrow(); row++) { partitions[row] = PFUNC()(dts[row],n); } //std::transform(getDates(), getDates() + nrow(), partitions.begin(), std::bind2nd(PFUNC, n)); // vector for selected rows std::vector ans_rows; breaks(partitions.begin(),partitions.end(),std::back_inserter(ans_rows)); return row_subset(ans_rows.begin(), ans_rows.end()); } } // namespace tslib #endif // TSERIES_HPP fts/src/tslib/tslib/range.specifier/0000755000176000001440000000000012317326347017173 5ustar ripleyusersfts/src/tslib/tslib/range.specifier/range.iterator.hpp0000644000176000001440000001335411176645141022634 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RANGE_ITERATOR_HPP #define RANGE_ITERATOR_HPP #include namespace tslib { using std::iterator_traits; template class RangeIterator { private: const DATAPOINTER data_pointer_; INDEXPOINTER index_pointer_; public: typedef std::random_access_iterator_tag iterator_category; typedef typename std::iterator_traits::value_type value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type* iterator; typedef const value_type* const_iterator; typedef value_type& reference; typedef const value_type& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; RangeIterator(const DATAPOINTER data_pointer, const INDEXPOINTER index_pointer); RangeIterator(const RangeIterator& r); RangeIterator& operator++(); RangeIterator operator++(const int i); RangeIterator& operator--(); RangeIterator operator--(const int i); RangeIterator& operator+=(const int i); RangeIterator& operator-=(const int i); RangeIterator operator+(const int i) const; RangeIterator operator-(const int i) const; typename std::iterator_traits::value_type operator*(); friend bool operator==(RangeIterator& lhs, RangeIterator& rhs) { return (lhs.data_pointer_ == rhs.data_pointer_) && (lhs.index_pointer_ == rhs.index_pointer_); } friend bool operator!=(RangeIterator& lhs, RangeIterator& rhs) { return (lhs.data_pointer_ != rhs.data_pointer_) || (lhs.index_pointer_ != rhs.index_pointer_); } friend difference_type operator-(RangeIterator& lhs, RangeIterator& rhs) { return (lhs.index_pointer_ - rhs.index_pointer_); } }; template RangeIterator::RangeIterator(const DATAPOINTER data_pointer, const INDEXPOINTER index_pointer) : data_pointer_(data_pointer), index_pointer_(index_pointer) { } template inline RangeIterator::RangeIterator(const RangeIterator& r) : data_pointer_(r.data_pointer_), index_pointer_(r.index_pointer_) { } template inline RangeIterator& RangeIterator::operator++() { ++index_pointer_; return *this; } template inline RangeIterator RangeIterator::operator++(const int i) { RangeIterator tmp(*this); ++*this; return tmp; } template inline RangeIterator& RangeIterator::operator--() { --index_pointer_; return *this; } template inline RangeIterator RangeIterator::operator--(const int i) { RangeIterator tmp(*this); --*this; return tmp; } template inline RangeIterator& RangeIterator::operator+=(const int i) { index_pointer_ += i; return *this; } template inline RangeIterator& RangeIterator::operator-=(const int i) { index_pointer_ -= i; return *this; } template inline RangeIterator RangeIterator::operator+(const int i) const { return RangeIterator(data_pointer_, index_pointer_ + i); } template inline RangeIterator RangeIterator::operator-(const int i) const { return RangeIterator(data_pointer_, index_pointer_ - i); } template inline typename std::iterator_traits::value_type RangeIterator::operator*() { return data_pointer_[ *index_pointer_ ]; } } // namespace tslib #endif // RANGE_ITERATOR_HPP fts/src/tslib/tslib/range.specifier/rangeSpecifier.hpp0000644000176000001440000001077112317325726022640 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RANGESPECIFIER_HPP #define RANGESPECIFIER_HPP namespace tslib { // template friend must be pre-declared template class RangeSpecifier; template std::ostream& operator<< (std::ostream& os, const RangeSpecifier& rs); template class RangeSpecifier { private: T* dates_; // intersection dates_ U* index1_; // index of intersections of index1_ U* index2_; // index of intersections of index2_ U size_; // also the length of all the internal vectors: dates_, index1_, index2_ public: ~RangeSpecifier(); RangeSpecifier(const RangeSpecifier &r); // not allowed!! RangeSpecifier(T *dates_1, T *dates_2, const U length_index1_, const U length_index2_); const T* getDates() const; const U* getArg1() const; const U* getArg2() const; const U getSize() const; friend std::ostream& operator<< <> (std::ostream& os, const RangeSpecifier& rs); }; template RangeSpecifier::~RangeSpecifier() { delete [] dates_; delete [] index1_; delete [] index2_; } template RangeSpecifier::RangeSpecifier(T *dates_1, T *dates_2, const U length_index1_, const U length_index2_) { // find size of smaller of the two arguments const U bufferSize = length_index1_ < length_index2_ ? length_index1_ : length_index2_; dates_ = new T[bufferSize]; // find size of date intersection T* dates_end = std::set_intersection(dates_1, dates_1+length_index1_, dates_2, dates_2+length_index2_, dates_); size_ = std::distance(dates_,dates_end); // if there is no intersection then specifier has no size, and elements should be set to null // must delete buffer of dates_ that we allocated if(size_==0) { delete []dates_; index1_ = NULL; index2_ = NULL; dates_ = NULL; } // since we have some dates_ in the intersection // we can alloc space for the intersection points index1_ = new U[size_]; index2_ = new U[size_]; // placeholders to find intersecting dates_ U date1_index = 0; U date2_index = 0; U dates_index = 0; // go through all the dates_ in the intersection while(dates_index < size_) { // catch up arg 1 to dates_ intersection while(dates_[dates_index] != dates_1[date1_index]) { date1_index++; } // catch up arg 2 to dates_ intersection while(dates_[dates_index] != dates_2[date2_index]) { date2_index++; } // when equal, record position of matching elements if(dates_[dates_index] == dates_1[date1_index] && dates_[dates_index] == dates_2[date2_index]) { index1_[dates_index] = date1_index; index2_[dates_index] = date2_index; dates_index++; date1_index++; date2_index++; } } } template const U RangeSpecifier::getSize() const { return size_; } template const T* RangeSpecifier::getDates() const { return dates_; } template const U* RangeSpecifier::getArg1() const { return index1_; } template const U* RangeSpecifier::getArg2() const { return index2_; } } // namespace tslib #endif fts/src/tslib/tslib/vector.transform/0000755000176000001440000000000013346662421017442 5ustar ripleyusersfts/src/tslib/tslib/vector.transform/since.na.hpp0000644000176000001440000000421711176645141021654 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef SINCE_NA_HPP #define SINCE_NA_HPP #include namespace tslib { template class SinceNA { public: template static inline void apply(T dest, U beg, U end) { typedef typename std::iterator_traits::value_type dest_type; dest_type count(0); // while no NA is found at all in the tseries then -1 while(beg != end && !numeric_traits::value_type>::ISNA(*beg) ) { *dest = static_cast(-1); ++beg; ++dest; } // if we get here, then an NA has been found while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { *dest = static_cast(0); count = 0; } else { *dest = count; } ++count; ++beg; ++dest; } } }; } // namespace tslib #endif // SINCE_NA_HPP fts/src/tslib/tslib/vector.transform/fill.traits.hpp0000644000176000001440000000304011176645141022402 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef FILL_TRAITS_HPP #define FILL_TRAITS_HPP template class fillTraits; template<> class fillTraits { public: typedef double ReturnType; typedef double ArgType; // for fillValue }; template<> class fillTraits { public: typedef int ReturnType; typedef int ArgType; // for fillValue }; #endif // FILL_TRAITS_HPP fts/src/tslib/tslib/vector.transform/fill.value.hpp0000644000176000001440000000336111176645141022216 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef FILL_VALUE_HPP #define FILL_VALUE_HPP #include namespace tslib { template class FillValue { public: template static inline void apply(T dest, U beg, U end, V value) { while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { *dest = static_cast< typename std::iterator_traits::value_type >(value); } else { *dest = *beg; } ++beg; ++dest; } } }; } // namespace tslib #endif // FILL_VALUE_HPP fts/src/tslib/tslib/vector.transform/diff.hpp0000644000176000001440000000331211176645141021061 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef DIFF_HPP #define DIFF_HPP #include #include namespace tslib { template class Diff { public: template static inline void apply(T dest, U beg, U end) { // set dest[0] to NA *dest++ = numeric_traits< typename std::iterator_traits::value_type >::NA(); ++beg; while(beg != end) { *dest = *beg - *(beg-1); beg++; dest++; } } }; } // namespace tslib #endif // DIFF_HPP fts/src/tslib/tslib/vector.transform/ema.hpp0000644000176000001440000000427311176645141020722 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef EMA_HPP #define EMA_HPP #include #include namespace tslib { template class EMA { public: template static inline void apply(T dest, U beg, U end, V periods) { const double p = static_cast(periods); ReturnType initial_value = Mean::apply(beg,beg+periods); // fill with NA until we have initial window int initial_count = 0; while(initial_count < (periods - 1) && beg != end) { *dest++ = numeric_traits::NA(); ++beg; ++initial_count; } *dest++ = initial_value; ++beg; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { *dest = numeric_traits::value_type>::NA(); } else { *dest = (*(dest-1) * (p - 1.0) + *beg)/p; } ++beg; ++dest; } } }; } // namespace tslib #endif // EMA_HPP fts/src/tslib/tslib/vector.transform/lag.lead.traits.hpp0000644000176000001440000000305711176645141023133 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef LAG_LEAD_TRAITS_HPP #define LAG_LEAD_TRAITS_HPP template class lagleadTraits; template<> class lagleadTraits { public: typedef double ReturnType; typedef int ArgType; // for periods }; template<> class lagleadTraits { public: typedef int ReturnType; typedef int ArgType; // for periods }; #endif // LAG_LEAD_TRAITS_HPP fts/src/tslib/tslib/vector.transform/fill.bwd.hpp0000644000176000001440000000405412317326022021646 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef FILL_BWD_HPP #define FILL_BWD_HPP #include namespace tslib { template class FillBwd { public: template static inline void apply(T dest, U beg, U end) { // have to find offset to start from back typename std::iterator_traits::difference_type len = std::distance(beg,end); // push beg off end of array since we are comming towards it --beg; // shift dest to element N-1 dest += (len - 1); // end is beyond array right now --end; // set last element to value of end *dest-- = *end--; while(end != beg) { if(numeric_traits::value_type>::ISNA(*end)) { *dest = *(dest + 1); } else { *dest = *end; } --dest; --end; } } }; } // namespace tslib #endif // FILL_BWD_HPP fts/src/tslib/tslib/vector.transform/expanding.maximum.hpp0000644000176000001440000000371512312111327023574 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef EXPANDING_MAXIMUM_HPP #define EXPANDING_MAXIMUM_HPP #include namespace tslib { template class ExpandingMaximum { public: template static inline void apply(T dest, U beg, U end) { // fill with NA until we have values while(numeric_traits::value_type>::ISNA(*beg) && beg != end) { *dest++ = numeric_traits::NA(); ++beg; } // init first value ReturnType running_max = *beg++; *dest++ = running_max; while(beg != end) { running_max = std::max(*beg,running_max); *dest = running_max; ++beg; ++dest; } } }; } // namespace tslib #endif // EXPANDING_MAXIMUM_HPP fts/src/tslib/tslib/vector.transform/ema.traits.hpp0000644000176000001440000000302711176645141022223 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef EMA_TRAITS_HPP #define EMA_TRAITS_HPP template class emaTraits; template<> class emaTraits { public: typedef double ReturnType; typedef int ArgType; // for periods }; template<> class emaTraits { public: typedef double ReturnType; typedef int ArgType; // for periods }; #endif // EMA_TRAITS_HPP fts/src/tslib/tslib/vector.transform/since.na.traits.hpp0000644000176000001440000000273711176645141023166 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef SINCE_NA_TRAITS_HPP #define SINCE_NA_TRAITS_HPP template class SinceNATraits; template<> class SinceNATraits { public: typedef int ReturnType; }; template<> class SinceNATraits { public: typedef int ReturnType; }; #endif // SINCE_NA_TRAITS_HPP fts/src/tslib/tslib/vector.transform/expanding.minimum.hpp0000644000176000001440000000371512312111267023575 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef EXPANDING_MINIMUM_HPP #define EXPANDING_MINIMUM_HPP #include namespace tslib { template class ExpandingMinimum { public: template static inline void apply(T dest, U beg, U end) { // fill with NA until we have values while(numeric_traits::value_type>::ISNA(*beg) && beg != end) { *dest++ = numeric_traits::NA(); ++beg; } // init first value ReturnType running_max = *beg++; *dest++ = running_max; while(beg != end) { running_max = std::min(*beg,running_max); *dest = running_max; ++beg; ++dest; } } }; } // namespace tslib #endif // EXPANDING_MINIMUM_HPP fts/src/tslib/tslib/vector.transform/fill.fwd.hpp0000644000176000001440000000334411176645141021663 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef FILL_FWD_HPP #define FILL_FWD_HPP #include namespace tslib { template class FillFwd { public: template static inline void apply(T dest, U beg, U end) { // nothing we can do about elelment [0] *dest++ = *beg++; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { *dest = *(dest - 1); } else { *dest = *beg; } ++beg; ++dest; } } }; } // namespace tslib #endif // FILL_FWD_HPP fts/src/tslib/tslib/vector.summary/0000755000176000001440000000000013346662421017124 5ustar ripleyusersfts/src/tslib/tslib/vector.summary/prod.hpp0000644000176000001440000000371011176645141020601 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef PROD_HPP #define PROD_HPP #include #include namespace tslib { template class prodTraits; template<> class prodTraits { public: typedef double ReturnType; }; template<> class prodTraits { public: typedef int ReturnType; }; template class Prod { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = static_cast( 1 ); while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans *= *beg; ++beg; } return ans; } }; } // namespace tslib #endif // PROD_HPP fts/src/tslib/tslib/vector.summary/contains.na.hpp0000644000176000001440000000315711176645141022055 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef CONTAINS_NA_HPP #define CONTAINS_NA_HPP #include #include namespace tslib { template static inline bool containsNA(T beg, T end) { while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return true; } ++beg; } return false; }; } // namespace tslib #endif // CONTAINS_NA_HPP fts/src/tslib/tslib/vector.summary/mean.hpp0000644000176000001440000000377511176645141020570 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef MEAN_HPP #define MEAN_HPP #include #include namespace tslib { template class meanTraits; template<> class meanTraits { public: typedef double ReturnType; }; template<> class meanTraits { public: typedef double ReturnType; }; template class Mean { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 0; ReturnType len = static_cast(std::distance(beg,end)); while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans += *beg; ++beg; } return ans/len; } }; } // namespace tslib #endif // MEAN_HPP fts/src/tslib/tslib/vector.summary/cor.hpp0000644000176000001440000000414511176645141020423 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef COR_HPP #define COR_HPP #include #include #include namespace tslib { template class corTraits; template<> class corTraits { public: typedef double ReturnType; }; template<> class corTraits { public: typedef double ReturnType; }; template class Cor { public: template static inline ReturnType apply(T x_beg, T x_end, T y_beg, T y_end) { ReturnType xy_cov = Cov::apply(x_beg, x_end, y_beg, y_end); if(numeric_traits::ISNA(xy_cov)) { return numeric_traits::NA(); } ReturnType x_sd = Stdev::apply(x_beg, x_end); ReturnType y_sd = Stdev::apply(y_beg, y_end); return xy_cov / ( x_sd * y_sd ); } }; } // namespace tslib #endif // COR_HPP fts/src/tslib/tslib/vector.summary/close.hpp0000644000176000001440000000314211240355401020726 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef CLOSE_HPP #define CLOSE_HPP #include #include namespace tslib { template class closeTraits { public: typedef T ReturnType; }; template class Close { public: template static inline ReturnType apply(T beg, T end) { return *(end-1); } }; } // namespace tslib #endif // CLOSE_HPP fts/src/tslib/tslib/vector.summary/stdev.hpp0000644000176000001440000000435211176645141020765 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef STDEV_HPP #define STDEV_HPP #include #include namespace tslib { template class stdevTraits; template<> class stdevTraits { public: typedef double ReturnType; }; template<> class stdevTraits { public: typedef double ReturnType; }; template class Stdev { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 0; ReturnType len = static_cast(std::distance(beg,end)); // can't take stdev of only 1 element if(len <= 1) { return numeric_traits::NA(); } ReturnType vec_mean = Mean::apply(beg,end); // check NA of mean if(numeric_traits::ISNA(vec_mean)) { return numeric_traits::NA(); } while(beg != end) { ans += std::pow(*beg - vec_mean, 2); ++beg; } return std::pow( ans/(len - 1), 0.5); } }; } // namespace tslib #endif // STDEV_HPP fts/src/tslib/tslib/vector.summary/pos.sum.hpp0000644000176000001440000000371511176645141021246 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef POS_SUM_HPP #define POS_SUM_HPP #include #include namespace tslib { template class posSumTraits; template<> class posSumTraits { public: typedef double ReturnType; }; template<> class posSumTraits { public: typedef int ReturnType; }; template class PosSum { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 0; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans += *beg > 0 ? *beg : 0; ++beg; } return ans; } }; } // namespace tslib #endif // POS_SUM_HPP fts/src/tslib/tslib/vector.summary/rsi.hpp0000644000176000001440000000450411176645141020434 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RSI_HPP #define RSI_HPP #include #include namespace tslib { template class rsiTraits; template<> class rsiTraits { public: typedef double ReturnType; }; template<> class rsiTraits { public: typedef double ReturnType; }; template class RSI { public: template static inline ReturnType apply(T beg, T end) { ReturnType pos_count = 0; ReturnType neg_count = 0; ReturnType pos_sum = 0; ReturnType neg_sum = 0; double avg_gain = 0; double avg_loss = 0; if(numeric_traits::ISNA(*beg)) { return numeric_traits::NA(); } if(*beg > 0) { ++pos_count; pos_sum += *beg; } if(*beg < 0) { ++neg_count; neg_sum += std::abs(*beg); } if(pos_count) { avg_gain = pos_sum/pos_count; } if(neg_count) { avg_loss = neg_sum/neg_count; } return 100.0 - 100.0 / (1.0 + avg_gain/avg_loss); } }; } // namespace tslib #endif // RSI_HPP fts/src/tslib/tslib/vector.summary/open.hpp0000644000176000001440000000313111240355401020560 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef OPEN_HPP #define OPEN_HPP #include #include namespace tslib { template class openTraits { public: typedef T ReturnType; }; template class Open { public: template static inline ReturnType apply(T beg, T end) { return *beg; } }; } // namespace tslib #endif // OPEN_HPP fts/src/tslib/tslib/vector.summary/sum.hpp0000644000176000001440000000364611176645141020451 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef SUM_HPP #define SUM_HPP #include #include namespace tslib { template class sumTraits; template<> class sumTraits { public: typedef double ReturnType; }; template<> class sumTraits { public: typedef int ReturnType; }; template class Sum { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 0; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans += *beg; ++beg; } return ans; } }; } // namespace tslib #endif // SUM_HPP fts/src/tslib/tslib/vector.summary/cov.hpp0000644000176000001440000000501411176645141020423 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef COV_HPP #define COV_HPP #include #include namespace tslib { template class covTraits; template<> class covTraits { public: typedef double ReturnType; }; template<> class covTraits { public: typedef double ReturnType; }; template class Cov { public: template static inline ReturnType apply(T x_beg, T x_end, T y_beg, T y_end) { typedef typename std::iterator_traits::difference_type DT; typedef typename std::iterator_traits::value_type VT; DT x_len = std::distance(x_beg,x_end); DT y_len = std::distance(y_beg,y_end); if(x_len != y_len) { return numeric_traits::NA(); } ReturnType x_mean = Mean::apply(x_beg,x_end); ReturnType y_mean = Mean::apply(y_beg,y_end); // if we know that x_mean or y_mean is already NA, then just return NA if(numeric_traits::ISNA(x_mean) || numeric_traits::ISNA(y_mean)) { return numeric_traits::NA(); } ReturnType ans = 0; while(x_beg != x_end) { ans += (*x_beg - x_mean)*(*y_beg - y_mean); ++x_beg; ++y_beg; } return ans/(x_len - 1); } }; } // namespace tslib #endif // COV_HPP fts/src/tslib/tslib/vector.summary/min.hpp0000644000176000001440000000347411176645141020427 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef MIN_HPP #define MIN_HPP #include #include namespace tslib { template class minTraits { public: typedef T ReturnType; }; template class Min { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = *beg++; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans = *beg < ans ? *beg : ans; ++beg; } return ans; } }; } // namespace tslib #endif // MIN_HPP fts/src/tslib/tslib/vector.summary/rank.hpp0000644000176000001440000000370711176645141020576 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef RANK_HPP #define RANK_HPP #include #include namespace tslib { template class rankTraits { public: typedef int ReturnType; }; template class Rank { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 1; typename std::iterator_traits::value_type rank_value = *(end - 1); while(beg != (end - 1)) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } // if end > data[index] then increment it's rank ans += (rank_value > *beg ? 1 : 0); ++beg; } return ans; } }; } // namespace tslib #endif // RANK_HPP fts/src/tslib/tslib/vector.summary/max.hpp0000644000176000001440000000347411176645141020431 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef MAX_HPP #define MAX_HPP #include #include namespace tslib { template class maxTraits { public: typedef T ReturnType; }; template class Max { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = *beg++; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans = *beg > ans ? *beg : ans; ++beg; } return ans; } }; } // namespace tslib #endif // MAX_HPP fts/src/tslib/tslib/vector.summary/neg.sum.hpp0000644000176000001440000000372711176645141021221 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef NEG_SUM_HPP #define NEG_SUM_HPP #include #include namespace tslib { template class negSumTraits; template<> class negSumTraits { public: typedef double ReturnType; }; template<> class negSumTraits { public: typedef int ReturnType; }; template class NegSum { public: template static inline ReturnType apply(T beg, T end) { ReturnType ans = 0; while(beg != end) { if(numeric_traits::value_type>::ISNA(*beg)) { return numeric_traits::NA(); } ans += *beg < 0 ? std::abs(*beg) : 0; ++beg; } return ans; } }; } // namespace tslib #endif // NEG_SUM_HPP fts/src/tslib/tslib/tseries.io.hpp0000644000176000001440000000454612317326636016736 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2014 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef TSERIES_IO_HPP #define TSERIES_IO_HPP #include namespace tslib { template class TSDATABACKEND, template class DatePolicy> std::ostream& operator<< (std::ostream& os, const TSeries& ts) { std::vector cnames(ts.getColnames()); if(cnames.size()) { // shift out to be in line w/ first column of values (space is for dates column) os << "\t"; for(std::vector::const_iterator iter = cnames.begin(); iter != cnames.end(); iter++) { os << *iter++ << " "; } } TDATE* dates = ts.getDates(); TSDIM nr = ts.nrow(); TSDIM nc = ts.ncol(); for(TSDIM row = 0; row < nr; row++) { os << DatePolicy::toString(dates[row],"%Y-%m-%d %T") << "\t"; for(TSDIM col = 0; col < nc; col++) { if(numeric_traits::ISNA(ts(row,col))) { os << "NA" << " "; } else { os << ts(row,col) << " "; } } os << std::endl; } return os; } } // namespace tslib #endif // TSERIES_IO_HPP fts/src/tslib/tslib/utils/0000755000176000001440000000000012312573505015262 5ustar ripleyusersfts/src/tslib/tslib/utils/window.intersection.apply.hpp0000644000176000001440000000366211176645141023145 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef WINDOW_INTERSECTION_APPLY_HPP #define WINDOW_INTERSECTION_APPLY_HPP #include #include namespace tslib { template class F> class windowIntersectionApply { public: template static inline void apply(T ans, DataIter x_iter, DataIter y_iter, TSDIM size, const size_t window) { std::advance(x_iter, window - 1); std::advance(y_iter, window - 1); for(TSDIM i = (window-1); i < size; i++) { *ans = F::apply(x_iter-(window-1),x_iter+1,y_iter-(window-1),y_iter+1); ++x_iter; ++y_iter; ++ans; } } }; } // namespace tslib #endif // WINDOW_INTERSECTION_APPLY_HPP fts/src/tslib/tslib/utils/breaks.hpp0000644000176000001440000000315012312573505017241 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef BREAKS_HPP #define BREAKS_HPP namespace tslib { template void breaks(T beg, T end, U ans) { T original_beg = beg; // FIXME: check beg==end // advance one position while(beg != (end - 1)) { if(*beg != *(beg+1)) { ans = std::distance(original_beg, beg); } ++beg; } ans = std::distance(original_beg, end) - 1; } } #endif // BREAKS_HPP fts/src/tslib/tslib/utils/window.function.hpp0000644000176000001440000001024411176645141021132 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef WINDOW_FUNCTION_HPP #define WINDOW_FUNCTION_HPP #include #include #include #include #include namespace tslib { template class F, class TDATE, class TDATA, class TSDIM, template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries> inline const TSeries window_function(const TSeries& lhs, const TSeries& rhs, const size_t window) { TSDIM lhs_ncol = lhs.ncol(); TSDIM rhs_ncol = rhs.ncol(); if(lhs_ncol != rhs_ncol && lhs_ncol != 1 && rhs_ncol != 1) return TSeries(); // find date intersection RangeSpecifier range(lhs.getDates(), rhs.getDates(), lhs.nrow(), rhs.nrow() ); if(!range.getSize()) return TSeries(); TSDIM ans_ncol = (lhs_ncol > rhs_ncol) ? lhs_ncol : rhs_ncol; // allocate new answer TSDIM ans_nrow = range.getSize() - (window - 1); if(ans_nrow <= 0) return TSeries(); TSeries ans(ans_nrow, ans_ncol); // copy over dates std::copy(range.getDates() + (window - 1), range.getDates()+range.getSize(), ans.getDates()); // set new colnames std::vector lhs_cnames = lhs.getColnames(); std::vector rhs_cnames = rhs.getColnames(); std::vector ans_cnames; // FIXME: this will take some work to get correct if(lhs_cnames==rhs_cnames) { ans_cnames = lhs_cnames; } else { ans_cnames = lhs_cnames.size() ? lhs_cnames : rhs_cnames; } ans.setColnames(ans_cnames); ReturnType* ans_data = ans.getData(); TDATA* lhs_data = lhs.getData(); TDATA* rhs_data = rhs.getData(); for(TSDIM col = 0; col < lhs.ncol(); col++) { RangeIterator lhs_iter(lhs_data, range.getArg1()); RangeIterator rhs_iter(rhs_data, range.getArg2()); windowIntersectionApply::apply(ans_data, lhs_iter, rhs_iter, range.getSize(), window); // increment column ans_data+= ans.nrow(); lhs_data+= lhs.nrow(); rhs_data+= rhs.nrow(); } return ans; } } // namespace tslib #endif // WINDOW_FUNCTION_HPP fts/src/tslib/tslib/utils/window.apply.hpp0000644000176000001440000000334011176645141020431 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef WINDOW_APPLY_HPP #define WINDOW_APPLY_HPP #include #include namespace tslib { template class F> class windowApply { public: template static inline void apply(T ans, U beg, U end, const size_t window) { std::advance(beg, window - 1); while(beg != end) { *ans = F::apply( beg - (window - 1), beg+1); ++beg; ++ans; } } }; } // namespace tslib #endif // WINDOW_APPLY_HPP fts/src/tslib/tslib/utils/cbind.hpp0000644000176000001440000002173011176645141017060 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef CBIND_HPP #define CBIND_HPP #include #include #include namespace tslib { template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT> TSeries cbind(const CONT >& cont, const bool intersection) { size_t sz = cont.size(); if(sz == 0) { return TSeries(); } if(sz == 1) { return *cont.begin(); } std::vector ans_dates; if(intersection) { date_intersection(cont,std::inserter(ans_dates,ans_dates.begin())); } else { date_union(cont,std::inserter(ans_dates,ans_dates.begin())); } if(ans_dates.size() == 0) { return TSeries(); } TSeries ans(ans_dates.size(),cbind_total_cols(cont)); std::copy(ans_dates.begin(), ans_dates.end(), ans.getDates()); // FIXME: set colnames // if union, then we must initialize the values of ans to NA if(!intersection) { for(TSDIM i = 0; i < ans.nrow() * ans.ncol(); i++) { ans.getData()[i] = numeric_traits::NA(); } } typename CONT >::const_iterator it = cont.begin(); // walk along iterator and map values into ans TSDIM offset = 0; while(it != cont.end()) { cbind_map_values(ans, *it, offset); offset += it->ncol(); ++it; } return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT, typename II> void date_intersection(const CONT >& cont, II output_dates) { std::vector inBuff; std::vector outBuff; typename CONT >::const_iterator it = cont.begin(); // pre-load dates for first series std::copy(it->getDates(),it->getDates() + it->nrow(), std::inserter(inBuff,inBuff.begin())); for(it = cont.begin() + 1; it != cont.end(); it++) { outBuff.clear(); set_intersection(inBuff.begin(),inBuff.end(), it->getDates(),it->getDates() + it->nrow(), std::inserter(outBuff,outBuff.begin())); // swap buffs inBuff.clear(); std::copy(outBuff.begin(),outBuff.end(), std::inserter(inBuff,inBuff.begin())); } std::copy(outBuff.begin(),outBuff.end(),output_dates); } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT, typename II> void date_union(const CONT >& cont, II output_dates) { std::set ans; typename CONT >::const_iterator it; // walk through all tseries adding all dates // let std::set drop dups for us for(it = cont.begin(); it != cont.end(); it++) { TDATE* dts = it->getDates(); for(TSDIM i = 0; i < it->nrow(); i++) { ans.insert(dts[i]); } } std::copy(ans.begin(), ans.end(), output_dates); } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT> TSDIM cbind_total_cols(const CONT >& cont) { TSDIM ans = 0; typename CONT >::const_iterator it; for(it = cont.begin(); it != cont.end(); it++) { ans += it->ncol(); } return ans; } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT> TSDIM cbind_max_nrow(const CONT >& cont) { std::vector nrows; typename CONT >::const_iterator it; for(it = cont.begin(); it != cont.end(); it++) { nrows.push_back(it->nrow()); } return *max_element(nrows.begin(), nrows.end()); } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries> void cbind_map_values(TSeries& ans, const TSeries& ts_values, const TSDIM offset) { RangeSpecifier range(ans.getDates(), ts_values.getDates(), ans.nrow(), ts_values.nrow()); TDATA* ans_data = ans.getData(); //advance ans_data by offset ans_data += ans.nrow() * offset; for(TSDIM col = 0; col < ts_values.ncol(); col++) { RangeIterator ts_data_iter(ts_values.getData()+ ts_values.nrow()*col, range.getArg2()); std::copy(ts_data_iter,ts_data_iter + range.getSize(),ans_data); ans_data += ans.nrow(); } } template class TSDATABACKEND, template class DatePolicy, template class DATABACKEND, template class DP> class TSeries, template > class CONT, typename II> void cbind_create_colnames(const CONT >& cont, II new_colnames) { typename CONT >::const_iterator it; for(it = cont.begin(); it != cont.end(); it++) { std::vector this_cnames; // if series has non-empty colnames, pad them into new_colnames // otherwise pad empty strings //FIXME: add a test for all series having empty colnames, then ans should not have blnk strings set as colnames if(this_cnames.size()) { for(std::vector::const_iterator cn_it = this_cnames.begin();it != this_cnames.end(); cn_it++) { *new_colnames++ = *cn_it; } } else { for(int i = 0; i < it->ncol(); i++) { *new_colnames++ = std::string(""); } } } } } // namespace tslib #endif // CBIND_HPP fts/src/tslib/tslib/utils/numeric.traits.hpp0000644000176000001440000000475511176645141020760 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef NUMERIC_TRAITS_HPP #define NUMERIC_TRAITS_HPP #include #include namespace tslib { // to be conformant to R's NA value typedef union { double value; unsigned int word[2]; } ieee_type; template class numeric_traits; template<> class numeric_traits { private: static double calculate_NA() { volatile ieee_type ans_ieee; // do this b/c don't have a good way to determine // endianness at compile time double ans = std::numeric_limits::quiet_NaN(); ans_ieee.value = ans; if( ans_ieee.word[0] == 0 ) { ans_ieee.word[0] = 1954; } else { ans_ieee.word[1] = 1954; } return ans_ieee.value; } public: static const bool has_NA = true; static inline double NA() { static double na_value = calculate_NA(); return na_value; } static inline bool ISNA(double x) { return std::isnan(x); } }; template<> class numeric_traits { public: static const bool has_NA = true; static inline int NA() { return std::numeric_limits::min(); } static inline bool ISNA(int x) { return x == std::numeric_limits::min() ? true : false; } }; } // namespace tslib #endif //NUMERIC_TRAITS_HPP fts/src/tslib/tslib/vector.transform.hpp0000644000176000001440000000355611176645141020163 0ustar ripleyusers/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2008 Whit Armstrong // // // // 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 . // /////////////////////////////////////////////////////////////////////////// #ifndef VECTOR_TRANSFORM_HPP #define VECTOR_TRANSFORM_HPP #include #include #include #include #include #include #include #include #include #include #include #include #endif // VECTOR_TRANSFORM_HPP fts/src/tslib/GPLv3.LICENSE0000644000176000001440000010451311176645141014713 0ustar ripleyusers GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . fts/src/lag.cpp0000644000176000001440000000640713346655317013160 0ustar ripleyusers#define R_NO_REMAP #include #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy> SEXP lagFun(SEXP x, SEXP periods) { int p = Rtype::scalar(periods); if(p < 0) { REprintf("lagFun: periods is not >= 0."); return R_NilValue; } // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.lag(p); return ans.getIMPL()->Robject; } SEXP lagSpecializer(SEXP x, SEXP p) { const TsTypeTuple tsTypeInfo(x); if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return lagFun(x,p); } else { //throw std::logic_error("unable to classify time series."); REprintf("diffSpecializer: unable to classify time series."); return R_NilValue; } } extern "C" SEXP lag(SEXP x, SEXP periods) { return lagSpecializer(x,periods); } fts/src/interface.cpp0000644000176000001440000000551313346655317014352 0ustar ripleyusers#include #include #include #include #include #include #include #include #include #include extern "C" SEXP movingMean(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingSum(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingProduct(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingMax(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingMin(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingStdev(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP movingRank(SEXP x, SEXP periods) { return windowSpecializer(x,periods); } extern "C" SEXP expandingMax(SEXP x) { return transformSpecializer(x); } extern "C" SEXP expandingMin(SEXP x) { return transformSpecializer(x); } extern "C" SEXP sinceNA(SEXP x) { return transformSpecializer(x); } extern "C" SEXP fillForward(SEXP x) { return transformSpecializer(x); } extern "C" SEXP fillBackward(SEXP x) { return transformSpecializer(x); } extern "C" SEXP fillValue(SEXP x, SEXP y) { return transformSpecializer(x, y); } extern "C" SEXP movingCov(SEXP x, SEXP y, SEXP periods) { return windowSpecializer(x,y,periods); } extern "C" SEXP movingCor(SEXP x, SEXP y, SEXP periods) { return windowSpecializer(x,y,periods); } extern "C" SEXP dailySum(SEXP x) { return timeWindowSpecializer(x); } extern "C" SEXP monthlySum(SEXP x) { return timeWindowSpecializer(x); } extern "C" SEXP toYearly(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toQuarterly(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toMonthly(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toWeekly(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toDaily(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toHourly(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toMinute(SEXP x) { return freqSpecializer(x); } extern "C" SEXP toSecond(SEXP x) { return freqSpecializer(x);} extern "C" SEXP ema(SEXP x, SEXP periods) { return transformSpecializer(x, periods); } fts/src/pad.cpp0000644000176000001440000000712613346655317013160 0ustar ripleyusers#define R_NO_REMAP #include #include #include #include #include #include using namespace tslib; template class TSDATABACKEND, template class DatePolicy> SEXP padFun(SEXP x, SEXP dates) { // build tseries from SEXP x TSDATABACKEND tsData(x); TSeries ts(tsData); TSeries ans = ts.pad(Rallocator::RdataPtr(dates),Rallocator::RdataPtr(dates) + Rf_length(dates)); return ans.getIMPL()->Robject; } SEXP padSpecializer(SEXP x, SEXP dates) { const TsTypeTuple tsTypeInfo(x); if(TYPEOF(dates) != tsTypeInfo.dateSEXPTYPE) { REprintf("padSpecializer: pad dates must be same storage.mode as index."); return R_NilValue; } if(TsTypeTuple::getIndexPolicyType(dates) != tsTypeInfo.datePolicy) { REprintf("padSpecializer: pad dates must be the same class as index."); return R_NilValue; } if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==dateT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==REALSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==REALSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==INTSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else if(tsTypeInfo.dateSEXPTYPE==INTSXP && tsTypeInfo.dataSEXPTYPE==LGLSXP && tsTypeInfo.datePolicy==posixT) { return padFun(x,dates); } else { //throw std::logic_error("unable to classify time series."); REprintf("diffSpecializer: unable to classify time series."); return R_NilValue; } } extern "C" SEXP pad(SEXP x, SEXP dates) { return padSpecializer(x,dates); } fts/NAMESPACE0000644000176000001440000000555113327362156012333 0ustar ripleyusersuseDynLib(fts) importFrom("grDevices", "xy.coords") importFrom("graphics", "plot", "plot.xy") importFrom("stats", "cor", "lag") importFrom("utils", "read.csv", "write.csv") importFrom(zoo,coredata) importFrom(zoo, index) importFrom(zoo,'index<-') importFrom(zoo,'time<-') export( fts, as.fts, as.fts.default, as.fts.data.frame, as.fts.zoo, as.matrix.fts, template.fts, Ops.fts, "[.fts", "[<-.fts", as.data.frame.fts, cbind.fts, rbind.fts, pad, trim, read.csv.fts, write.csv.fts, print.fts, to.yearly, to.quarterly, to.monthly, to.weekly, to.daily, to.hourly, to.minute, to.second, to.day.of.week, moving.mean, moving.sum, moving.product, moving.max, moving.min, moving.rank, moving.sd, expanding.max, expanding.min, moving.cor, moving.cov, since.na, lead, lead.fts, lag.fts, diff.fts, fill.fwd, fill.bwd, fill.value, monthly.sum, plot.fts, event.dates, intersect.all, remove.na.rows, remove.all.na.rows, row.apply, row.any, row.all, column.apply, col.any, col.all, filter.min.obs, ## technical analysis ema, rsi, year, month, mday, wday, ma.crossover.up, ma.crossover.down, lower.low, higher.high, repeated, new.low, new.high, above.ma, below.ma, ma.d, higher.low, lower.high, up, down, pct.chg, inside.day, inside.day.up, inside.day.down, inside.day.direction, ma.crossover.up, ma.crossover.down, ma.crossover, outside.day, outside.day.up, outside.day.down, outside.day.direction, hl.oc.ratio, gap.up, gap.down, gap.up.continue, gap.down.continue, gap.continue, gap.up.reverse, gap.down.reverse, gap.reverse, gap.direction, rsi.crossover.up, rsi.crossover.down, rsi.crossover, ma.distance, trend.day, trend.day.up, trend.day.down, cor.by.row ) S3method("Ops", "fts") S3method("[", "fts") S3method("cummax", "fts") S3method("cummin", "fts") S3method("cumprod", "fts") S3method("cumsum", "fts") S3method("lag", "fts") S3method("plot", "fts") S3method("print", "fts") S3method("[<-", "fts") S3method("as.data.frame", "fts") S3method("as.fts", "data.frame") S3method("as.fts", "default") S3method("as.fts", "zoo") S3method("as.matrix", "fts") S3method("cbind", "fts") S3method("diff", "fts") S3method("lead", "fts") S3method("rbind", "fts") fts/R/0000755000176000001440000000000012315033603011273 5ustar ripleyusersfts/R/fts.R0000644000176000001440000004550512315033603012223 0ustar ripleyusers############################################################### ################ Fts class definitions #################### ############################################################### ############################################################### ## layout of an fts object is ## a matrix with a dates attribute attached fts <- function(index,data) { if(missing(index)) stop("missing index") if(missing(data)) stop("missing data") stopifnot(length(index)==NROW(data)) structure(as.matrix(data),index=index,class=c("fts","zoo")) } as.fts <- function(x) { UseMethod("as.fts") } as.fts.default <- function(x) { if(!is.null(dim(x))) { dts <- rownames(x) } else { dts <- names(x) } fts(index=dts,data=x) } as.fts.data.frame <- function(x) { cnames <- colnames(x) ans <- fts(index=x[,"asofdate"], data=as.matrix(x[,-match("asofdate",cnames)])) colnames(ans) <- cnames[-1] ans } as.fts.zoo <- function(x) fts(index=attr(x,"index"),data=as.matrix(coredata(x))) as.matrix.fts <- function(x, ...) structure(matrix(as.numeric(x),nrow=nrow(x),ncol=ncol(x)),dimnames=list(format(index(x),"%Y%m%d"),colnames(x))) as.dataframe.fts <- function(x, ...) { ans <- data.frame(x) rownames(ans) <- format(index(x),"%Y%m%d") ans } ## create an fts object given dates and column names template.fts <- function(index,cnames) { ans <- fts(index=index, data=matrix(nrow=length(index),ncol=length(cnames))) colnames(ans) <- cnames ans } Ops.fts <- function (e1, e2) { if(missing(e2)) { .Class <- "matrix" NextMethod() } else { c.e1 <- class(e1) c.e2 <- class(e2) if("fts" %in% c.e1 && "fts" %in% c.e2) { nce1 <- NCOL(e1) nce2 <- NCOL(e2) if(nce1!=nce2 && nce1!=1 && nce2!=1) { stop("Ops.fts: non conformable data.") } stopifnot(all.equal(class(index(e1)),class(index(e2)))) i.dates <- intersect(index(e1),index(e2)) class(i.dates) <- class(index(e1)) ## if there is an intersection, the do the Op if(length(i.dates)) { e1 <- e1[i.dates,] e2 <- e2[i.dates,] if(nce1==1 && nce2!=1) { e1 <- rep(e1,nce2) } else if(nce1!=1 && nce2==1) { e2 <- rep(e2,nce1) } .Class <- "matrix" ans <- NextMethod() attr(ans,"index") <- i.dates class(ans) <- c("fts","zoo") } else { ## no matching dates, return NULL ans <- NULL } } else { .Class <- "matrix" ans <- NextMethod() if("fts" %in% c.e1) { ans.dates <- attr(e1,"index") } else { ans.dates <- attr(e2,"index") } attr(ans,"index") <- ans.dates class(ans) <- c("fts","zoo") } ans } } print.fts <- function(x, ...) { cnms <- colnames(x) dnms <- list(format(index(x)),cnms) dims <- dim(x) attributes(x) <- NULL dim(x) <- dims dimnames(x) <- dnms print(x,...) invisible(x) } "[.fts" <- function(x,i,j,...,drop=FALSE) { if(missing(i)) i <- 1:nrow(x) if(missing(j)) j <- 1:ncol(x) ## ##if(typeof(i)=="character") { ## i <- guess.index(i,index(x)) ##} ## if we have dates, then use them if(any(c("Date","POSIXct") %in% class(i))) { i <- match(i,index(x)) } ## FIXME: not sure about this hack... ##i <- i[!is.na(i)] ##j <- j[!is.na(j)] ans.dates <- index(x)[i] ans <- unclass(x)[i,j,...,drop=drop] attr(ans,"index") <- ans.dates class(ans) <- c("fts","zoo") ans } "[<-.fts" <- function(x, i = TRUE, j = TRUE, ..., value) { ## if we have dates, then use them if(!missing(i)) { if(any(c("Date","POSIXct") %in% class(i))) { i <- match(i,index(x)) } else if (mode(i)=="logical") { i <- which(i) } } .Class <- "matrix" NextMethod() } ## apply a function to an fts row row.apply <- function(x,FUN,...) { ans <- apply(x,1,FUN,...) if(!is.null(dim(ans))) { ans <- t(ans) rownames(ans) <- NULL } fts(index=index(x),data=ans) } row.any <- function(x) apply(x,1,any) row.all <- function(x) apply(x,1,all) col.any <- function(x) apply(x,2,any) col.all <- function(x) apply(x,2,all) ## apply a function to an fts column column.apply <- function(x,FUN,...) { apply(x,2,FUN,...) } remove.na.rows <- function(x) x[!row.any(is.na(x)),] remove.all.na.rows <- function(x) x[!row.all(is.na(x)),] as.data.frame.fts <- function(x,row.names = NULL, optional = FALSE, check.names = TRUE,...) { data.frame(asofdate=index(x),as.data.frame.matrix(unclass(x),optional=optional),check.names=check.names) } as.matrix.fts <- function(x, ...) { rownames(x) <- format(index(x)) attr(x,"index") <- NULL class(x) <- "matrix" x } rbind.fts <- function(...) { x <- list(...) ## check for same number of cols if(length(unique(unlist(lapply(x,ncol))))!=1) { stop("unequal number of cols in arguments.") } ## unclass data ans.unclass <- lapply(x,unclass) ## do rbind ans.data <- do.call(rbind,ans.unclass) ## get dates ans.dates <- do.call(c,lapply(x,index)) ## sort it new.order <- order(ans.dates) ## must do data before we sort dates ans.data <- ans.data[new.order,,drop=F] ans.dates <- ans.dates[new.order] fts(index=ans.dates,data=ans.data) } cbind.fts <- function(...) { x <- list(...) ans.index <- sort(unique(unlist(lapply(x,index)))) class(ans.index) <- class(index(x[[1]])) nrow.ans <- length(ans.index) ncol.list <- lapply(x,ncol) ncol.ans <- sum(unlist(ncol.list)) ans <- matrix(NA,nrow=nrow.ans,ncol=ncol.ans) ## starting col start.col <- 1 ## fill the answer for(i in 1:length(x)) { ## guard against null contracts from LIM if(!is.null(x[[i]])) { end.col <- start.col + ncol.list[[i]] - 1 ans[match(index(x[[i]]),ans.index),start.col:end.col] <- x[[i]] start.col <- end.col + 1 } } ## set attributes ## fix blank cnames cnames.list <- lapply(x,colnames) colnames(ans) <- fix.cnames(cnames.list) attr(ans,"index") <- ans.index class(ans) <- c("fts","zoo") ans } fix.cnames <- function(cnames.list) { null.cnames <- unlist(lapply(cnames.list,is.null)) for(i in 1:length(cnames.list)) { if(null.cnames[i]) { cnames.list[[i]] <- "" } } unlist(cnames.list) } trim <- function(x,trim.dates) { new.dates <- sort(intersect(index(x),trim.dates)) class(new.dates) <- class(index(x)) x[new.dates,] } write.csv.fts <- function(x, file, ...) { write.csv(as.data.frame(x), file,row.names=FALSE, ...) } read.csv.fts <- function(file, date.column=1, date.format="%Y-%m-%d",date.convert.fun=as.Date,...) { fts.data <- read.csv(file,...) if(mode(date.column)=="character") date.column <- match(date.column,colnames(fts.data)) fts(index=date.convert.fun(strptime(fts.data[,date.column],date.format)), data=as.matrix(fts.data[, -date.column, drop=F])) } cumsum.fts <- function(x) fts(index=index(x),data=apply(x,2,cumsum)) cumprod.fts <- function(x) fts(index=index(x),data=apply(x,2,cumprod)) cummax.fts <- function(x) fts(index=index(x),data=apply(x,2,cummax)) cummin.fts <- function(x) fts(index=index(x),data=apply(x,2,cummin)) ############################################################### ################### Date Functions ############################ ############################################################### ############################################################### ## return the dates just when the fts is true event.dates <- function(x) { stopifnot(ncol(x)==1) index(x)[as.logical(x)&!is.na(x)] } ## find date intersection of all tseries intersect.all <- function(...) { x <- list(...) dts <- lapply(x,index) ans <- dts[[1]] if(length(dts) > 1) { for(i in 2:length(x)) { ans <- intersect(ans,dts[[i]]) } } class(ans) <- class(index(x[[1]])) ans } ############################################################### ################ Calls to External Library #################### ############################################################### ############################################################### moving.mean <- function(x,periods) { .Call("movingMean",x,as.integer(periods),PACKAGE="fts") } moving.sum <- function(x,periods) { .Call("movingSum",x,as.integer(periods),PACKAGE="fts") } moving.product <- function(x,periods) { .Call("movingProduct",x,as.integer(periods),PACKAGE="fts") } moving.max <- function(x,periods) { .Call("movingMax",x,as.integer(periods),PACKAGE="fts") } moving.min <- function(x,periods) { .Call("movingMin",x,as.integer(periods),PACKAGE="fts") } moving.rank <- function(x,periods) { .Call("movingRank",x,as.integer(periods),PACKAGE="fts") } moving.sd <- function(x,periods) { .Call("movingStdev",x,as.integer(periods),PACKAGE="fts") } expanding.max <- function(x) { .Call("expandingMax",x,PACKAGE="fts") } expanding.min <- function(x) { .Call("expandingMin",x,PACKAGE="fts") } moving.cor <- function(x,y,periods) { .Call("movingCor", x, y, as.integer(periods),PACKAGE="fts") } moving.cov <- function(x,y,periods) { .Call("movingCov", x, y, as.integer(periods),PACKAGE="fts") } since.na <- function(x) { .Call("sinceNA",x,PACKAGE="fts") } lag.fts <- function(x, k, ...) { stopifnot(k > -1) ans <- .Call("lag", x, as.integer(k),PACKAGE="fts") ans } lead <- function(x, k, ...) { UseMethod("lead") } lead.fts <- function(x, k, ...) { if(k < 0) stop("only positive values of k are allowed") .Call("lead",x ,as.integer(k),PACKAGE="fts") } diff.fts <- function(x, k, ...) { stopifnot(k > 0) ans <- .Call("diff", x, as.integer(k),PACKAGE="fts") attr(ans,"ticker") <- attr(x,"ticker") ans } fill.fwd <- function(x) { .Call("fillForward",x,PACKAGE="fts") } fill.bwd <- function(x) { .Call("fillBackward",x,PACKAGE="fts") } fill.value <- function(x,value) { .Call("fillValue",x,value,PACKAGE="fts") } pad <- function(x,pad.dates) { stopifnot(all.equal(class(index(x)),class(pad.dates))) if(storage.mode(pad.dates)!=storage.mode(index(x))) storage.mode(pad.dates) <- storage.mode(index(x)) .Call("pad",x,pad.dates,PACKAGE="fts") } monthly.sum <- function(x) { .Call("monthlySum",x,PACKAGE="fts") } to.yearly <- function(x) { .Call("toYearly",x,PACKAGE="fts") } to.quarterly <- function(x) { .Call("toQuarterly",x,PACKAGE="fts") } to.monthly <- function(x) { .Call("toMonthly",x,PACKAGE="fts") } to.weekly <- function(x) { .Call("toWeekly",x,PACKAGE="fts") } to.daily <- function(x) { .Call("toDaily",x,PACKAGE="fts") } to.hourly <- function(x) { .Call("toHourly",x,PACKAGE="fts") } to.minute <- function(x) { .Call("toMinute",x,PACKAGE="fts") } to.second <- function(x) { .Call("toSecond",x,PACKAGE="fts") } to.day.of.week <- function(x,day.of.week,beginning.of.period=TRUE) { dts <- index(x) stopifnot(class(dts)=="Date") end.date <- dts[nrow(x)] end.date <- end.date + 6 pad.days <- seq(from=dts[1],to=end.date,by="days") ## seq changes storage mode storage.mode(pad.days) <- storage.mode(dts) pad.days <- pad.days[as.POSIXlt(pad.days)$wday==day.of.week] x.filled <- fill.fwd(pad(x,pad.days)) ans <- x.filled[as.POSIXlt(index(x.filled))$wday == day.of.week,] if(beginning.of.period) { index(ans) <- index(ans) - 6 } ans } ############################################################### ############ Plotting functions for Fts Objects ########### ############################################################### ############################################################### plot.fts <- function(x, type="l", xlab="Date", ylab=substitute(x), ...) { x.range <- c(min(index(x)), max(index(x))) y.range <- c(min(x, na.rm=TRUE), max(x, na.rm=TRUE)) plot(x.range, y.range, type="n", xlab=xlab, ylab=ylab, ...) params <- lapply(list(type = type, ...), rep, length.out = ncol(x)) for (i in seq(ncol(x))) { args <- c(list(xy.coords(index(x), x[,i])), lapply(params, `[`, i)) do.call(plot.xy, args) } } ## drop out rows that do not have the required number of observations filter.min.obs <- function(x,obs.required) { obs <- apply(!is.na(x),1,sum) x[obs >= obs.required,] } ############################################################### ################### Technical Analysis ####################### ############################################################### ############################################################### ema <- function(x,periods) { .Call("ema",x,as.integer(periods),PACKAGE="fts") } rsi <- function(x,periods) { x.up <- x x.up[x<0] <- 0 x.down <- x x.down[x>0] <- 0 x.avg.up <- ema(x.up, periods) x.avg.down <- ema(x.down, periods) 100 - 100/(1 - x.avg.up/x.avg.down) } year <- function(x) { as.POSIXlt(index(x))$year+1900 } month <- function(x) { as.POSIXlt(index(x))$mon+1 } mday <- function(x) { as.POSIXlt(index(x))$mday } wday <- function(x) { as.POSIXlt(index(x))$wday } ma.crossover.down <- function(x,n) { has.close <- !is.null(colnames(x)) && "close" %in% colnames(x) stopifnot(has.close || ncol(x) == 1) col <- ifelse(has.close,"close",1) x <- x[,col] xma <- moving.mean(x,n) x < xma & lag(x,1) > lag(xma,1) } ma.crossover.up <- function(x,n) { has.close <- !is.null(colnames(x)) && "close" %in% colnames(x) stopifnot(has.close || ncol(x) == 1) col <- ifelse(has.close,"close",1) x <- x[,col] xma <- moving.mean(x,n) x > xma & lag(x,1) < lag(xma,1) } ma.crossover <- function(x,n) { ma.crossover.up(x,n) - ma.crossover.down(x,n) } lower.low <- function(x) { stopifnot("low" %in% colnames(x)) xl <- x[,"low"] xl < lag(xl,1) } higher.high <- function(x) { stopifnot("high" %in% colnames(x)) xh <- x[,"high"] xh > lag(xh,1) } repeated <- function(x, times) { stopifnot(ncol(x)==1 && mode(x)=="logical") moving.sum(x,times)==as.integer(times) } new.low <- function(x,n) { stopifnot("low" %in% colnames(x)) moving.rank(x[,"low"],n)==1 } new.high <- function(x,n) { stopifnot("high" %in% colnames(x)) moving.rank(x[,"high"],n)==as.integer(n) } above.ma <- function(x,n) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xc > moving.mean(xc,n) } below.ma <- function(x,n) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xc < moving.mean(xc,n) } ma.d <- function(x,n) { above.ma(x,n) - below.ma(x,n) } higher.low <- function(x) { stopifnot("low" %in% colnames(x)) xl <- x[,"low"] xl > lag(xl,1) } lower.high <- function(x) { stopifnot("high" %in% colnames(x)) xh <- x[,"high"] xh < lag(xh,1) } up <- function(x) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xc > lag(xc,1) } down <- function(x) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xc < lag(xc,1) } pct.chg <- function(x) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] diff(xc,1) / lag(xc,1) * 100 } inside.day <- function(x) { stopifnot(all(c("high","low") %in% colnames(x))) xh <- x[,"high"] xl <- x[,"low"] xh < lag(xh,1) & xl > lag(xl,1) } inside.day.up <- function(x) { inside.day(x) & up(x) } inside.day.down <- function(x) { inside.day(x) & down(x) } inside.day.direction <- function(x) { inside.day.up(x) - inside.day.down(x) } outside.day <- function(x) { stopifnot(all(c("high","low") %in% colnames(x))) xh <- x[,"high"] xl <- x[,"low"] xh > lag(xh,1) & xl < lag(xl,1) } outside.day.up <- function(x) { outside.day(x) & up(x) } outside.day.down <- function(x) { outside.day(x) & down(x) } outside.day.direction <- function(x) { outside.day.up(x) - outside.day.down(x) } hl.oc.ratio <- function(x) { stopifnot(all(c("open","high","low","close") %in% colnames(x))) abs(x[,"close"] - x[,"open"]) / (x[,"high"] - x[,"low"]) } gap.up <- function(x) { stopifnot(all(c("open","high","low","close") %in% colnames(x))) xh <- x[,"high"] xo <- x[,"open"] xo > lag(xh,1) } gap.down <- function(x) { stopifnot(all(c("open","high","low","close") %in% colnames(x))) xl <- x[,"low"] xo <- x[,"open"] xo < lag(xl,1) } gap.up.continue <- function(x) { gap.up(x) & up(x) } gap.down.continue <- function(x) { gap.down(x) & down(x) } gap.continue <- function(x) { gap.up.continue(x) - gap.down.continue(x) } gap.up.reverse <- function(x) { gap.up(x) & down(x) } gap.down.reverse <- function(x) { gap.down(x) & up(x) } gap.reverse <- function(x) { gap.up.reverse(x) - gap.down.reverse(x) } gap.direction <- function(x) { gap.up(x) - gap.down(x) } rsi.crossover.up <- function(x,periods,thresh) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xd <- diff(xc,1) x.rsi <- rsi(xd,periods) x.rsi <- x.rsi[!is.na(x.rsi),] x.rsi < thresh & lag(x.rsi,1) > thresh } rsi.crossover.down <- function(x, periods, thresh) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xd <- diff(xc,1) x.rsi <- rsi(xd,periods) x.rsi <- x.rsi[!is.na(x.rsi),] x.rsi > thresh & lag(x.rsi,1) < thresh } rsi.crossover <- function(x,periods, thresh) { rsi.crossover.up(x,periods,thresh) - rsi.crossover.down(x,periods,thresh) } ma.distance <- function(x, periods) { stopifnot("close" %in% colnames(x)) xc <- x[,"close"] xma <- moving.mean(xc,periods) (xc - xma) / xc * 100 } trend.day.up <- function(x,thresh=0.2) { stopifnot(all(c("open","high","low","close") %in% colnames(x))) xo <- x[,"open"] xh <- x[,"high"] xl <- x[,"low"] xc <- x[,"close"] day.range <- xh - xl open.low <- (xo - xl) / day.range high.close <- (xh - xc) / day.range open.low <= thresh & high.close <= thresh } trend.day.down <- function(x,thresh=0.2) { stopifnot(all(c("open","high","low","close") %in% colnames(x))) xo <- x[,"open"] xh <- x[,"high"] xl <- x[,"low"] xc <- x[,"close"] day.range <- xh - xl open.high <- (xh - xo) / day.range low.close <- (xc - xl) / day.range open.high <= thresh & low.close <= thresh } trend.day <- function(x,thresh=.2) { trend.day.up(x,thresh) - trend.day.down(x,thresh) } cor.by.row <- function(x,y) { i.dts <- sort(intersect(index(x),index(y))) class(i.dts) <- class(index(x)) ans <- template.fts(i.dts,"cor") for(i in 1:length(i.dts)) { ans[i,] <- cor(as.vector(x[i.dts[i],]),as.vector(y[i.dts[i],])) } ans } fts/MD50000644000176000001440000001302013346662421011411 0ustar ripleyusers22239cc9cbc014287a7207d6377c4480 *DESCRIPTION 46198257c1929f05f7617fcdd16ba5e3 *NAMESPACE d0dd69d8b3f47929570308fe8f3cd307 *R/fts.R 1a0fa2e95e2fd56c29a9823e05b1aa02 *man/any.all.fts.Rd de686c8b1815496e8b26956c135e1611 *man/apply.Rd 70967d6d47f08302ca8e0a25e996b2b3 *man/as.fts.Rd f32968521929561de7ad7f2f98635d44 *man/event.dates.Rd 2db617b067d083d836feec0f7bd13a11 *man/expanding.Rd bc113741dde4d0f16069346c98a0b8be *man/fill.Rd ccc558ea4046fcdee5f81cd02647deb6 *man/frequency.convert.Rd f42ab1980f7fd243e7249948ba54e952 *man/fts.Rd 35967918142706c931ba86579169250c *man/indicators.Rd 8fb4926690db8bce826d0eedf72a3323 *man/intersect.all.Rd e490c99ac3a890011aa4ff3019f55433 *man/lead.lag.Rd ec543741265cc452d52583c6f91d673d *man/moving.Rd 8c23bc5ddba41f8dfaf60cd38695aaff *man/pad.trim.Rd 26c1b156309d9359f994002908d8ec14 *man/read.write.fts.Rd 8aff81340b37b69fb54ed35d4f638489 *man/remove.rows.Rd a6a70c0be746edbe9fd3c6b40f0a5d66 *man/since.na.Rd b03ea0206a2b72770dc79edf3ca2b9cb *src/Makevars 3317cc7aaa82659472dd70f3235ee38f *src/diff.cpp 45e485bc390d818b9229bfcd13283384 *src/helpers/R.tseries.data.backend.hpp b52ca43add6b0bcc092e937de72daf8f *src/helpers/Rsexp.allocator.templates.hpp 94903813385cf1500731adc640044552 *src/helpers/Rtype.hpp bb28acc793f03153bf61ace4762bff7a *src/helpers/freq.transform.template.hpp 52badd61806b6a8b2fbb4d802b603b59 *src/helpers/fts.factory.hpp d4df08f0f4a8aeec0ed52b2887143230 *src/helpers/time.window.template.hpp 6174ef6d5fa48474f39bcb4b0d7fbf02 *src/helpers/transform.template.hpp 5a117f7aa661c0fdfc09a7762b0dc89f *src/helpers/window.intersection.template.hpp 8a70be7fdf23d98b15f4d11aa8de4e51 *src/helpers/window.template.hpp f5f159d2abaea43bfb75396cc03299e2 *src/interface.cpp fb9ab22b702135e2b25f37b5fcd3fce2 *src/lag.cpp f3ab5c7b6e7d83afe2cc920ef2245003 *src/lead.cpp b80c68087e053bd6e7e470e42966eb1c *src/pad.cpp d32239bcb673463ab874e80d47fae504 *src/tslib/GPLv3.LICENSE aeb7c67b6af75f46fbbc90cdaa5ae2e0 *src/tslib/Makefile c3ee6f8eacf5e2a7118416ef8d6229f9 *src/tslib/tslib/date.policies/date.partition.hpp c393547887884e5958bf78acbd36d9d8 *src/tslib/tslib/date.policies/julian.date.policy.hpp 24955ad6cb282f6f4cb6b98144758bbf *src/tslib/tslib/date.policies/posix.date.policy.hpp 8dce7f79e9caf51e804068d2a5f06d6f *src/tslib/tslib/range.specifier/range.iterator.hpp 07d9a790d33f45823fd7e506cd1ab036 *src/tslib/tslib/range.specifier/rangeSpecifier.hpp d88791bef29802c4a752c0a3e73a7d7c *src/tslib/tslib/ts.opps/ifthenelse.hpp 619aed9cd8cc8fd58297f70aec290bb0 *src/tslib/tslib/ts.opps/ts.opps.hpp b01f7ab712f2331945746c3de9ea6c3c *src/tslib/tslib/ts.opps/ts.promotion.hpp 1bc44b546439130c98d6c0852b1ee234 *src/tslib/tslib/ts.opps/ts.scalar.opp.hpp 98160fe0072447066fc0d4a614d6a375 *src/tslib/tslib/ts.opps/ts.ts.opp.hpp 7bdd5f5eaeca93ed015466012b5033bb *src/tslib/tslib/tseries.data.hpp a1415776276e0a280f0668e27d0d9306 *src/tslib/tslib/tseries.hpp 4e88da4706441f56b8157858e90a567e *src/tslib/tslib/tseries.io.hpp 65ef3f73807cfa1c6a851b8cdbe7a09a *src/tslib/tslib/utils/breaks.hpp c390eeea7e31807bf5797665da87e297 *src/tslib/tslib/utils/cbind.hpp 1e01e2a66f214354a55dc75dde4060b6 *src/tslib/tslib/utils/numeric.traits.hpp 93cd66824beeaa4cb0b65cb8b8216313 *src/tslib/tslib/utils/window.apply.hpp 640e60c4470073a6658f43071558708f *src/tslib/tslib/utils/window.function.hpp 0e836440b4c73b11b908691c65d7b9e3 *src/tslib/tslib/utils/window.intersection.apply.hpp 12dac149b1de1ad536ddb3771280b97e *src/tslib/tslib/vector.summary.hpp f06029b2edd813177077488c32ccdc6e *src/tslib/tslib/vector.summary/close.hpp 00aac345baa8161df0c3c14313564720 *src/tslib/tslib/vector.summary/contains.na.hpp 8c20f6df16f4208f9db0721f54a278c8 *src/tslib/tslib/vector.summary/cor.hpp 4d5b7f7da9f37007ea1ee586539d6881 *src/tslib/tslib/vector.summary/cov.hpp f13d4a5395f7d08adca2d3ae405e8b2a *src/tslib/tslib/vector.summary/max.hpp f29b04e545902c3f2f56bff2c1e908d9 *src/tslib/tslib/vector.summary/mean.hpp 6739c03128b2e33411cc67d7c50b9705 *src/tslib/tslib/vector.summary/min.hpp 1d4e65002af9ffde028e5a5c5c206869 *src/tslib/tslib/vector.summary/neg.sum.hpp 30a3d0e5736c36a6d262fbd15c968d36 *src/tslib/tslib/vector.summary/open.hpp 3f5c0af5c83e0f285b7b96f55efcde7f *src/tslib/tslib/vector.summary/pos.sum.hpp 42370841f4304423859ea3499283acbe *src/tslib/tslib/vector.summary/prod.hpp cfa1f585e516b973744f97610d00e85b *src/tslib/tslib/vector.summary/rank.hpp 4c90c9d133728d4413b0c2fa6dd746e7 *src/tslib/tslib/vector.summary/rsi.hpp 559ba0c67e337510738ea99343ed9fcd *src/tslib/tslib/vector.summary/stdev.hpp 2b25124e3a8edb314ff13d48c9cb0289 *src/tslib/tslib/vector.summary/sum.hpp 4b5099aed1abe8acee0dd36345a5b92e *src/tslib/tslib/vector.transform.hpp 4aeccf3fedc381b555f1ce1241d90461 *src/tslib/tslib/vector.transform/diff.hpp 8b2ac02d3458f515780c154d4c0163cf *src/tslib/tslib/vector.transform/ema.hpp e4e1c21cdf72e1da344fd9e2920a4684 *src/tslib/tslib/vector.transform/ema.traits.hpp 4fa86accb69fb935a5ac772358190c7e *src/tslib/tslib/vector.transform/expanding.maximum.hpp d050cf7b8f73c9346e3c175af9ef19fc *src/tslib/tslib/vector.transform/expanding.minimum.hpp b3e92106ade6eeb9b6d2debf996a0b14 *src/tslib/tslib/vector.transform/fill.bwd.hpp 4745ce04ee6021688cda7ac85defa9fc *src/tslib/tslib/vector.transform/fill.fwd.hpp 309cd1038f2dfd4125d0a15d090f84e5 *src/tslib/tslib/vector.transform/fill.traits.hpp ffcb026bea115ebc72e741d2b4d5e2f3 *src/tslib/tslib/vector.transform/fill.value.hpp 7ccfe201d3430a9f76086ec1120965b1 *src/tslib/tslib/vector.transform/lag.lead.traits.hpp ea8196ed7c9e99b95fa7a4d4eafec766 *src/tslib/tslib/vector.transform/since.na.hpp eb8b1f303d2834f807f1371d03396e29 *src/tslib/tslib/vector.transform/since.na.traits.hpp fts/DESCRIPTION0000644000176000001440000000073613346662421012621 0ustar ripleyusersPackage: fts Title: R Interface to 'tslib' (a Time Series Library in C++) Version: 0.9.9.2 Maintainer: Whit Armstrong Author: Whit Armstrong Depends: utils, stats, zoo LinkingTo: BH Description: Fast operations for time series objects. License: GPL-3 BugReports: http://github.com/armstrtw/fts/issues Packaged: 2018-09-14 06:53:03 UTC; ripley NeedsCompilation: yes Repository: CRAN Date/Publication: 2018-09-14 07:36:49 UTC fts/man/0000755000176000001440000000000012315034330011643 5ustar ripleyusersfts/man/any.all.fts.Rd0000644000176000001440000000101312310372132014256 0ustar ripleyusers\name{fts.logical} \alias{fts.logical} \alias{col.any} \alias{col.all} \alias{row.any} \alias{row.all} \title{Logical subsets of objects} \description{ Find subsets of logical objects } \usage{ col.any(x) col.all(x) row.any(x) row.all(x) } \arguments{ \item{x}{ a rectangular object } } \value{ a logical vector } \author{ Whit Armstrong } \examples{ x <- fts(seq(from=Sys.Date(),by="months",length.out=50),matrix(rnorm(100),nrow=50)) jj <- x > 0 row.all(jj) row.any(jj) col.any(x > 0) col.all(x > -3) } \keyword{ts} fts/man/expanding.Rd0000644000176000001440000000136012310466202014111 0ustar ripleyusers\name{expanding} \alias{expanding} \alias{expanding.mean} \alias{expanding.sum} \alias{expanding.product} \alias{expanding.max} \alias{expanding.min} \alias{expanding.sd} \alias{expanding.rank} \alias{expanding.cor} \alias{expanding.cov} \title{Expanding Window Functions} \description{ apply summary functions on an expanding basis } \usage{ expanding.max(x) expanding.min(x) } \arguments{ \item{x}{ An Fts object } } \details{ apply a function that takes a vector and returns a scalar on an expanding basis to an fts object } \value{ an fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=rnorm(100)) x.emax <- expanding.max(x) x.emin <- expanding.min(x) } \keyword{ts} fts/man/frequency.convert.Rd0000644000176000001440000000165512312073723015627 0ustar ripleyusers\name{frequency.convert} \alias{frequency.convert} \alias{to.weekly} \alias{to.day.of.week} \alias{to.monthly} \alias{to.quarterly} \alias{to.daily} \alias{to.hourly} \alias{to.minute} \alias{to.second} \alias{to.yearly} \title{Change Frequencies} \description{ convert a time series from a higher frequency to a lower frequency or from an irregular frequency to a regular frequency } \usage{ to.weekly(x) to.monthly(x) to.quarterly(x) to.day.of.week(x,day.of.week,beginning.of.period=TRUE) } \arguments{ \item{x}{An Fts object.} \item{day.of.week}{a numerical value indicating the day of week following POSIXlt conventions.} \item{beginning.of.period}{whether to shift the sampling dates to the beginning of period dates.} } \value{ an Fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=500),data=1:500) to.weekly(x) to.monthly(x) to.quarterly(x) } \keyword{ts} fts/man/fts.Rd0000644000176000001440000000171512310451531012733 0ustar ripleyusers\name{fts} \alias{fts} \alias{Ops.fts} \alias{[.fts} \alias{[<-.fts} \alias{cbind.fts} \alias{rbind.fts} \alias{print.fts} \alias{plot.fts} \title{Fts: a fast timeseries library } \description{ create an fts object by specifying index and data } \usage{ fts(index,data) } \arguments{ \item{index}{a vector of dates} \item{data}{a matrix, dataframe, or vector} } \details{ fts is an S3 class in which the fts object is represented as a native R matrix and the dates are attached as an attribute to the matrix } \value{ a fts object } \author{ Whit Armstrong } \seealso{\code{\link{as.fts}}} \examples{ x <- fts(index=seq(from=Sys.Date(),by="months",length.out=24),data=1:24) y <- fts(index=seq(from=Sys.Date(),by="months",length.out=12),data=13:24) xx <- x[1:10,] ## intersection of dates is taken for Arith methods xyp <- x + y xys <- x - y xym <- x * y xyd <- x / y xyg <- x > y xyl <- x < y cxy <- cbind(x,y) rxy <- rbind(x,y) print(x) plot(x) } \keyword{ts} fts/man/intersect.all.Rd0000644000176000001440000000075112312122442014703 0ustar ripleyusers\name{intersect.all} \alias{intersect.all} \title{find date intersection among multiple fts objects} \description{ find date intersection } \usage{ intersect.all(\dots) } \arguments{ \item{\dots}{ Fts objects } } \value{ a vector of dates } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=1:100) y <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=1:100) y <- y[1:nrow(y) \%\% 2==0,] intersect.all(x,y) } \keyword{ts} fts/man/event.dates.Rd0000644000176000001440000000103012310453215014346 0ustar ripleyusers\name{event.dates} \alias{event.dates} \title{ Extract Dates } \description{ Extract the dates from a one column LOGICAL Fts object where value is TRUE } \usage{ event.dates(x) } \arguments{ \item{x}{ An Fts object } } \details{ removes NA values before extracting dates } \value{ a vector of dates } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=rnorm(100)) x.bool <- x > 10 event.dates(x.bool) ## ignores NA's x.bool[10:20] <- NA event.dates(x.bool) } \keyword{ts} fts/man/remove.rows.Rd0000644000176000001440000000126512312320612014422 0ustar ripleyusers\name{remove.rows} \alias{remove.rows} \alias{remove.na.rows} \alias{remove.all.na.rows} \title{Remove Rows} \description{ remove.na.rows removes rows which contain at least 1 NA remove.all.na rows removes rows which are all NA's } \usage{ remove.na.rows(x) remove.all.na.rows(x) } \arguments{ \item{x}{ An Fts object } } \value{ an Fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=10),matrix(rnorm(20),ncol=2)) x[5,1] <- NA x[10,] <- NA print(x) ## will drop rows where NA's appear ## in any of the columns remove.na.rows(x) ## will drop rows where NA's appear ## in all of the columns remove.all.na.rows(x) } \keyword{ts} fts/man/lead.lag.Rd0000644000176000001440000000122012312122537013600 0ustar ripleyusers\name{lead.lag} \alias{lead.lag.fts} \alias{lead} \alias{lag.fts} \alias{lead.fts} \title{Shift an Fts ojbect in time} \description{ Shift an Fts ojbect forward or backwards in time be the supplied number of periods } \usage{ \method{lead}{fts}(x, k, \dots) \method{lag}{fts}(x, k, \dots) } \arguments{ \item{x}{ An Fts object } \item{k}{ number of periods to shift } \item{\dots}{ further arguments to function } } \details{ removed elements are replaced with NA } \value{ an Fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=10),data=1:10) print(x) lag(x,1) lead(x,1) } \keyword{ts} fts/man/since.na.Rd0000644000176000001440000000060112312322037013626 0ustar ripleyusers\name{since.na} \alias{since.na} \title{Count distance since an NA has occurred} \description{ Count number of rows since an NA has occurred } \usage{ since.na(x) } \arguments{ \item{x}{ An Fts object } } \value{ an Fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),rnorm(100)) x[10,] <- NA since.na(x) } \keyword{ts} fts/man/pad.trim.Rd0000644000176000001440000000136012312316726013661 0ustar ripleyusers\name{pad} \alias{pad.trim} \alias{pad} \alias{trim} \alias{filter.min.obs} \title{pad and trim dates} \description{ add dates to an Fts object by padding w/ additional dates or remove dates from an Fts object by trimming dates } \usage{ pad(x, pad.dates) trim(x, trim.dates) filter.min.obs(x, obs.required) } \arguments{ \item{x}{ An Fts object } \item{pad.dates}{a vector of dates.} \item{trim.dates}{a vector of dates.} \item{obs.required}{number of required observations per row.} } \value{ an fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=5),data=1:5) pad.dates <- index(x)[1] + c(10L,20L) pad(x,pad.dates) trim.dts <- index(x)[c(1,3)] trim(x,trim.dts) } \keyword{ts} fts/man/fill.Rd0000644000176000001440000000136412310604625013071 0ustar ripleyusers\name{fill} \alias{fill} \alias{fill.fwd} \alias{fill.bwd} \alias{fill.value} \title{Fill Missing Values} \description{ Fill a missing value (NA) with any of previous value, next value, or a user supplied value. } \usage{ fill.fwd(x) fill.bwd(x) fill.value(x,value) } \arguments{ \item{x}{ An Fts object } \item{value}{ a value to replace the missing values} } \value{ an Fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=50),rnorm(50)) x[x > 0,] <- NA fill.fwd(x) x <- fts(index=seq(from=Sys.Date(),by="days",length.out=50),rnorm(50)) x[x > 0,] <- NA fill.bwd(x) x <- fts(index=seq(from=Sys.Date(),by="days",length.out=50),rnorm(50)) x[x > 0,] <- NA fill.value(x,100.0) } \keyword{ts} fts/man/moving.Rd0000644000176000001440000000345012312312550013433 0ustar ripleyusers\name{moving} \alias{moving.functions} \alias{moving.mean} \alias{moving.sum} \alias{moving.product} \alias{moving.max} \alias{moving.min} \alias{moving.sd} \alias{moving.rank} \alias{moving.cor} \alias{moving.cov} \alias{cor.by.row} \title{Moving Functions} \description{ apply summary functions on a moving/rolling basis } \usage{ moving.mean(x, periods) moving.sum(x, periods) moving.max(x, periods) moving.min(x, periods) moving.sd(x, periods) moving.rank(x, periods) moving.cor(x, y, periods) moving.cov(x, y, periods) cor.by.row(x,y) } \arguments{ \item{x}{ An Fts object } \item{y}{ An Fts object } \item{periods}{ integer: number of periods in window } } \details{ apply a function that takes a vector and returns a scalar on a rolling basis to an fts object. For cor.by.row, the indicator is not rolling, but is the result of the application of the cor function to matching rows of x and y. asking for a window larger than the number of rows of the fts object will result in an fts of all NA w/ the same number of rows as the input for functions that take two fts objects the date intersection is taken before the window function is applied } \value{ an fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=1:100) y <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=1:100) x.mean <- moving.mean(x,20) x.sum <- moving.sum(x,20) x.prod <- moving.product(x,20) x.max <- moving.max(x,20) x.min <- moving.min(x,20) x.sd <- moving.sd(x,20) x.rank <- moving.rank(x,20) ## take only odd rows ## to illustrate that teh correlation and covariance ## will only be calculated for the intersection of the dates y <- y[(1:nrow(y))\%\%2 == 1] xy.cor <- moving.cor(x, y, 20) xy.cov <- moving.cov(x, y, 20) } \keyword{ts} fts/man/apply.Rd0000644000176000001440000000134012310453055013261 0ustar ripleyusers\name{apply} \alias{apply} \alias{row.apply} \alias{column.apply} \title{Apply Function} \description{ Apply a function to the rows or columns of an fts object } \usage{ column.apply(x, FUN, ...) row.apply(x, FUN, ...) } \arguments{ \item{x}{ An Fts object } \item{FUN}{ function to be applied } \item{\dots}{ further arguments to function } } \value{ an Fts object or vector depending on the fuction type } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="months",length.out=24),data=1:24) y <- fts(index=seq(from=Sys.Date(),by="months",length.out=24),data=1:24) z <- cbind(x,y) ## returns vector z.col.sum <- column.apply(z,sum) ## returns fts z.row.sum <- row.apply(z,sum) } \keyword{ts} fts/man/read.write.fts.Rd0000644000176000001440000000174412312317524015005 0ustar ripleyusers\name{read.write.fts} \alias{read.write.fts} \alias{read.csv.fts} \alias{write.csv.fts} \title{Read / Write Files } \description{ Read / Write files to csv or .RDS format } \usage{ read.csv.fts(file, date.column=1, date.format="\%Y-\%m-\%d", date.convert.fun=as.Date, ...) write.csv.fts(x, file, ...) } \arguments{ \item{x}{ An Fts object } \item{file}{ filename of file to read/write} \item{date.column}{ column that = the dates are in } \item{date.format}{ the format of the date strings } \item{date.convert.fun}{ function to convert dates into desired index class } \item{\dots}{ further arguments to underlying read/write functions } } \value{ a Fts object for functions that read data } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="days",length.out=100),data=1:100) colnames(x) <- "big.ass.black.dog" csv.fname <- paste(tempfile(),".csv",sep="") write.csv.fts(x,csv.fname) y.csv <- read.csv.fts(csv.fname) all.equal(x,y.csv) } \keyword{ts} fts/man/indicators.Rd0000644000176000001440000000504412310452773014306 0ustar ripleyusers\name{indicators} \alias{indicators} \alias{above.ma} \alias{analog} \alias{below.ma} \alias{wday} \alias{mday} \alias{diff.fts} \alias{up} \alias{down} \alias{ema} \alias{gap.continue} \alias{gap.direction} \alias{gap.down} \alias{gap.down.continue} \alias{gap.down.reverse} \alias{gap.reverse} \alias{gap.up} \alias{gap.up.continue} \alias{gap.up.reverse} \alias{higher.high} \alias{higher.low} \alias{hl.oc.ratio} \alias{inside.day} \alias{inside.day.direction} \alias{inside.day.down} \alias{inside.day.up} \alias{lower.high} \alias{lower.low} \alias{ma.crossover} \alias{ma.crossover.down} \alias{ma.crossover.up} \alias{ma.d} \alias{ma.distance} \alias{month} \alias{year} \alias{monthly.sum} \alias{new.high} \alias{new.low} \alias{outside.day} \alias{outside.day.direction} \alias{outside.day.down} \alias{outside.day.up} \alias{pct.chg} \alias{repeated} \alias{rsi} \alias{rsi.crossover} \alias{rsi.crossover.down} \alias{rsi.crossover.up} \alias{template.fts} \alias{trend.day} \alias{trend.day.down} \alias{trend.day.up} \title{Trading indicators} \description{ Various binary indicators for fts objects } \usage{ above.ma(x,n) below.ma(x,n) wday(x) mday(x) \method{diff}{fts}(x,k,\dots) up(x) down(x) ema(x,periods) gap.continue(x) gap.direction(x) gap.down(x) gap.down.continue(x) gap.down.reverse(x) gap.reverse(x) gap.up(x) gap.up.continue(x) gap.up.reverse(x) higher.high(x) higher.low(x) hl.oc.ratio(x) inside.day(x) inside.day.direction(x) inside.day.down(x) inside.day.up(x) lower.high(x) lower.low(x) ma.crossover(x,n) ma.crossover.down(x,n) ma.crossover.up(x,n) ma.d(x,n) ma.distance(x,periods) month(x) year(x) monthly.sum(x) new.high(x,n) new.low(x,n) outside.day(x) outside.day.direction(x) outside.day.down(x) outside.day.up(x) pct.chg(x) repeated(x,times) rsi(x,periods) rsi.crossover(x,periods,thresh) rsi.crossover.down(x,periods,thresh) rsi.crossover.up(x,periods,thresh) template.fts(index, cnames) trend.day(x,thresh) trend.day.down(x,thresh) trend.day.up(x,thresh) } \arguments{ \item{x}{ An Fts object } \item{periods}{ number of periods} \item{n}{ number of periods} \item{k}{ number of lags} \item{times}{ how many times } \item{thresh}{ threshold level} \item{index}{ index to use to construct fts object} \item{cnames}{ colnames to use to construct fts object} \item{\dots}{ further arguments to function } } \details{ removed elements are replaced with NA } \value{ an fts object } \author{ Whit Armstrong } \examples{ x <- fts(index=seq(from=Sys.Date(),by="months",length.out=5),rnorm(5)) print(x) lag(x,1) lead(x,1) } \keyword{ts} fts/man/as.fts.Rd0000644000176000001440000000134212315033603013332 0ustar ripleyusers\name{as.fts} \alias{as.fts} \alias{as.fts.default} \alias{as.fts.data.frame} \alias{as.fts.matrix} \alias{as.fts.zoo} \alias{as.data.frame.fts} \alias{as.matrix.fts} \title{ Convert from/to fts } \description{ convert an object into an fts and vice versa } \usage{ as.fts(x) } \arguments{ \item{x}{ an R matrix or data.frame } } \details{ converts a rectanular object into an Fts object must be able to convert rownames into some form of dates } \value{ an Fts object } \author{ Whit Armstrong } \examples{ N <- 100 xm <- matrix(rnorm(N)) dts <- format(seq(from=Sys.Date(),length.out=N,by="days"),"\%Y-\%m-\%d") rownames(xm) <- dts x.from.m <- as.fts(xm) x.from.df <- as.fts(data.frame(asofdate=dts,my.data=xm)) } \keyword{ts}