Detrended Price Oscillator.

    Formula:
    DPO = DATA[i] - Avg(DATA[period/2 + 1])
511245
def detrended_price_oscillator(data, period):
    
    catch_errors.check_for_period_error(data, period)
    period = int(period)
    dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))]
    dop = fill_for_noncomputable_vals(data, dop)
    return dop
159468
function erf( x ) {
	var sign;
	var ax;
	var z;
	var r;
	var s;
	var y;
	var p;
	var q;

	// Special case: NaN
	if ( x !== x ) {
		return NaN;
	}
	// Special case: +infinity
	if ( x === PINF ) {
		return 1;
	}
	// Special case: -infinity
	if ( x === NINF ) {
		return -1;
	}
	// Special case: +-0
	if ( x === 0 ) {
		return x;
	}
	if ( x < 0 ) {
		sign = true;
		ax = -x;
	} else {
		sign = false;
		ax = x;
	}
	// |x| < 0.84375
	if ( ax < 0.84375 ) {
		if ( ax < SMALL ) {
			if ( ax < VERY_TINY ) {
				// Avoid underflow:
				return 0.125 * (8.0*x + EFX8*x);
			}
			return x + EFX*x;
		}
		z = x * x;
		r = PPC + z*polyvalPP( z );
		s = QQC + z*polyvalQQ( z );
		y = r / s;
		return x + x*y;
	}
	// 0.84375 <= |x| < 1.25
	if ( ax < 1.25 ) {
		s = ax - 1;
		p = PAC + s*polyvalPA( s );
		q = QAC + s*polyvalQA( s );
		if ( sign ) {
			return -ERX - p/q;
		}
		return ERX + p/q;
	}
	// +inf > |x| >= 6
	if ( ax >= 6 ) {
		if ( sign ) {
			return TINY - 1.0; // raise inexact
		}
		return 1.0 - TINY; // raise inexact
	}
	s = 1.0 / (ax*ax);

	// |x| < 1/0.35 ~ 2.857143
	if ( ax < 2.857142857142857 ) {
		r = RAC + s*polyvalRA( s );
		s = SAC + s*polyvalSA( s );
	}
	// |x| >= 1/0.35 ~ 2.857143
	else {
		r = RBC + s*polyvalRB( s );
		s = SBC + s*polyvalSB( s );
	}
	z = setLowWord( ax, 0 ); // pseudo-single (20-bit) precision x
	r = exp( -z*z - 0.5625 ) * exp( (z-ax)*(z+ax) + r/s );
	if ( sign ) {
		return r/ax - 1;
	}
	return 1 - r/ax;
}
368038
def standard_variance(data, period):
    
    catch_errors.check_for_period_error(data, period)
    sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))]
    sv = fill_for_noncomputable_vals(data, sv)

    return sv
1222609
def QA_data_tick_resample(tick, type_='1min'):
    
    tick = tick.assign(amount=tick.price * tick.vol)
    resx = pd.DataFrame()
    _temp = set(tick.index.date)

    for item in _temp:
        _data = tick.loc[str(item)]
        _data1 = _data[time(9,
                            31):time(11,
                                     30)].resample(
                                         type_,
                                         closed='right',
                                         base=30,
                                         loffset=type_
                                     ).apply(
                                         {
                                             'price': 'ohlc',
                                             'vol': 'sum',
                                             'code': 'last',
                                             'amount': 'sum'
                                         }
                                     )

        _data2 = _data[time(13,
                            1):time(15,
                                    0)].resample(
                                        type_,
                                        closed='right',
                                        loffset=type_
                                    ).apply(
                                        {
                                            'price': 'ohlc',
                                            'vol': 'sum',
                                            'code': 'last',
                                            'amount': 'sum'
                                        }
                                    )

        resx = resx.append(_data1).append(_data2)
    resx.columns = resx.columns.droplevel(0)
    return resx.reset_index().drop_duplicates().set_index(['datetime', 'code'])
679090
def mean_harmonic(self):
        ''
        res = self.price.groupby(level=1
                                ).apply(lambda x: statistics.harmonic_mean(x))
        res.name = 'mean_harmonic'
        return res
1296727
def get_R_det2(y_segment, y_avg, y_prime):
    
    numerator = sum((numpy.array(y_segment) - numpy.array(y_prime))**2)
    denominator = sum((numpy.array(y_segment) - y_avg)**2)
    if denominator: # prevent divide by zero error
        R_det2 = 1 - (old_div(numerator, denominator))
        return R_det2
    else:
        return float('nan')
