Calculate the RSI (Relative Strength Index) within N days

        calculated based on the formula at:
        https://en.wikipedia.org/wiki/Relative_strength_index

        :param df: data
        :param n_days: N days
        :return: None
176620
def _get_rsi(cls, df, n_days):
        
        n_days = int(n_days)
        d = df['close_-1_d']

        df['closepm'] = (d + d.abs()) / 2
        df['closenm'] = (-d + d.abs()) / 2
        closepm_smma_column = 'closepm_{}_smma'.format(n_days)
        closenm_smma_column = 'closenm_{}_smma'.format(n_days)
        p_ema = df[closepm_smma_column]
        n_ema = df[closenm_smma_column]

        rs_column_name = 'rs_{}'.format(n_days)
        rsi_column_name = 'rsi_{}'.format(n_days)
        df[rs_column_name] = rs = p_ema / n_ema
        df[rsi_column_name] = 100 - 100 / (1.0 + rs)

        del df['closepm']
        del df['closenm']
        del df[closepm_smma_column]
        del df[closenm_smma_column]
1302413
def get_yield_stress(self, n):
        
        # TODO: root finding could be more robust
        comp = root(self.get_stability_criteria, -1, args=n)
        tens = root(self.get_stability_criteria, 1, args=n)
        return (comp.x, tens.x)
1099551
def stoch(df, window=14, d=3, k=3, fast=False):
    

    my_df = pd.DataFrame(index=df.index)

    my_df['rolling_max'] = df['high'].rolling(window).max()
    my_df['rolling_min'] = df['low'].rolling(window).min()

    my_df['fast_k'] = 100 * (df['close'] - my_df['rolling_min'])/(my_df['rolling_max'] - my_df['rolling_min'])
    my_df['fast_d'] = my_df['fast_k'].rolling(d).mean()

    if fast:
        return my_df.loc[:, ['fast_k', 'fast_d']]

    my_df['slow_k'] = my_df['fast_k'].rolling(k).mean()
    my_df['slow_d'] = my_df['slow_k'].rolling(d).mean()

    return my_df.loc[:, ['slow_k', 'slow_d']]
1061588
def fs_r_sup(self, DF, N=None):
		
		if not hasattr(self, 'G'):
			self.fs_c(N=self.rank)  # generate G

		if N and (not isinstance(N, int) or N <= 0):
			raise ValueError("ncols should be a positive integer.")
		s = -sqrt(self.E) if self.cor else self.s
		N = min(N, self.rank) if N else self.rank
		S_inv = diagsvd(-1/s[:N], len(self.G.T), N)
		# S = diagsvd(s[:N], len(self.tau), N)
		return _mul(DF.div(DF.sum(axis=1), axis=0), self.G, S_inv)[:, :N]
