示例#1
0
def pascals_triangle(n: int = None, **kwargs: dict) -> npNdArray:
    """Pascal's Triangle

    Returns a numpy array of the nth row of Pascal's Triangle.
    n=4  => triangle: [1, 4, 6, 4, 1]
         => weighted: [0.0625, 0.25, 0.375, 0.25, 0.0625]
         => inverse weighted: [0.9375, 0.75, 0.625, 0.75, 0.9375]
    """
    n = int(npFabs(n)) if n is not None else 0

    # Calculation
    triangle = npArray([combination(n=n, r=i) for i in range(0, n + 1)])
    triangle_sum = npSum(triangle)
    triangle_weights = triangle / triangle_sum
    inverse_weights = 1 - triangle_weights

    weighted = kwargs.pop("weighted", False)
    inverse = kwargs.pop("inverse", False)
    if weighted and inverse:
        return inverse_weights
    if weighted:
        return triangle_weights
    if inverse:
        return None

    return triangle
示例#2
0
def fibonacci(n: int = 2, **kwargs: dict) -> npNdArray:
    """Fibonacci Sequence as a numpy array"""
    n = int(npFabs(n)) if n >= 0 else 2

    zero = kwargs.pop("zero", False)
    if zero:
        a, b = 0, 1
    else:
        n -= 1
        a, b = 1, 1

    result = npArray([a])
    for _ in range(0, n):
        a, b = b, a + b
        result = npAppend(result, a)

    weighted = kwargs.pop("weighted", False)
    if weighted:
        fib_sum = npSum(result)
        if fib_sum > 0:
            return result / fib_sum
        else:
            return result
    else:
        return result
示例#3
0
    def getChat(self):
        frame = ImageGrab.grab(self.coords)
        frame.convert()

        frame_gray: cv2 = cvtColor(npArray(frame), COLOR_RGB2GRAY)
        imwrite(f'img_fgr.jpg', frame_gray)
        # chat = frame_gray
        # _, chat = cv2.threshold(frame_gray,i*10,255,cv2.THRESH_BINARY)
        # _, chat = cv2.threshold(frame_gray,i*10,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
        # chat = cv2.adaptiveThreshold(frame_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
        # for i in range(25):
        #     _, chat = cv2.threshold(frame_gray,i*10,255,cv2.THRESH_BINARY)
        #     chat = cv2.bitwise_not(chat)
        #     cv2.imwrite(f'img{i}.jpg', chat)
        if np.mean(frame_gray[:10, :10]) < 122:
            frame_gray = bitwise_not(frame_gray)
        padding = 20
        frame_gray = copyMakeBorder(frame_gray, padding, padding, padding,
                                    padding, BORDER_REPLICATE)
        imwrite(f'img_fgr2.jpg', frame_gray)
        # _, chat = cv2.threshold(frame_gray, 80, 255, cv2.THRESH_BINARY)
        # chat = cv2.ximgproc.niBlackThreshold(frame_gray, 255, cv2.THRESH_BINARY, 9, 0, cv2.ximgproc.BINARIZATION_SAUVOLA)
        # _, chat = cv2.threshold(frame_gray, 50, 255, 0)
        # cv2.imwrite(f'imgx1.jpg', chat)
        # chat = cv2.ximgproc.thinning(chat, thinningType=cv2.ximgproc.THINNING_GUOHALL)
        # cv2.imwrite(f'imgx2.jpg', chat)
        return frame_gray
def findParabola(p0,p1,p2):
    # Always of the form y = a * x^2 + b * x + c
    fcoeffs = lambda x,y : (x*x , x , 1, y)
    # Map points to arrays of coeffecients (variable array, solution array) 
    arr0 = fcoeffs(p0.x,p0.y)
    arr1 = fcoeffs(p1.x,p1.y)
    arr2 = fcoeffs(p2.x,p2.y)
    # Solve system of equations
    from numpy import array as npArray
    from numpy.linalg import solve
    # Varaible arrary
    arrV = npArray([
                    arr0[0:-1], 
                    arr1[0:-1],
                    arr2[0:-1]
                    ])
    # Solution array ... = arrS
    arrS = npArray([arr0[3],arr1[3],arr2[3]])
    coeff = solve(arrV,arrS)
    # Give the parameters needed to construct parabola (a,b,c) for y=ax^2+bx+c
    return coeff