174742
def simple_moving_average(data, period):
    
    catch_errors.check_for_period_error(data, period)
    # Mean of Empty Slice RuntimeWarning doesn't affect output so it is
    # supressed
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=RuntimeWarning)
        sma = [np.mean(data[idx-(period-1):idx+1]) for idx in range(0, len(data))]
    sma = fill_for_noncomputable_vals(data, sma)
    return sma
120071
def moving_average_value(self, date):
        
        val, conti = self.__calculate_moving_average(date, 1)
        val = (round(i / 1000, 3) for i in val)
        return list(val), conti
1184571
def sde(self): 
         
        
        variance = float(self.variance.values)
        lengthscale = float(self.lengthscale.values)

        lamda = np.sqrt(5.0)/lengthscale
        kappa = 5.0/3.0*variance/lengthscale**2        
        
        F = np.array(((0, 1,0), (0, 0, 1), (-lamda**3, -3.0*lamda**2, -3*lamda)))
        L = np.array(((0,),(0,),(1,)))
        Qc = np.array((((variance*400.0*np.sqrt(5.0)/3.0/lengthscale**5),),))
        H = np.array(((1,0,0),))        
        
        Pinf = np.array(((variance,0,-kappa), (0, kappa, 0), (-kappa, 0, 25.0*variance/lengthscale**4)))
        P0 = Pinf.copy()
        # Allocate space for the derivatives         
        dF = np.empty((3,3,2))        
        dQc = np.empty((1,1,2))        
        dPinf = np.empty((3,3,2))
        
         # The partial derivatives 
        dFvariance = np.zeros((3,3))
        dFlengthscale = np.array(((0,0,0),(0,0,0),(15.0*np.sqrt(5.0)/lengthscale**4, 
                                   30.0/lengthscale**3, 3*np.sqrt(5.0)/lengthscale**2)))
        dQcvariance = np.array((((400*np.sqrt(5)/3/lengthscale**5,),)))
        dQclengthscale = np.array((((-variance*2000*np.sqrt(5)/3/lengthscale**6,),)))        
        
        dPinf_variance = Pinf/variance
        kappa2 = -2.0*kappa/lengthscale
        dPinf_lengthscale = np.array(((0,0,-kappa2),(0,kappa2,0),(-kappa2, 
                                    0,-100*variance/lengthscale**5)))        
        # Combine the derivatives 
        dF[:,:,0] = dFvariance
        dF[:,:,1] = dFlengthscale        
        dQc[:,:,0] = dQcvariance         
        dQc[:,:,1] = dQclengthscale        
        dPinf[:,:,0] = dPinf_variance
        dPinf[:,:,1] = dPinf_lengthscale
        dP0 = dPinf.copy()
        
        return (F, L, Qc, H, Pinf, P0, dF, dQc, dPinf, dP0)
1288838
def commodity_channel_index(close_data, high_data, low_data, period):
    
    catch_errors.check_for_input_len_diff(close_data, high_data, low_data)
    catch_errors.check_for_period_error(close_data, period)
    tp = typical_price(close_data, high_data, low_data)
    cci = ((tp - sma(tp, period)) /
           (0.015 * np.mean(np.absolute(tp - np.mean(tp)))))
    return cci
308254
def volume_adjusted_moving_average(close_data, volume, period):
    
    catch_errors.check_for_input_len_diff(close_data, volume)
    catch_errors.check_for_period_error(close_data, period)

    avg_vol = np.mean(volume)
    vol_incr = avg_vol * 0.67
    vol_ratio = [val / vol_incr for val in volume]
    close_vol = np.array(close_data) * vol_ratio
    vama = [sum(close_vol[idx+1-period:idx+1]) / period for idx in range(period-1, len(close_data))]
    vama = fill_for_noncomputable_vals(close_data, vama)
    return vama
430082
def detrend(arr, x=None, deg=5, tol=1e-3, maxloop=10):
    """"""

    xx = numpy.arange(len(arr)) if x is None else x
    base = arr.copy()
    trend = base
    pol = numpy.ones((deg + 1,))
    for _ in range(maxloop):
        pol_new = numpy.polyfit(xx, base, deg)
        pol_norm = numpy.linalg.norm(pol)
        diff_pol_norm = numpy.linalg.norm(pol - pol_new)
        if diff_pol_norm / pol_norm < tol:
            break
        pol = pol_new
        trend = numpy.polyval(pol, xx)
        base = numpy.minimum(base, trend)
    return trend