1242798
def QA_indicator_DDI(DataFrame, N=13, N1=26, M=1, M1=5):
    

    H = DataFrame['high']
    L = DataFrame['low']
    DMZ = IF((H + L) > (REF(H, 1) + REF(L, 1)), 
             MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
    DMF = IF((H + L) < (REF(H, 1) + REF(L, 1)),
             MAX(ABS(H - REF(H, 1)), ABS(L - REF(L, 1))), 0)
    DIZ = SUM(DMZ, N) / (SUM(DMZ, N) + SUM(DMF, N))
    DIF = SUM(DMF, N) / (SUM(DMF, N) + SUM(DMZ, N))
    ddi = DIZ - DIF
    ADDI = SMA(ddi, N1, M)
    AD = MA(ADDI, M1)
    DICT = {'DDI': ddi, 'ADDI': ADDI, 'AD': AD}

    return pd.DataFrame(DICT)
1306817
def offset(self, date, n_days):
        '''
        
        '''
#CONSIDER: raise an exception if a date is not in self
        index = self.index(date) + n_days
        if index < 0:
            index = 0
        if index > len(self) - 1:
            index = len(self) - 1
        return self[index]
1024502
def CV(self, days=45):
    
    if len(self.raw_data) >= days:
      data_avg = sum(self.raw_data[-days:]) / days
      return self.SD / data_avg
    else:
      return 0
1048128
def getCoeffs(date):
    
    if date < 1900.0 or date > 2025.0:
        print('This subroutine will not work with a date of ' + str(date))
        print('Date must be in the range 1900.0 <= date <= 2025.0')
        print('On return [], []')
        return [], []
    elif date >= 2015.0:
        if date > 2020.0:
            # not adapt for the model but can calculate
            print('This version of the IGRF is intended for use up to 2020.0.')
            print('values for ' + str(date) + ' will be computed but may be of reduced accuracy')
        t = date - 2015.0
        tc = 1.0
        #     pointer for last coefficient in pen-ultimate set of MF coefficients...
        ll = 3060
        nmx = 13
        nc = nmx * (nmx + 2)
    else:
        t = 0.2 * (date - 1900.0)
        ll = int(t)
        t = t - ll
        #     SH models before 1995.0 are only to degree 10
        if date < 1995.0:
            nmx = 10
            nc = nmx * (nmx + 2)
            ll = nc * ll
        else:
            nmx = 13
            nc = nmx * (nmx + 2)
            ll = round(0.2 * (date - 1995.0))
            #     19 is the number of SH models that extend to degree 10
            ll = 120 * 19 + nc * ll
        tc = 1.0 - t

    g, h = [], []
    temp = ll-1
    for n in range(nmx+1):
        g.append([])
        h.append([])
        if n == 0:
            g[0].append(None)
        for m in range(n+1):
            if m != 0:
                g[n].append(tc*gh[temp] + t*gh[temp+nc])
                h[n].append(tc*gh[temp+1] + t*gh[temp+nc+1])
                temp += 2
                # print(n, m, g[n][m], h[n][m])
            else:
                g[n].append(tc*gh[temp] + t*gh[temp+nc])
                h[n].append(None)
                temp += 1
                # print(n, m, g[n][m], h[n][m])
    return g, h
205807
def correl(df,periods=21,columns=None,include=True,str=None,detail=False,how='value',**correl_kwargs):
	
	def _correl(df,periods=21,columns=None,include=True,str=None,detail=False,**correl_kwargs):
		study='CORREL'
		df,_df,columns=validate(df,columns)

		_df['CORREL'] = df[columns[0]].rolling(window=periods,**correl_kwargs).corr(df[columns[1]])

		str=str if str else 'CORREL({column1},{column2},{period})'.format(column1=columns[0],column2=columns[1],period=periods)
		return rename(df,_df,study,periods,columns,include,str,detail)
	columns=df.columns if not columns else columns
	if len(columns) != 2: 
		raise StudyError("2 Columns need to be specified for a correlation study")
	periods=make_list(periods)
	if how=='pct_chg':
		df=df[columns].pct_change()
	elif how=='diff':
		df=df[columns].diff()
	__df=pd.concat([_correl(df,columns=columns,periods=y,include=False,str=str) for y in periods],axis=1)
	if include:
		return pd.concat([df,__df],axis=1)
	else:
		return __df
59480
def dataframe(self):
        
        if self._points_for is None and self._points_against is None:
            return None
        fields_to_include = {
            'boxscore_index': self.boxscore_index,
            'date': self.date,
            'datetime': self.datetime,
            'day_of_week': self.day_of_week,
            'game': self.game,
            'location': self.location,
            'losses': self.losses,
            'opponent_abbr': self.opponent_abbr,
            'opponent_conference': self.opponent_conference,
            'opponent_name': self.opponent_name,
            'opponent_rank': self.opponent_rank,
            'points_against': self.points_against,
            'points_for': self.points_for,
            'rank': self.rank,
            'result': self.result,
            'streak': self.streak,
            'time': self.time,
            'wins': self.wins
        }
        return pd.DataFrame([fields_to_include], index=[self._boxscore])
1353749
def dysmetria_score(self, data_frame):
        
        tap_data = data_frame[data_frame.action_type == 0]
        ds = np.mean(np.sqrt((tap_data.x - tap_data.x_target) ** 2 + (tap_data.y - tap_data.y_target) ** 2))
        duration = math.ceil(data_frame.td[-1])
        return ds, duration
1305901
def __calculate_bu_dfs(dfs_data):
    """"""
    u = dfs_data['ordering'][0]
    b = {}
    b[u] = D(u, dfs_data)
    __calculate_bu_dfs_recursively(u, b, dfs_data)
    return b
873330
def rsi(series, window=14):
    

    # 100-(100/relative_strength)
    deltas = np.diff(series)
    seed = deltas[:window + 1]

    # default values
    ups = seed[seed > 0].sum() / window
    downs = -seed[seed < 0].sum() / window
    rsival = np.zeros_like(series)
    rsival[:window] = 100. - 100. / (1. + ups / downs)

    # period values
    for i in range(window, len(series)):
        delta = deltas[i - 1]
        if delta > 0:
            upval = delta
            downval = 0
        else:
            upval = 0
            downval = -delta

        ups = (ups * (window - 1) + upval) / window
        downs = (downs * (window - 1.) + downval) / window
        rsival[i] = 100. - 100. / (1. + ups / downs)

    # return rsival
    return pd.Series(index=series.index, data=rsival)
1300023
def incoordination_score(self, data_frame):
        
        diff = data_frame.td[1:-1].values - data_frame.td[0:-2].values
        inc_s = np.var(diff[np.arange(1, len(diff), 2)], dtype=np.float64) * 1000.0
        duration = math.ceil(data_frame.td[-1])
        return inc_s, duration
415112
def preprocess(df):
    """"""

    def process_row(idx_row):
        idx, row = idx_row

        # press-press latency
        tau = 1000 * row[4::3].astype(float).values
        tau = np.r_[np.median(tau), tau]

        # duration
        duration = 1000 * row[3::3].astype(float).values

        keyname = list('.tie5Roanl') + ['enter']

        return pd.DataFrame.from_items([
            ('user', [row['subject']] * 11),
            ('session', [row['sessionIndex'] * 100 + row['rep']] * 11),
            ('tau', tau),
            ('duration', duration),
            ('event', keyname)
        ])

    df = pd.concat(map(process_row, df.iterrows())).set_index(['user', 'session'])
    return df
1043500
private void calculateInside(int spanStart, int spanEnd, CfgParseChart chart, double[] newValues) {
    double[] binaryRuleValues = binaryDistributionWeights.getValues();
    
    int leftIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), leftVar.getOnlyVariableNum());
    int rightIndex = Ints.indexOf(binaryDistributionWeights.getDimensionNumbers(), rightVar.getOnlyVariableNum());
    
    for (int i = 0; i < spanEnd - spanStart; i++) {
      double[] left = chart.getInsideEntriesArray(spanStart, spanStart + i);
      double[] right = chart.getInsideEntriesArray(spanStart + i + 1, spanEnd);

      for (int j = 0; j < newValues.length; j++) {
        newValues[j] = binaryRuleValues[j] * left[binaryDistributionWeights.indexToPartialDimKey(j, leftIndex)]
            * right[binaryDistributionWeights.indexToPartialDimKey(j, rightIndex)];
      }

      chart.updateInsideEntry(spanStart, spanEnd, i, newValues, binaryDistribution);
    }
  }
404846
def data_len_for_day(self, day):
        
        day_ix = self._session_labels.get_loc(day)
        # Add one to the 0-indexed day_ix to get the number of days.
        num_days = day_ix + 1
        return num_days * self._minutes_per_day