def copyGrid(grid, elementGennerator=None):
    """
    Returns an empty Sudoku grid.

    Parameters:
        - elementGennerator (function) (optional=None): Is is used to generate initial values of the grid's elements.
            If it's not given, all grid's elements will be "None".
    """

    return npArray([[
        (0 if elementGennerator is None else elementGennerator(i, j))
        for j in range(len(grid))
    ] for i in range(len(grid))])
def _concatArrays(arrs):
	"""
	Mimics MATLAB array flattening behaviour.

	@arrs [[int], [int]]  
		Arbitrary 2D array.

	@returns [int]        
		All arrays, flattened.
	"""
	flattened = []
	[ flattened.extend(arrs[i]) for i in range(len(arrs)) ]
	return npArray(flattened)
def encodePuzzle(grid):
    """
    Returns chromosome of Sudoku puzzle. The chromosome of a puzzle is 
    defined as an array of 81 numbers that is divided into nine sub block.

    Parameters:
        - grid: Sudoku puzzle
    """
    chromosome = [[] for i in range(DIGIT_NUMBER)]
    for j in range(DIGIT_NUMBER):
        for i in range(DIGIT_NUMBER):
            chromosome[int(i / BLOCK_NUMBER) +
                       int(j / BLOCK_NUMBER) * BLOCK_NUMBER].append(grid[j][i])

    return npArray(chromosome)
    def _plot(self,
              df,
              mas: bool = True,
              constants: bool = False,
              **kwargs) -> None:

        if constants:
            chart_lines = npAppend(npArange(-5, 6, 1), npArange(-100, 110, 10))
            df.ta.constants(True,
                            chart_lines)  # Adding the constants for the charts
            df.ta.constants(False, npArray(
                [-60, -40, 40,
                 60]))  # Removing some constants from the DataFrame
            if self.verbose: print(f"[i] {df.ticker} constants added.")

        if ta.Imports["matplotlib"]:
            _exchange = kwargs.pop("exchange", "NYSE")
            _time = ta.get_time(_exchange, to_string=True)
            _kind = kwargs.pop("plot_kind", None)
            _figsize = kwargs.pop("figsize", (16, 10))
            _colors = kwargs.pop("figsize",
                                 ["black", "green", "orange", "red", "maroon"])
            _grid = kwargs.pop("grid", True)
            _alpha = kwargs.pop("alpha", 1)
            _last = kwargs.pop("last", 252)
            _title = kwargs.pop("title",
                                f"{df.ticker}   {_time}   [{self.ds_name}]")

            col = kwargs.pop("close", "close")
            if mas:
                # df.ta.strategy(self.strategy, append=True)
                price = df[[col, "SMA_10", "SMA_20", "SMA_50", "SMA_200"]]
            else:
                price = df[col]

            if _kind is None:
                price.tail(_last).plot(figsize=_figsize,
                                       color=_colors,
                                       linewidth=2,
                                       title=_title,
                                       grid=_grid,
                                       alpha=_alpha)
            else:
                print(f"[X] Plot kind not implemented")
                return
def decodePuzzle(chromosome):
    """
    Returns Sudoku puzzle of chromosome.

    Parameters:
        - chromosome: Chromosome.
    """
    grid = zerosLike(chromosome)

    i = 0
    for a, b in sameColumnIndexes(0, 0, BLOCK_NUMBER):
        row = list(
            getCellsFromIndexes(chromosome, sameRowIndexes(a, b,
                                                           BLOCK_NUMBER)))
        grid[i] = npArray(row)
        i += 1

    return grid
示例#10
0
def dailySeizureDistributionComparison(request):
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    from matplotlib.dates import DateFormatter
    from datetime import timedelta
    from numpy import array as npArray

    import seaborn as sns
    sns.set(style="darkgrid", palette="Set2")

    seizureFrequency = Seizure.objects.getSeizuresPerNight()
    fig = Figure(facecolor="white", figsize=(12, 6))
    ax = fig.add_subplot(111)

    duration = []
    time = []
    for day in seizureFrequency:
        duration.append([dayI.duration for dayI in day])
        time.append([dayI.time for dayI in day])

    plots = []
    labels = []
    for setI in range(len(duration)):
        p, = ax.plot(npArray(time[setI]) - timedelta(days=setI, hours=-2),
                     duration[setI],
                     marker='o')
        plots.append(p)
        labels.append("%s" % time[setI][0].strftime("%d-%m-%Y"))

    fig.legend(plots, labels, 'upper right', bbox_to_anchor=(1.01, 1))
    fig.autofmt_xdate()
    ax.grid(True)
    ax.set_xlabel("Time of sampling interval [h]")
    ax.set_ylabel("Seizure duration [s]")

    canvas = FigureCanvas(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)

    return response