103690
def generate_single_return_period(args):
    
    qout_file, return_period_file, rivid_index_list, step, num_years, \
        method, mp_lock = args

    skewvals = [-3.0, -2.8, -2.6, -2.4, -2.2, -2.0, -1.8, -1.6, -1.4, -1.2,
                -1.0, -0.8, -0.6, -0.4, -0.2, 0, 0.2, 0.4, 0.6, 0.8, 1.0,
                1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0]
    kfac2 = [0.396, 0.384, 0.368, 0.351, 0.33, 0.307, 0.282, 0.254, 0.225,
             0.195, 0.164, 0.132, 0.099, 0.066, 0.033, 0, -0.033, -0.066,
             -0.099, -0.132, -0.164, -0.195, -0.225, -0.254, -0.282, -0.307,
             -0.33, -0.351, -0.368, -0.384, -0.396]
    kfac10 = [0.66, 0.702, 0.747, 0.795, 0.844, 0.895, 0.945, 0.994, 1.041,
              1.086, 1.128, 1.166, 1.2, 1.231, 1.258, 1.282, 1.301, 1.317,
              1.328, 1.336, 1.34, 1.34, 1.337, 1.329, 1.318, 1.302, 1.284,
              1.262, 1.238, 1.21, 1.18]
    kfac25 = [.666, .712, .764, .823, .888, .959, 1.035, 1.116, 1.198, 1.282,
              1.366, 1.448, 1.528, 1.606, 1.680, 1.751, 1.818, 1.880, 1.939,
              1.993, 2.043, 2.087, 2.128, 2.163, 2.193, 2.219, 2.240, 2.256,
              2.267, 2.275, 2.278]
    kfac50 = [0.666, 0.714, 0.768, 0.83, 0.9, 0.98, 1.069, 1.166, 1.27, 1.379,
              1.492, 1.606, 1.72, 1.834, 1.945, 2.054, 2.159, 2.261, 2.359,
              2.453, 2.542, 2.626, 2.706, 2.78, 2.848, 2.912, 2.97, 3.023,
              3.071, 3.114, 3.152]
    kfac100 = [0.667, 0.714, 0.769, 0.832, 0.905, 0.99, 1.087, 1.197, 1.318,
               1.499, 1.588, 1.733, 1.88, 2.029, 2.178, 2.326, 2.472, 2.615,
               2.755, 2.891, 3.022, 3.149, 3.271, 3.388, 3.499, 3.605, 3.705,
               3.8, 3.889, 3.973, 4.051]

    with RAPIDDataset(qout_file) as qout_nc_file:
        # get index of return period data
        if method == 'weibull':
            rp_index_20 = int((num_years + 1)/20.0)
            rp_index_10 = int((num_years + 1)/10.0)
            rp_index_2 = int((num_years + 1)/2.0)

        if method == 'weibull':
            return_20_array = np.zeros(len(rivid_index_list))
        elif method == 'gumble':
            return_100_array = np.zeros(len(rivid_index_list))
            return_50_array = np.zeros(len(rivid_index_list))
            return_20_array = np.zeros(len(rivid_index_list))
        elif method == 'log_pearson':
            return_100_array = np.zeros(len(rivid_index_list))
            return_50_array = np.zeros(len(rivid_index_list))
            return_25_array = np.zeros(len(rivid_index_list))
        return_10_array = np.zeros(len(rivid_index_list))
        return_2_array = np.zeros(len(rivid_index_list))
        max_flow_array = np.zeros(len(rivid_index_list))

        # iterate through rivids to generate return periods
        for iter_idx, rivid_index in enumerate(rivid_index_list):
            filtered_flow_data = qout_nc_file.get_qout_index(
                rivid_index,
                pd_filter="{0}D".format(step),
                filter_mode="max")
            sorted_flow_data = np.sort(filtered_flow_data)[:num_years:-1]
            max_flow = sorted_flow_data[0]
            if max_flow < 0.01:
                log("Return period data < 0.01 generated for rivid {0}"
                    .format(qout_nc_file.qout_nc.variables[
                        qout_nc_file.river_id_dimension][rivid_index]),
                    "WARNING")
            max_flow_array[iter_idx] = max_flow

            if method == 'weibull':
                return_20_array[iter_idx] = sorted_flow_data[rp_index_20]
                return_10_array[iter_idx] = sorted_flow_data[rp_index_10]
                return_2_array[iter_idx] = sorted_flow_data[rp_index_2]

            elif method == 'gumble':
                mean_flow = np.mean(filtered_flow_data)
                stddev = np.std(filtered_flow_data)
                return_100_array[iter_idx] = mean_flow + 3.14*stddev
                return_50_array[iter_idx] = mean_flow + 2.59*stddev
                return_20_array[iter_idx] = mean_flow + 1.87*stddev
                return_10_array[iter_idx] = mean_flow + 1.3*stddev
                return_2_array[iter_idx] = mean_flow - .164*stddev

            elif method == 'log_pearson':
                log_flow = np.log10(filtered_flow_data[filtered_flow_data > 0])
                if len(log_flow) <= 0:
                    continue
                mean_log_flow = np.mean(log_flow)
                std_log_flow = np.std(log_flow)
                log_flow_array = np.array(log_flow)
                skew = (num_years * (np.sum(
                    np.power((log_flow_array - mean_log_flow), 3)))) / \
                    ((num_years - 1) * (num_years - 2) * std_log_flow ** 3)
                k2 = np.interp(skew, skewvals, kfac2)
                k10 = np.interp(skew, skewvals, kfac10)
                k25 = np.interp(skew, skewvals, kfac25)
                k50 = np.interp(skew, skewvals, kfac50)
                k100 = np.interp(skew, skewvals, kfac100)
                return_100_array[iter_idx] = \
                    np.power(10, (mean_log_flow + k100*std_log_flow))
                return_50_array[iter_idx] = \
                    np.power(10, (mean_log_flow + k50*std_log_flow))
                return_25_array[iter_idx] = \
                    np.power(10, (mean_log_flow + k25*std_log_flow))
                return_10_array[iter_idx] = \
                    np.power(10, (mean_log_flow + k10*std_log_flow))
                return_2_array[iter_idx] = \
                    np.power(10, (mean_log_flow + k2*std_log_flow))

        mp_lock.acquire()
        return_period_nc = Dataset(return_period_file, 'a')
        return_period_nc.variables['max_flow'][rivid_index_list] = \
            max_flow_array
        if method == 'weibull':
            return_period_nc.variables['return_period_20'][
                rivid_index_list] = return_20_array
        elif method in 'gumble':
            return_period_nc.variables['return_period_100'][
                rivid_index_list] = return_100_array
            return_period_nc.variables['return_period_50'][
                rivid_index_list] = return_50_array
            return_period_nc.variables['return_period_20'][
                rivid_index_list] = return_20_array
        elif method == 'log_pearson':
            return_period_nc.variables['return_period_100'][
                rivid_index_list] = return_100_array
            return_period_nc.variables['return_period_50'][
                rivid_index_list] = return_50_array
            return_period_nc.variables['return_period_25'][
                rivid_index_list] = return_25_array
        return_period_nc.variables['return_period_10'][
            rivid_index_list] = return_10_array
        return_period_nc.variables['return_period_2'][
            rivid_index_list] = return_2_array
        return_period_nc.close()
        mp_lock.release()
