Beispiel #1
0
def coinTossWinnerGraph(cur, ax):
    cur.execute('use IPL_DATA_SET');
    cur.execute('Select Tosswinner, count(*) from Matches group by Tosswinner');
    QuerryResponse = cur.fetchall();
    Teams = []
    TeamWinCount = []
    for i in range(0,len(QuerryResponse)):
        Teams.insert(0,QuerryResponse[i][0]);
        TeamWinCount.insert(0,QuerryResponse[i][1]);
    ax.scatter(Teams,TeamWinCount);
    ax.set_title('Coin Toss Wins');
    plt.xlabel('Team')
    plt.ylabel('Number of Wins');
    ax.xaxis.set_label_coords(0.50, 0.075);
    plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    plt.tick_params(axis='x', which='major', labelsize=7)
    crs = mplcursors.cursor(ax,hover=True)
Beispiel #2
0
def draw_networkx_nodes(G, pos,
                        nodelist=None,
                        node_size=300,
                        node_color='r',
                        node_shape='o',
                        alpha=1.0,
                        cmap=None,
                        vmin=None,
                        vmax=None,
                        ax=None,
                        linewidths=None,
                        label=None,
                        **kwds):
    """Draw the nodes of the graph G.

    This draws only the nodes of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    nodelist : list, optional
       Draw only specified nodes (default G.nodes())

    node_size : scalar or array
       Size of nodes (default=300).  If an array is specified it must be the
       same length as nodelist.

    node_color : color string, or array of floats
       Node color. Can be a single color format string (default='r'),
       or a  sequence of colors with the same length as nodelist.
       If numeric values are specified they will be mapped to
       colors using the cmap and vmin,vmax parameters.  See
       matplotlib.scatter for more details.

    node_shape :  string
       The shape of the node.  Specification is as matplotlib.scatter
       marker, one of 'so^>v<dph8' (default='o').

    alpha : float
       The node transparency (default=1.0)

    cmap : Matplotlib colormap
       Colormap for mapping intensities of nodes (default=None)

    vmin,vmax : floats
       Minimum and maximum for node colormap scaling (default=None)

    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collections.PathCollection
        `PathCollection` of the nodes.

    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> nodes=nx.draw_networkx_nodes(G,pos=nx.spring_layout(G))

    Also see the NetworkX drawing examples at
    http://networkx.github.io/documentation/latest/gallery.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib.pyplot as plt
        import numpy
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if nodelist is None:
        nodelist = G.nodes()

    if not nodelist or len(nodelist) == 0:  # empty nodelist, no drawing
        return None

    try:
        xy = numpy.asarray([pos[v] for v in nodelist])
    except KeyError as e:
        raise nx.NetworkXError('Node %s has no position.'%e)
    except ValueError:
        raise nx.NetworkXError('Bad value in node positions.')

    node_collection = ax.scatter(xy[:, 0], xy[:, 1],
                                 s=node_size,
                                 c=node_color,
                                 marker=node_shape,
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax,
                                 alpha=alpha,
                                 linewidths=linewidths,
                                 label=label,
                                 **kwds)

    node_collection.set_zorder(2)
    return node_collection
Beispiel #3
0
def plot_corr_diff(tseries1, tseries2, fig=None,
                  ts_names=['1', '2']):
    """
    Show the differences in *Fischer-transformed* snr correlations for two
    time-series

    Parameters
    ----------
    tseries1, tseries2 : nitime TimeSeries objects
       These are the time-series to compare, with each of them having the
       dims: (n_channels, n_reps, time), where n_channels1 = n_channels2

    lb,ub: float
       Lower and upper bounds on the frequency range over which to
       calculate the information rate (default to [0,Nyquist]).

    fig: matplotlib figure object
       If you want to do this on already existing figure. Otherwise, a new
       figure object will be generated.

    ts_names: list of str
       Labels for the two inputs, to be used in plotting (defaults to
       ['1','2'])

    bandwidth, adaptive, low_bias: See :func:`SNRAnalyzer` for details


    Returns
    -------

    fig: a matplotlib figure object
    """

    if fig is None:
        fig = plt.figure()

    ax = fig.add_subplot(1, 1, 1)

    SNR1 = []
    SNR2 = []
    corr1 = []
    corr2 = []
    corr_e1 = []
    corr_e2 = []

    for i in range(tseries1.shape[0]):
        SNR1.append(nta.SNRAnalyzer(ts.TimeSeries(tseries1.data[i],
                                    sampling_rate=tseries1.sampling_rate)))

        corr1.append(np.arctanh(np.abs(SNR1[-1].correlation[0])))
        corr_e1.append(SNR1[-1].correlation[1])

        SNR2.append(nta.SNRAnalyzer(ts.TimeSeries(tseries2.data[i],
                                    sampling_rate=tseries2.sampling_rate)))

        corr2.append(np.arctanh(np.abs(SNR2[-1].correlation[0])))
        corr_e2.append(SNR1[-1].correlation[1])

    ax.scatter(np.array(corr1), np.array(corr2))
    ax.errorbar(np.mean(corr1), np.mean(corr2),
                 yerr=np.std(corr2),
                 xerr=np.std(corr1))
    plot_min = min(min(corr1), min(corr2))
    plot_max = max(max(corr1), max(corr2))
    ax.plot([plot_min, plot_max], [plot_min, plot_max], 'k--')
    ax.set_xlabel('Correlation (Fischer Z) %s' % ts_names[0])
    ax.set_ylabel('Correlation (Fischer Z) %s' % ts_names[1])

    return fig, corr1, corr2
Beispiel #4
0
def plotTSs1(start_date, end_date, shortMa, longMa):
    yf.pdr_override()
    plt.close()
    shortMaP = int(shortMa)
    longMaP = int(longMa)

    data = pdr.get_data_yahoo("BTC-USD", start_date, end_date)
    btc = pd.DataFrame(data)

    btc = btc[['Adj Close']]
    btc.columns = ['price']
    btc.reset_index(level=0, inplace=True)

    ###################################################################################

    # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading
    #[online] DataCamp Community. Available at: <https://www.datacamp.com/community/tutorials/finance-python-trading#basics>

    plt.close()

    signal = pd.DataFrame(index=btc.index)  #copy index from BTC

    signal['id'] = 0.0

    signal['shortMA'] = btc['price'].rolling(
        window=shortMaP,
        min_periods=1).mean()  #Short Moving Average Calculated

    signal['longMA'] = btc['price'].rolling(
        window=longMaP, min_periods=1).mean()  ##Long Moving Average Calculated

    signal['id'][shortMaP:] = np.where(
        signal['shortMA'][shortMaP:] > signal['longMA'][shortMaP:], 1.0,
        0.0)  #where short moving average surpasses long, id is changed to 1

    #[shortMaP:] only for the period that is surpasses than the short moving average

    signal['buySell'] = signal['id'].diff()

    fig = plt.figure()

    ax1 = fig.add_subplot(111, ylabel=' Currency Price in $')

    ax1.plot(btc.price)  #Plot price
    # Plot the short and long moving averages
    ax1.plot(signal['shortMA'], color='black', label='Short Moving Average')
    ax1.plot(signal['longMA'], color='orange', label='Long Moving Average')
    ax1.legend(loc='upper right')

    # The buy signals according to buySell are plotted
    ax1.plot(signal.loc[signal.buySell == 1.0].index,
             signal.shortMA[signal.buySell == 1.0],
             '^',
             markersize=10,
             color='green')

    # The sell signals according to buySell are plotted
    ax1.plot(signal.loc[signal.buySell == -1.0].index,
             signal.shortMA[signal.buySell == -1.0],
             'v',
             markersize=10,
             color='red')

    # Show the plot
    plt.show()

    ###################################################################################
    # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading

    portfolio = pd.DataFrame(index=signal.index)

    initInvestment = 100000
    stocksOwned = pd.DataFrame(index=signal.index).fillna(0.0)

    noCur = 10  #No of currency to be purchased

    stocksOwned['BTC'] = noCur * signal['id']

    portfolio['Holdings'] = stocksOwned['BTC'].multiply(btc['price'], axis=0)

    buySell = stocksOwned['BTC'].diff()

    portfolio['cash'] = initInvestment - (buySell.multiply(btc['price'],
                                                           axis=0)).cumsum()

    portfolio['total'] = portfolio['cash'] + portfolio['Holdings']

    portfolio['cash'][0] = initInvestment
    portfolio['total'][0] = initInvestment

    ###################################################################################

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.plot(portfolio.index, portfolio['total'], label='Price')
    ax.set_xlabel('Date')
    ax.set_ylabel('Value of Portfolio in $')

    day = portfolio.loc[signal.buySell == 1.0].index
    day2 = portfolio.loc[signal.buySell == -1.0].index

    #x co
    ax.scatter(x=day, y=portfolio.loc[day, 'total'], color='green', marker='^')
    ax.scatter(x=day2, y=portfolio.loc[day2, 'total'], color='red', marker='^')
Beispiel #5
0
def draw_networkx_nodes(G,
                        pos,
                        nodelist=None,
                        node_size=300,
                        node_color='r',
                        node_shape='o',
                        alpha=1.0,
                        cmap=None,
                        vmin=None,
                        vmax=None,
                        ax=None,
                        linewidths=None,
                        label=None,
                        **kwds):
    """Draw the nodes of the graph G.

    This draws only the nodes of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    nodelist : list, optional
       Draw only specified nodes (default G.nodes())

    node_size : scalar or array
       Size of nodes (default=300).  If an array is specified it must be the
       same length as nodelist.

    node_color : color string, or array of floats
       Node color. Can be a single color format string (default='r'),
       or a  sequence of colors with the same length as nodelist.
       If numeric values are specified they will be mapped to
       colors using the cmap and vmin,vmax parameters.  See
       matplotlib.scatter for more details.

    node_shape :  string
       The shape of the node.  Specification is as matplotlib.scatter
       marker, one of 'so^>v<dph8' (default='o').

    alpha : float
       The node transparency (default=1.0)

    cmap : Matplotlib colormap
       Colormap for mapping intensities of nodes (default=None)

    vmin,vmax : floats
       Minimum and maximum for node colormap scaling (default=None)

    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collections.PathCollection
        `PathCollection` of the nodes.

    Examples
    --------
    >>> G=nx.dodecahedral_graph()
    >>> nodes=nx.draw_networkx_nodes(G,pos=nx.spring_layout(G))

    Also see the NetworkX drawing examples at
    http://networkx.github.io/documentation/latest/gallery.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_edges()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib.pyplot as plt
        import numpy
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if nodelist is None:
        nodelist = G.nodes()

    if not nodelist or len(nodelist) == 0:  # empty nodelist, no drawing
        return None

    try:
        xy = numpy.asarray([pos[v] for v in nodelist])
    except KeyError as e:
        raise nx.NetworkXError('Node %s has no position.' % e)
    except ValueError:
        raise nx.NetworkXError('Bad value in node positions.')

    node_collection = ax.scatter(xy[:, 0],
                                 xy[:, 1],
                                 s=node_size,
                                 c=node_color,
                                 marker=node_shape,
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax,
                                 alpha=alpha,
                                 linewidths=linewidths,
                                 label=label,
                                 **kwds)

    node_collection.set_zorder(2)
    return node_collection