示例#11
0
def linreg(close, length=None, offset=None, **kwargs):
    """Indicator: Linear Regression"""
    # Validate arguments
    length = int(length) if length and length > 0 else 14
    close = verify_series(close, length)
    offset = get_offset(offset)
    angle = kwargs.pop("angle", False)
    intercept = kwargs.pop("intercept", False)
    degrees = kwargs.pop("degrees", False)
    r = kwargs.pop("r", False)
    slope = kwargs.pop("slope", False)
    tsf = kwargs.pop("tsf", False)

    if close is None: return

    # Calculate Result
    x = range(1, length + 1)  # [1, 2, ..., n] from 1 to n keeps Sum(xy) low
    x_sum = 0.5 * length * (length + 1)
    x2_sum = x_sum * (2 * length + 1) / 3
    divisor = length * x2_sum - x_sum * x_sum

    def linear_regression(series):
        y_sum = series.sum()
        xy_sum = (x * series).sum()

        m = (length * xy_sum - x_sum * y_sum) / divisor
        if slope:
            return m
        b = (y_sum * x2_sum - x_sum * xy_sum) / divisor
        if intercept:
            return b

        if angle:
            theta = npAtan(m)
            if degrees:
                theta *= 180 / npPi
            return theta

        if r:
            y2_sum = (series * series).sum()
            rn = length * xy_sum - x_sum * y_sum
            rd = (divisor * (length * y2_sum - y_sum * y_sum)) ** 0.5
            return rn / rd

        return m * length + b if tsf else m * (length - 1) + b

    linreg_ = [linear_regression(_) for _ in sliding_window_view(npArray(close), length)]
    linreg = Series([npNaN] * (length - 1) + linreg_, index=close.index)

    # Offset
    if offset != 0:
        linreg = linreg.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        linreg.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        linreg.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    linreg.name = f"LR"
    if slope: linreg.name += "m"
    if intercept: linreg.name += "b"
    if angle: linreg.name += "a"
    if r: linreg.name += "r"

    linreg.name += f"_{length}"
    linreg.category = "overlap"

    return linreg
示例#12
0
def linreg(close, length=None, offset=None, **kwargs):
    """Indicator: Linear Regression"""
    # Validate arguments
    length = int(length) if length and length > 0 else 14
    close = verify_series(close, length)
    offset = get_offset(offset)
    angle = kwargs.pop("angle", False)
    intercept = kwargs.pop("intercept", False)
    degrees = kwargs.pop("degrees", False)
    r = kwargs.pop("r", False)
    slope = kwargs.pop("slope", False)
    tsf = kwargs.pop("tsf", False)

    if close is None: return

    # Calculate Result
    x = range(1, length + 1)  # [1, 2, ..., n] from 1 to n keeps Sum(xy) low
    x_sum = 0.5 * length * (length + 1)
    x2_sum = x_sum * (2 * length + 1) / 3
    divisor = length * x2_sum - x_sum * x_sum

    def linear_regression(series):
        y_sum = series.sum()
        xy_sum = (x * series).sum()

        m = (length * xy_sum - x_sum * y_sum) / divisor
        if slope:
            return m
        b = (y_sum * x2_sum - x_sum * xy_sum) / divisor
        if intercept:
            return b

        if angle:
            theta = npAtan(m)
            if degrees:
                theta *= 180 / npPi
            return theta

        if r:
            y2_sum = (series * series).sum()
            rn = length * xy_sum - x_sum * y_sum
            rd = (divisor * (length * y2_sum - y_sum * y_sum)) ** 0.5
            return rn / rd

        return m * length + b if tsf else m * (length - 1) + b

    def rolling_window(array, length):
        """https://github.com/twopirllc/pandas-ta/issues/285"""
        strides = array.strides + (array.strides[-1],)
        shape = array.shape[:-1] + (array.shape[-1] - length + 1, length)
        return as_strided(array, shape=shape, strides=strides)

    if npVersion >= "1.20.0":
        from numpy.lib.stride_tricks import sliding_window_view
        linreg_ = [linear_regression(_) for _ in sliding_window_view(npArray(close), length)]
    else:
        from numpy.lib.stride_tricks import as_strided
        linreg_ = [linear_regression(_) for _ in rolling_window(npArray(close), length)]

    linreg = Series([npNaN] * (length - 1) + linreg_, index=close.index)

    # Offset
    if offset != 0:
        linreg = linreg.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        linreg.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        linreg.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    linreg.name = f"LR"
    if slope: linreg.name += "m"
    if intercept: linreg.name += "b"
    if angle: linreg.name += "a"
    if r: linreg.name += "r"

    linreg.name += f"_{length}"
    linreg.category = "overlap"

    return linreg
