import streamlit as st

def app():
    import yfinance as yf
    import streamlit as st
    import datetime 
    import matplotlib.pyplot as plt
    import talib 
    import ta
    import numpy as np
    import matplotlib.ticker as mticker
    import pandas as pd
    import requests
    yf.pdr_override()
    
    st.write("""
    # Technical Analysis of Securites
    Shown below are the **Moving Average Crossovers**, **Bollinger Bands**, **MACD's**, **Commodity Channel Indexes**, **Relative Strength Indexes** and **Extended Market Calculators** of any stock
    """)
    
    st.sidebar.header('User Input Parameters')
    
    today = datetime.date.today()
    def user_input_features():
        ticker = st.sidebar.text_input("Ticker", 'GME')
        start_date = st.sidebar.text_input("Start Date", '2019-01-01')
        end_date = st.sidebar.text_input("End Date", f'{today}')
        return ticker, start_date, end_date
        
    symbol, start, end = user_input_features()
    
    def get_symbol(symbol):
        cticker = yf.Ticker(symbol)
        company_name = cticker.info['longName']
        return company_name
    company_name = get_symbol(symbol.upper())
    
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    
    # Read data 
    data = yf.download(symbol,start,end)
    
    # Adjusted Close Price
    st.header(f"""
            Adjusted Close Price\n {company_name}
            """)
    st.line_chart(data['Adj Close'])
    
    # ## SMA and EMA
    #Simple Moving Average
    data['SMA'] = talib.SMA(data['Adj Close'], timeperiod = 20)
    
    # Exponential Moving Average
    data['EMA'] = talib.EMA(data['Adj Close'], timeperiod = 20)
    
    # Plot
    st.header(f"""
            Simple Moving Average vs. Exponential Moving Average\n {company_name}
            """)
    st.line_chart(data[['Adj Close','SMA','EMA']])
    
    # Bollinger Bands
    data['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS(data['Adj Close'], timeperiod =20)
    
    # Plot
    st.header(f"""
            Bollinger Bands\n {company_name}
            """)
    st.line_chart(data[['Adj Close','upper_band','middle_band','lower_band']])
    
    # ## MACD (Moving Average Convergence Divergence)
    # MACD
    data['macd'], data['macdsignal'], data['macdhist'] = talib.MACD(data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9)
    
    # Plot
    st.header(f"""Moving Average Convergence Divergence\n {company_name}""")
    st.line_chart(data[['macd','macdsignal']])
    
    ## CCI (Commodity Channel Index)
    # CCI
    cci = ta.trend.cci(data['High'], data['Low'], data['Close'], 31, 0.015)
    
    # Plot
    st.header(f"""Commodity Channel Index\n {company_name}""")
    st.line_chart(cci)
    
    # ## RSI (Relative Strength Index)
    # RSI
    data['RSI'] = talib.RSI(data['Adj Close'], timeperiod=14)
    
    # Plot
    st.header(f"""Relative Strength Index\n {company_name}""")
    st.line_chart(data['RSI'])
    
    # ## OBV (On Balance Volume)
    # OBV
    data['OBV'] = talib.OBV(data['Adj Close'], data['Volume'])/10**6
    
    # Plot
    st.header(f"""On Balance Volume\n {company_name}""")
    st.line_chart(data['OBV'])
    
    # Extended Market
    fig, ax1 = plt.subplots() 
    
    #Asks for stock ticker
    sma = 50
    limit = 10
    
    data = yf.download(symbol,start, today)
    
    #calculates sma and creates a column in the dataframe
    data['SMA'+str(sma)] = data.iloc[:,4].rolling(window=sma).mean() 
    data['PC'] = ((data["Adj Close"]/data['SMA'+str(sma)])-1)*100
    
    mean = round(data["PC"].mean(), 2)
    stdev = round(data["PC"].std(), 2)
    current= round(data["PC"][-1], 2)
    yday= round(data["PC"][-2], 2)
    
    stats = [['Mean', mean], ['Standard Deviation', stdev], ['Current', current], ['Yesterday', yday]]
    
    frame = pd.DataFrame(stats,columns = ['Statistic', 'Value'])
    
    st.header(f"""Extended Market Calculator\n {company_name}""")
    st.dataframe(frame.style.hide_index())
    
    # fixed bin size
    bins = np.arange(-100, 100, 1) 
    plt.rcParams['figure.figsize'] = 15, 10
    plt.xlim([data["PC"].min()-5, data["PC"].max()+5])
    
    plt.hist(data["PC"], bins=bins, alpha=0.5)
    plt.title(symbol+"-- % From "+str(sma)+" SMA Histogram since "+str(start.year))
    plt.xlabel('Percent from '+str(sma)+' SMA (bin size = 1)')
    plt.ylabel('Count')
    
    plt.axvline( x=mean, ymin=0, ymax=1, color='k', linestyle='--')
    plt.axvline( x=stdev+mean, ymin=0, ymax=1, color='gray', alpha=1, linestyle='--')
    plt.axvline( x=2*stdev+mean, ymin=0, ymax=1, color='gray',alpha=.75, linestyle='--')
    plt.axvline( x=3*stdev+mean, ymin=0, ymax=1, color='gray', alpha=.5, linestyle='--')
    plt.axvline( x=-stdev+mean, ymin=0, ymax=1, color='gray', alpha=1, linestyle='--')
    plt.axvline( x=-2*stdev+mean, ymin=0, ymax=1, color='gray',alpha=.75, linestyle='--')
    plt.axvline( x=-3*stdev+mean, ymin=0, ymax=1, color='gray', alpha=.5, linestyle='--')
    
    plt.axvline( x=current, ymin=0, ymax=1, color='r', label = 'today')
    plt.axvline( x=yday, ymin=0, ymax=1, color='blue', label = 'yesterday')
    
    #add more x axis labels
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(14)) 
    st.pyplot(fig)
    
    #Create Plots
    fig2, ax2 = plt.subplots() 
    data=data[-150:]
    
    data['PC'].plot(label='close',color='k')
    plt.title(symbol+"-- % From "+str(sma)+" SMA Over last 100 days")
    plt.xlabel('Date') 
    plt.ylabel('Percent from '+str(sma)+' EMA')
    
    #add more x axis labels
    ax2.xaxis.set_major_locator(mticker.MaxNLocator(8)) 
    plt.axhline( y=limit, xmin=0, xmax=1, color='r')
    plt.rcParams['figure.figsize'] = 15, 10
    st.pyplot(fig2)