Beispiel #6
0
def plot_corr_diff(tseries1, tseries2, fig=None, ts_names=['1', '2']):
    """
    Show the differences in *Fischer-transformed* snr correlations for two
    time-series

    Parameters
    ----------
    tseries1, tseries2 : nitime TimeSeries objects
       These are the time-series to compare, with each of them having the
       dims: (n_channels, n_reps, time), where n_channels1 = n_channels2

    lb,ub: float
       Lower and upper bounds on the frequency range over which to
       calculate the information rate (default to [0,Nyquist]).

    fig: matplotlib figure object
       If you want to do this on already existing figure. Otherwise, a new
       figure object will be generated.

    ts_names: list of str
       Labels for the two inputs, to be used in plotting (defaults to
       ['1','2'])

    bandwidth, adaptive, low_bias: See :func:`SNRAnalyzer` for details


    Returns
    -------

    fig: a matplotlib figure object
    """

    if fig is None:
        fig = plt.figure()

    ax = fig.add_subplot(1, 1, 1)

    SNR1 = []
    SNR2 = []
    corr1 = []
    corr2 = []
    corr_e1 = []
    corr_e2 = []

    for i in range(tseries1.shape[0]):
        SNR1.append(
            nta.SNRAnalyzer(
                ts.TimeSeries(tseries1.data[i],
                              sampling_rate=tseries1.sampling_rate)))

        corr1.append(np.arctanh(np.abs(SNR1[-1].correlation[0])))
        corr_e1.append(SNR1[-1].correlation[1])

        SNR2.append(
            nta.SNRAnalyzer(
                ts.TimeSeries(tseries2.data[i],
                              sampling_rate=tseries2.sampling_rate)))

        corr2.append(np.arctanh(np.abs(SNR2[-1].correlation[0])))
        corr_e2.append(SNR1[-1].correlation[1])

    ax.scatter(np.array(corr1), np.array(corr2))
    ax.errorbar(np.mean(corr1),
                np.mean(corr2),
                yerr=np.std(corr2),
                xerr=np.std(corr1))
    plot_min = min(min(corr1), min(corr2))
    plot_max = max(max(corr1), max(corr2))
    ax.plot([plot_min, plot_max], [plot_min, plot_max], 'k--')
    ax.set_xlabel('Correlation (Fischer Z) %s' % ts_names[0])
    ax.set_ylabel('Correlation (Fischer Z) %s' % ts_names[1])

    return fig, corr1, corr2