示例#13
0
def tos_stdevall(close,
                 length=None,
                 stds=None,
                 ddof=None,
                 offset=None,
                 **kwargs):
    """Indicator: TD Ameritrade's Think or Swim Standard Deviation All"""
    # Validate Arguments
    stds = stds if isinstance(stds, list) and len(stds) > 0 else [1, 2, 3]
    if min(stds) <= 0: return
    if not all(i < j for i, j in zip(stds, stds[1:])):
        stds = stds[::-1]
    ddof = int(ddof) if ddof and ddof >= 0 and ddof < length else 1
    offset = get_offset(offset)

    if length is None:
        length = close.size
        _props = f"STDEVALL"
    else:
        length = int(length) if length and length > 2 else 30
        close = close.iloc[-length:]
        _props = f"STDEVALL_{length}"

    close = verify_series(close, length)

    if close is None: return

    # Calculate Result
    if isinstance(close.index, DatetimeIndex):
        close_ = npArray(close)
        np_index = npArange(length)
        m, b = npPolyfit(np_index, close_, 1)
        lr_ = m * np_index + b
    else:
        m, b = npPolyfit(close.index, close, 1)
        lr_ = m * close.index + b

    lr = Series(lr_, index=close.index)
    stdevall = stdev(Series(close), length=length, ddof=ddof)
    # std = npStd(close, ddof=ddof)

    # Name and Categorize it
    df = DataFrame({f"{_props}_LR": lr}, index=close.index)
    for i in stds:
        df[f"{_props}_L_{i}"] = lr - i * stdevall.iloc[-1]
        df[f"{_props}_U_{i}"] = lr + i * stdevall.iloc[-1]
        df[f"{_props}_L_{i}"].name = df[f"{_props}_U_{i}"].name = f"{_props}"
        df[f"{_props}_L_{i}"].category = df[
            f"{_props}_U_{i}"].category = "statistics"

    # Offset
    if offset != 0:
        df = df.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        df.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        df.fillna(method=kwargs["fill_method"], inplace=True)

    # Prepare DataFrame to return
    df.name = f"{_props}"
    df.category = "statistics"

    return df
示例#14
0
            y2_sum = sum(series ** 2)
            rn = length * xy_sum - x_sum * y_sum
            rd = (divisor * (length * y2_sum - y_sum * y_sum)) ** 0.5
            return rn / rd

        return m * length + b if tsf else m * (length - 1) + b

<<<<<<< HEAD
    values = [
        linear_regression(each)
        for each in np.lib.stride_tricks.sliding_window_view(np.array(close), length)
    ]
    linreg = pd.Series([np.NaN] * (length - 1) + values)
    linreg.index = close.index
=======
    linreg_ = [linear_regression(_) for _ in sliding_window_view(npArray(close), length)]
    linreg = Series([npNaN] * (length - 1) + linreg_, index=close.index)
>>>>>>> b2f2cc83a16376c1eb0a11aebed52186d7eab121

    # Offset
    if offset != 0:
        linreg = linreg.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        linreg.fillna(kwargs["fillna"], inplace=True)
    if "fill_method" in kwargs:
        linreg.fillna(method=kwargs["fill_method"], inplace=True)

    # Name and Categorize it
    linreg.name = f"LR"