TimeBasedCV 0.1.1
Time-based splitting for cross-validation
License: Apache License 2.0

# Time-Based Cross-Validation Improved

Overview
The package provides time-based splitting datasets required for training and validating(testing, as referred to by many).
The function returns training set indices and validation set indices using the end validation dates (default to maximum date in the data). The returned indices works like other scikit-learn cross validator.

![alt text](timebasedcv_improved.jpg "Title")

This is somewhat different and an improved version of "Time Based Cross Validation" by Or Herman-Saffar.



## Quick-Start examples
### How to use TimeBasedCV for Machine Learning Modeling

    ###Import necessary libraries
    import pandas as pd
    import numpy as np
    import datetime
    from datetime import datetime as dt
    from dateutil.relativedelta import *
    from sklearn.linear_model import LinearRegression
    import pandas_datareader as pdr
    from TimeBasedCV import TimeBasedCV
    import matplotlib.pyplot as plt
    %matplotlib inline
    
    #Read Historical Apple Stock data - This is just an example
    AAPL = pdr.get_data_yahoo('AAPL')
    
    #How to use TimeBasedCV
    data_for_modeling = AAPL.reset_index() 
    
    ####Example- compute average validate sets score: ####
    X = data_for_modeling.drop(['Adj Close','Close'], axis = 1)
    y = data_for_modeling['Adj Close']
    
    #Modeling with Linear Regression
    scores = []
    val_adj = []
    pred_adj = []
    
    tscv_init = TimeBasedCV(train_period=30,
                            validate_period=7,
                            freq='days',
                            end_validate_date=None,#datetime.date(2020,5,12), 
                            date_column='Date', 
                            gap=4)

    for train_index, val_index in tscv_init.split(X):
        
        
        data_train   = X.loc[train_index].drop('Date', axis=1)
        target_train = y.loc[train_index]
    
        data_val    = X.loc[val_index].drop('Date', axis=1)
        target_val  = y.loc[val_index]
    
        # if needed, do preprocessing here
    
        clf = LinearRegression()
        clf.fit(data_train,target_train)
    
        preds = clf.predict(data_val)
        
        val_adj.extend(target_val)
        pred_adj.extend(preds)
    
        # accuracy for the current fold only    
        r2score = clf.score(data_val,target_val)
    
        scores.append(r2score)
    
    #this is the average accuracy over all folds
    average_r2score = np.mean(scores)
    print(average_r2score)
    ####End of example ####

### How to use TimeBasedCV for Machine Learning Hyperparameter Tuning

    ####Example- RandomizedSearchCV ####
    from sklearn.model_selection import RandomizedSearchCV
    from random import randint, uniform
    import xgboost as xgb
    
    tscv_init = TimeBasedCV(train_period=30,
                            validate_period=7,
                            freq='days',
                            end_validate_date=None,#datetime.date(2020,5,12), 
                            date_column='Date', 
                            gap=4)
    
    index_output = tscv_init.split(data_for_modeling)
    
    xg = xgb.XGBRegressor(silent=True)
    
    xgpam = {" max_depth": [-1,2,3]
             }
    
    model = RandomizedSearchCV(
        estimator = xg,
        param_distributions = xgpam,
        n_iter = 10,
        n_jobs = -1,
        iid = True,
        cv = index_output,
        verbose=5,
        pre_dispatch='2*n_jobs',
        random_state = None,
        return_train_score = True)
    
    model.fit(X.drop('Date', axis=1),y)
    model.cv_results_
    ####End of example ####