Beispiel #7
0
def plotTsS2(start_date, end_date):

    plt.close()
    yf.pdr_override()

    data = pdr.get_data_yahoo("BTC-USD", start_date, end_date)
    btc = pd.DataFrame(data)

    btc = btc[['Adj Close']]
    btc.columns = ['Close']
    btc.reset_index(level=0, inplace=True)

    b = pd.DataFrame()

    for x in btc:
        b['price'] = btc['Close']
        b['sma'] = btc['Close'].rolling(window=20).mean()
        b['std'] = btc['Close'].rolling(window=20).std()

        b['bolU'] = b['sma'] + (2 * b['std'])  #Calculating Upper Bound
        b['bolD'] = b['sma'] - (2 * b['std'])  #Calculating Lower Bound
        #Convert Bollinger Bands to %b - bollinger column
        b['bollinger'] = (b['price'] - b['bolD']) / (b['bolU'] - b['bolD'])

    bb1 = b[['price', 'bolU', 'bolD', 'bollinger']]
    bb1.columns = ['Price', 'Upper Band', 'Lower Band', 'Bollinger']
    bb1.fillna(0, inplace=True)

    # In[ ]:

    # In[9]:

    RSI = pd.DataFrame(index=btc.index)

    RSI['price'] = btc['Close']

    RSI['val'] = None
    RSI['up'] = 0  #When there is no up  value 0
    RSI['down'] = 0  #When there is no down   value 0

    size = RSI.shape[0]
    dp = 14

    for x in range(size):
        if x == 0:
            continue  #first day will continue
        #calculating the ups , when closing price is higher in day x than x -1
        if RSI['price'].iloc[x] > RSI['price'].iloc[x - 1]:  #
            RSI['up'].iloc[x] = RSI['price'].iloc[x] - RSI['price'].iloc[x - 1]
        else:
            #calculating the downs days , when closing price is lower in day x than x -1
            RSI['down'].iloc[x] = RSI['price'].iloc[x -
                                                    1] - RSI['price'].iloc[x]

        if x >= dp:
            avgUp = RSI['up'][x - dp:x].sum(
            ) / dp  #calculates avg up of last dp days
            avgDown = RSI['down'][x - dp:x].sum(
            ) / dp  #calculates avg down of last dp days
            rs = avgUp / avgDown  #calculation of RS
            RSI['val'].iloc[x] = 100 - 100 / (1 + rs)

    signals = pd.DataFrame(index=btc.index)  #copy index for BTC

    signals['price'] = btc['Close']
    signals['id'] = 0.0

    signals['RSI'] = RSI['val']
    signals['RSI'].fillna(0, inplace=True)

    signals['bollinger'] = bb1['Bollinger']

    signals['id'] = [np.nan for i in signals.index]

    # only  verifications for days after DPth (period of RSI) day
    signals['id'][dp:].loc[((signals['RSI'] < 30) &
                            (signals['bollinger'] < 0))] = 1
    signals['id'][dp:].loc[((signals['RSI'] > 70) &
                            (signals['bollinger'] > 1))] = 0
    signals['id'].ffill(inplace=True)  #fill empty values with 0
    signals['id'].fillna(0, inplace=True)

    signals['buySell'] = signals['id'].diff()
    signals['buySell'].fillna(0, inplace=True)

    fig, (ax) = plt.subplots(1, 1)

    ax.plot(signals['price'])
    ax.set_xlabel('Date')
    ax.set_ylabel('Value in $')
    day = signals.loc[signals.buySell == 1.0].index
    day2 = signals.loc[signals.buySell == -1.0].index

    #x cordinates, index of day    --> y cordinate,price of day index
    ax.scatter(
        x=day,
        y=signals.loc[day, 'price'],
        marker='^',
        color='green',
    )
    ax.scatter(x=day2, y=signals.loc[day2, 'price'], marker='v', color='red')

    plt.show()