574939
public function getHistoricalPrice(int $type_id, string $date)
    {

        // If market_prices table is not populated update all entries with both average and adjusted price equals 0.0
        HistoricalPrices::where('average_price', 0.0)->where('adjusted_price', 0.0)
            ->update([
                'average_price'  => is_null(optional(Price::find($type_id))->average_price) ? 0.0 : Price::find($type_id)->average_price,
                'adjusted_price' => is_null(optional(Price::find($type_id))->adjusted_price) ? 0.0 : Price::find($type_id)->adjusted_price,
            ]);

        return HistoricalPrices::firstOrCreate([
            'type_id' => $type_id,
            'date'    => carbon($date)->setTimezone('UTC')->toDateString(),
        ], [
            'date'           => carbon($date)->setTimezone('UTC')->toDateString(),
            'average_price'  => is_null(optional(Price::find($type_id))->average_price) ? 0.0 : Price::find($type_id)->average_price,
            'adjusted_price' => is_null(optional(Price::find($type_id))->adjusted_price) ? 0.0 : Price::find($type_id)->adjusted_price,
        ]);

    }
797938
def hurst_exponent(px, lags=range(2, 100)):
    
    ts = px.reset_index(drop=True).dropna()
    # Calculate the array of the variances of the lagged differences
    tau = [np.sqrt(ts.diff(lag).std()) for lag in lags]
    # Use a linear fit to estimate the Hurst Exponent
    poly = np.polyfit(np.log(lags), np.log(tau), 1)
    # Return the Hurst exponent from the polyfit output
    return poly[0] * 2.0
764058
def sell_holding_pnl(self):
        
        return (self.sell_avg_holding_price - self.last_price) * self.sell_quantity * self.contract_multiplier
281814
def triangular_moving_average(data, period):
    
    catch_errors.check_for_period_error(data, period)

    tma = sma(sma(data, period), period)
    return tma