[((14, 4, 14, 21), 'yfinance.pdr_override', 'yf.pdr_override', ({}, {}), '()', True, 'import yfinance as yf\n'), ((16, 4, 19, 8), 'streamlit.write', 'st.write', ({(16, 13, 19, 7): '"""\n    # Technical Analysis of Securites\n    Shown below are the **Moving Average Crossovers**, **Bollinger Bands**, **MACD\'s**, **Commodity Channel Indexes**, **Relative Strength Indexes** and **Extended Market Calculators** of any stock\n    """'}, {}), '(\n    """\n    # Technical Analysis of Securites\n    Shown below are the **Moving Average Crossovers**, **Bollinger Bands**, **MACD\'s**, **Commodity Channel Indexes**, **Relative Strength Indexes** and **Extended Market Calculators** of any stock\n    """\n    )', True, 'import streamlit as st\n'), ((21, 4, 21, 46), 'streamlit.sidebar.header', 'st.sidebar.header', ({(21, 22, 21, 45): '"""User Input Parameters"""'}, {}), "('User Input Parameters')", True, 'import streamlit as st\n'), ((23, 12, 23, 33), 'datetime.date.today', 'datetime.date.today', ({}, {}), '()', False, 'import datetime\n'), ((38, 12, 38, 33), 'pandas.to_datetime', 'pd.to_datetime', ({(38, 27, 38, 32): 'start'}, {}), '(start)', True, 'import pandas as pd\n'), ((39, 10, 39, 29), 'pandas.to_datetime', 'pd.to_datetime', ({(39, 25, 39, 28): 'end'}, {}), '(end)', True, 'import pandas as pd\n'), ((42, 11, 42, 40), 'yfinance.download', 'yf.download', ({(42, 23, 42, 29): 'symbol', (42, 30, 42, 35): 'start', (42, 36, 42, 39): 'end'}, {}), '(symbol, start, end)', True, 'import yfinance as yf\n'), ((45, 4, 47, 16), 'streamlit.header', 'st.header', ({(45, 14, 47, 15): 'f"""\n            Adjusted Close Price\n {company_name}\n            """'}, {}), '(f"""\n            Adjusted Close Price\n {company_name}\n            """\n    )', True, 'import streamlit as st\n'), ((48, 4, 48, 36), 'streamlit.line_chart', 'st.line_chart', ({(48, 18, 48, 35): "data['Adj Close']"}, {}), "(data['Adj Close'])", True, 'import streamlit as st\n'), ((52, 18, 52, 63), 'talib.SMA', 'talib.SMA', (), '', False, 'import talib\n'), ((55, 18, 55, 63), 'talib.EMA', 'talib.EMA', (), '', False, 'import talib\n'), ((58, 4, 60, 16), 'streamlit.header', 'st.header', ({(58, 14, 60, 15): 'f"""\n            Simple Moving Average vs. Exponential Moving Average\n {company_name}\n            """'}, {}), '(\n    f"""\n            Simple Moving Average vs. Exponential Moving Average\n {company_name}\n            """\n    )', True, 'import streamlit as st\n'), ((61, 4, 61, 50), 'streamlit.line_chart', 'st.line_chart', ({(61, 18, 61, 49): "data[['Adj Close', 'SMA', 'EMA']]"}, {}), "(data[['Adj Close', 'SMA', 'EMA']])", True, 'import streamlit as st\n'), ((64, 66, 64, 113), 'talib.BBANDS', 'talib.BBANDS', (), '', False, 'import talib\n'), ((67, 4, 69, 16), 'streamlit.header', 'st.header', ({(67, 14, 69, 15): 'f"""\n            Bollinger Bands\n {company_name}\n            """'}, {}), '(f"""\n            Bollinger Bands\n {company_name}\n            """)', True, 'import streamlit as st\n'), ((70, 4, 70, 78), 'streamlit.line_chart', 'st.line_chart', ({(70, 18, 70, 77): "data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']]"}, {}), "(data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']])", True, 'import streamlit as st\n'), ((74, 57, 74, 132), 'talib.MACD', 'talib.MACD', (), '', False, 'import talib\n'), ((77, 4, 77, 76), 'streamlit.header', 'st.header', ({(77, 14, 77, 75): 'f"""Moving Average Convergence Divergence\n {company_name}"""'}, {}), '(f"""Moving Average Convergence Divergence\n {company_name}""")', True, 'import streamlit as st\n'), ((78, 4, 78, 46), 'streamlit.line_chart', 'st.line_chart', ({(78, 18, 78, 45): "data[['macd', 'macdsignal']]"}, {}), "(data[['macd', 'macdsignal']])", True, 'import streamlit as st\n'), ((82, 10, 82, 75), 'ta.trend.cci', 'ta.trend.cci', ({(82, 23, 82, 35): "data['High']", (82, 37, 82, 48): "data['Low']", (82, 50, 82, 63): "data['Close']", (82, 65, 82, 67): '31', (82, 69, 82, 74): '0.015'}, {}), "(data['High'], data['Low'], data['Close'], 31, 0.015)", False, 'import ta\n'), ((85, 4, 85, 62), 'streamlit.header', 'st.header', ({(85, 14, 85, 61): 'f"""Commodity Channel Index\n {company_name}"""'}, {}), '(f"""Commodity Channel Index\n {company_name}""")', True, 'import streamlit as st\n'), ((86, 4, 86, 22), 'streamlit.line_chart', 'st.line_chart', ({(86, 18, 86, 21): 'cci'}, {}), '(cci)', True, 'import streamlit as st\n'), ((90, 18, 90, 61), 'talib.RSI', 'talib.RSI', (), '', False, 'import talib\n'), ((93, 4, 93, 62), 'streamlit.header', 'st.header', ({(93, 14, 93, 61): 'f"""Relative Strength Index\n {company_name}"""'}, {}), '(f"""Relative Strength Index\n {company_name}""")', True, 'import streamlit as st\n'), ((94, 4, 94, 30), 'streamlit.line_chart', 'st.line_chart', ({(94, 18, 94, 29): "data['RSI']"}, {}), "(data['RSI'])", True, 'import streamlit as st\n'), ((101, 4, 101, 56), 'streamlit.header', 'st.header', ({(101, 14, 101, 55): 'f"""On Balance Volume\n {company_name}"""'}, {}), '(f"""On Balance Volume\n {company_name}""")', True, 'import streamlit as st\n'), ((102, 4, 102, 30), 'streamlit.line_chart', 'st.line_chart', ({(102, 18, 102, 29): "data['OBV']"}, {}), "(data['OBV'])", True, 'import streamlit as st\n'), ((105, 15, 105, 29), 'matplotlib.pyplot.subplots', 'plt.subplots', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((111, 11, 111, 43), 'yfinance.download', 'yf.download', ({(111, 23, 111, 29): 'symbol', (111, 30, 111, 35): 'start', (111, 37, 111, 42): 'today'}, {}), '(symbol, start, today)', True, 'import yfinance as yf\n'), ((124, 12, 124, 64), 'pandas.DataFrame', 'pd.DataFrame', (), '', True, 'import pandas as pd\n'), ((126, 4, 126, 65), 'streamlit.header', 'st.header', ({(126, 14, 126, 64): 'f"""Extended Market Calculator\n {company_name}"""'}, {}), '(f"""Extended Market Calculator\n {company_name}""")', True, 'import streamlit as st\n'), ((130, 11, 130, 34), 'numpy.arange', 'np.arange', ({(130, 21, 130, 25): '-100', (130, 27, 130, 30): '100', (130, 32, 130, 33): '1'}, {}), '(-100, 100, 1)', True, 'import numpy as np\n'), ((134, 4, 134, 46), 'matplotlib.pyplot.hist', 'plt.hist', (), '', True, 'import matplotlib.pyplot as plt\n'), ((137, 4, 137, 23), 'matplotlib.pyplot.ylabel', 'plt.ylabel', ({(137, 15, 137, 22): '"""Count"""'}, {}), "('Count')", True, 'import matplotlib.pyplot as plt\n'), ((139, 4, 139, 67), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((140, 4, 140, 85), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((141, 4, 141, 88), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((142, 4, 142, 88), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((143, 4, 143, 86), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((144, 4, 144, 89), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((145, 4, 145, 89), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((147, 4, 147, 71), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((148, 4, 148, 75), 'matplotlib.pyplot.axvline', 'plt.axvline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((152, 4, 152, 18), 'streamlit.pyplot', 'st.pyplot', ({(152, 14, 152, 17): 'fig'}, {}), '(fig)', True, 'import streamlit as st\n'), ((155, 16, 155, 30), 'matplotlib.pyplot.subplots', 'plt.subplots', ({}, {}), '()', True, 'import matplotlib.pyplot as plt\n'), ((160, 4, 160, 22), 'matplotlib.pyplot.xlabel', 'plt.xlabel', ({(160, 15, 160, 21): '"""Date"""'}, {}), "('Date')", True, 'import matplotlib.pyplot as plt\n'), ((165, 4, 165, 52), 'matplotlib.pyplot.axhline', 'plt.axhline', (), '', True, 'import matplotlib.pyplot as plt\n'), ((167, 4, 167, 19), 'streamlit.pyplot', 'st.pyplot', ({(167, 14, 167, 18): 'fig2'}, {}), '(fig2)', True, 'import streamlit as st\n'), ((25, 17, 25, 55), 'streamlit.sidebar.text_input', 'st.sidebar.text_input', ({(25, 39, 25, 47): '"""Ticker"""', (25, 49, 25, 54): '"""GME"""'}, {}), "('Ticker', 'GME')", True, 'import streamlit as st\n'), ((26, 21, 26, 70), 'streamlit.sidebar.text_input', 'st.sidebar.text_input', ({(26, 43, 26, 55): '"""Start Date"""', (26, 57, 26, 69): '"""2019-01-01"""'}, {}), "('Start Date', '2019-01-01')", True, 'import streamlit as st\n'), ((27, 19, 27, 64), 'streamlit.sidebar.text_input', 'st.sidebar.text_input', ({(27, 41, 27, 51): '"""End Date"""', (27, 53, 27, 63): 'f"""{today}"""'}, {}), "('End Date', f'{today}')", True, 'import streamlit as st\n'), ((33, 18, 33, 35), 'yfinance.Ticker', 'yf.Ticker', ({(33, 28, 33, 34): 'symbol'}, {}), '(symbol)', True, 'import yfinance as yf\n'), ((98, 18, 98, 62), 'talib.OBV', 'talib.OBV', ({(98, 28, 98, 45): "data['Adj Close']", (98, 47, 98, 61): "data['Volume']"}, {}), "(data['Adj Close'], data['Volume'])", False, 'import talib\n'), ((151, 32, 151, 55), 'matplotlib.ticker.MaxNLocator', 'mticker.MaxNLocator', ({(151, 52, 151, 54): '(14)'}, {}), '(14)', True, 'import matplotlib.ticker as mticker\n'), ((164, 32, 164, 54), 'matplotlib.ticker.MaxNLocator', 'mticker.MaxNLocator', ({(164, 52, 164, 53): '(8)'}, {}), '(8)', True, 'import matplotlib.ticker as mticker\n')]