Beispiel #8
0
def plotPorts2(start_date, end_date):
    plt.close()
    yf.pdr_override()

    data = pdr.get_data_yahoo("BTC-USD", start_date, end_date)
    btc = pd.DataFrame(data)

    btc = btc[['Adj Close']]
    btc.columns = ['Close']
    btc.reset_index(level=0, inplace=True)

    # In[8]:

    b = pd.DataFrame()

    for x in btc:
        b['price'] = btc['Close']
        b['sma'] = btc['Close'].rolling(window=20).mean()
        b['std'] = btc['Close'].rolling(window=20).std()

        b['bolU'] = b['sma'] + (2 * b['std'])  #Calculating Upper Bound
        b['bolD'] = b['sma'] - (2 * b['std'])  #Calculating Lower Bound
        #Convert Bollinger Bands to %b - bollinger column
        b['bollinger'] = (b['price'] - b['bolD']) / (b['bolU'] - b['bolD'])

    bb1 = b[['price', 'bolU', 'bolD', 'bollinger']]
    bb1.columns = ['Price', 'Upper Band', 'Lower Band', 'Bollinger']
    bb1.fillna(0, inplace=True)

    # In[ ]:

    # In[9]:

    RSI = pd.DataFrame(index=btc.index)

    RSI['price'] = btc['Close']

    RSI['val'] = None
    RSI['up'] = 0  #When there is no up  value 0
    RSI['down'] = 0  #When there is no down   value 0

    size = RSI.shape[0]
    dp = 14

    for x in range(size):
        if x == 0:
            continue  #first day will continue
        #calculating the ups , when closing price is higher in day x than x -1
        if RSI['price'].iloc[x] > RSI['price'].iloc[x - 1]:  #
            RSI['up'].iloc[x] = RSI['price'].iloc[x] - RSI['price'].iloc[x - 1]
        else:
            #calculating the downs days , when closing price is lower in day x than x -1
            RSI['down'].iloc[x] = RSI['price'].iloc[x -
                                                    1] - RSI['price'].iloc[x]

        if x >= dp:
            avgUp = RSI['up'][x - dp:x].sum(
            ) / dp  #calculates avg up of last dp days
            avgDown = RSI['down'][x - dp:x].sum(
            ) / dp  #calculates avg down of last dp days
            rs = avgUp / avgDown  #calculation of RS
            RSI['val'].iloc[x] = 100 - 100 / (1 + rs)

    signals = pd.DataFrame(index=btc.index)  #copy index for BTC

    signals['price'] = btc['Close']
    signals['id'] = 0.0

    signals['RSI'] = RSI['val']
    signals['RSI'].fillna(0, inplace=True)

    signals['bollinger'] = bb1['Bollinger']

    signals['id'] = [np.nan for i in signals.index]

    # only  verifications for days after DPth (period of RSI) day
    signals['id'][dp:].loc[((signals['RSI'] < 30) &
                            (signals['bollinger'] < 0))] = 1
    signals['id'][dp:].loc[((signals['RSI'] > 70) &
                            (signals['bollinger'] > 1))] = 0
    signals['id'].ffill(inplace=True)  #fill empty values with 0
    signals['id'].fillna(0, inplace=True)

    signals['buySell'] = signals['id'].diff()
    signals['buySell'].fillna(0, inplace=True)

    ###################################################################################
    # Code taken from Willems, K., 2019. (Tutorial) Python For Finance: Algorithmic Trading

    initInvestment = 100000
    stocksOwned = pd.DataFrame(index=signals.index).fillna(0.0)

    noCur = 10  #No of currency to be purchased

    stocksOwned['BTC'] = noCur * signals['id']

    portfolio = pd.DataFrame(index=signals.index)
    portfolio['Holdings'] = stocksOwned['BTC'].multiply(btc['Close'], axis=0)

    buySell = stocksOwned['BTC'].diff()

    portfolio['cash'] = initInvestment - (buySell.multiply(btc['Close'],
                                                           axis=0)).cumsum()

    portfolio['total'] = portfolio['cash'] + portfolio['Holdings']

    portfolio['cash'][0] = initInvestment
    portfolio['total'][0] = initInvestment

    ###################################################################################

    # In[50]:

    fig, (ax) = plt.subplots(1, 1, sharex=True)

    ax.plot(portfolio.index, portfolio['total'], label='Price')
    ax.set_xlabel('Date')
    ax.set_ylabel('Value of portfolio in USD')
    day = signals.loc[signals.buySell == 1.0].index
    day2 = signals.loc[signals.buySell == -1.0].index

    ax.scatter(x=day, y=portfolio.loc[day, 'total'], color='green')
    ax.scatter(x=day2, y=portfolio.loc[day2, 'total'], color='red')

    plt.show()