def portfolio_optimization():
  def get_Position(weights,amount):
    weights = [i*amount for i in weights]
    stks = normed_stocks * weights
    stks['Total Position']=stks.sum(axis=1)
    return stks

  def cagr(f,l,y):
    return((round(l,2)/round(f,2))**(1/float(y)) - 1)

  def calc_portfolio_perf_VaR(weights, cov, alpha, days):
      
    #amount here is investment amount
    portfolio = portfolio_stocks * (weights*amount)
    portfolio['Total Position']=portfolio.sum(axis=1)
    portfolio_return = cagr(portfolio['Total Position'].iloc[0],portfolio['Total Position'].iloc[-1],11)
    
    portfolio_std = np.sqrt(np.dot(weights.T, np.dot(cov, weights))) * np.sqrt(days)
    portfolio_var = abs(portfolio_return - (portfolio_std * stats.norm.ppf(1 - alpha)))
    return portfolio_return, portfolio_std, portfolio_var

  def simulate_random_portfolios_VaR(num_portfolios, no_of_stocks, cov, alpha, days):

    results_matrix = np.zeros((no_of_stocks+3, num_portfolios))
    my_bar = st.progress(0)
    for i in range(num_portfolios):
      weights = np.random.random(no_of_stocks)
      weights /= np.sum(weights)
      portfolio_return, portfolio_std, portfolio_VaR = calc_portfolio_perf_VaR(weights, cov, alpha, days)
      results_matrix[0,i] = portfolio_return
      results_matrix[1,i] = portfolio_std
      results_matrix[2,i] = portfolio_VaR
      #iterate through the weight vector and add data to results array
      for j in range(len(weights)):
          results_matrix[j+3,i] = weights[j]
      my_bar.progress((i+1)/num_portfolios)
            
    results_df = pd.DataFrame(results_matrix.T,columns=['ret','stdev','VaR'] + [ticker for ticker in p_stocks])

    return results_df
          

  st.header("Enter portfolio stocks")
  p_stocks = st.text_input("Enter list of stocks separated by comma",help="Enter the ticker symbol of portfolio stock on BSE/NSE. Ex - TCS,INFY,HCLTECH").upper().split(',')
  no_of_stocks = len(p_stocks)

  if no_of_stocks == 1 and p_stocks[0]!='':
    st.error("Enter atleast two stocks")
    st.stop()
  portfolio = [yf.Ticker(i+".NS") for i in p_stocks]

  amount = st.number_input("Enter the total investment amount",help="The total to amount be invested in the portfolio",value=0)

  if amount <= 0:
    st.stop()

  for i in range(no_of_stocks):
    portfolio[i]=portfolio[i].history(start="2010-01-01") #contains ticker dataframe

  #Dropping unwanted columns
  portfolio = rk.drop_divnstksplit(portfolio)

  portfolio_stocks = pd.concat([df['Close'] for df in portfolio],axis=1)
  portfolio_stocks.columns = p_stocks

  st.header("Enter the portfolio allocation for each stock")
  st.info("**NOTE** - ***The sum of all the allocations should be equal to 1.0***")
  allocations=[]
  for i in p_stocks:
    allocations.append(st.number_input("Enter the portfolio allocation for - "+i,min_value=0.0, max_value=1.0,help="Ex - If you want to allocate 50% in two stocks enter 0.5 and 0.5 in the respective fields"))


  if sum(allocations) != 1.0 and allocations[-1]!=0.0:
    allocations = []
    st.error("(Error) Please Re - Enter, The sum of all allocations must equal to 1")
    st.stop()
  elif sum(allocations) == 1.0:
    normed_stocks=portfolio_stocks/portfolio_stocks.iloc[0]
    portfolio_val=get_Position(allocations,amount)

    # Portfolio Price Chart
    st.text("")
    st.subheader("Portfolio Performance (5 years)")
    p1_chart=alt.Chart(portfolio_val.reset_index(level=0)).mark_line().encode(x='Date',
    y='Total Position',color=alt.value('#34a853'),
    tooltip=alt.Tooltip(['Total Position'], format='.2f',title='INR')).properties(height=600).configure_view(strokeOpacity=0).configure_axis(grid=False).interactive()
    st.altair_chart(p1_chart,use_container_width=True)


    #Portfolio Histogram
    st.text("")
    st.subheader("Portfolio Return Distribution")
    portfolio_val['Daily Return'] = portfolio_val['Total Position'].pct_change(1)
    #Cumulative returns i.e total return from the day i invested till now
    # cum_ret = 100 * (portfolio_val['Total Position'][-1]/portfolio_val['Total Position'][0] -1 )
    # print('Our return was {}  percent!'.format(cum_ret))
    st.altair_chart(alt.Chart(portfolio_val).mark_bar().encode(
    alt.X("Daily Return:Q", bin=alt.Bin(extent=[-0.100,0.100], step=0.005)),y='count()',color=alt.value('#ff7c0c')
    ).properties(height=500).interactive(),use_container_width=True)

    st.write("")

    st.header("Portfolio Optimization")


    if st.button('Click Here To Optimize Portfolio!'):

      #PORTFOLIO OPTIMIZATION
      cov = portfolio_stocks.pct_change().cov()
      num_portfolios = 5000
      rf = 0.0
      days = 252
      alpha = 0.05

      results_frame = simulate_random_portfolios_VaR(num_portfolios, no_of_stocks, cov, alpha, days)

      #locate positon of portfolio with minimum VaR
      min_VaR_port = results_frame.iloc[results_frame['VaR'].idxmin()]
      #create scatter plot coloured by VaR

      fig1 = plt.figure()
      ax = fig1.add_subplot(1,1,1)
      ax.scatter(results_frame.VaR,results_frame.ret,c=results_frame.VaR,cmap='plasma')
      ax.set_xlabel('Value at Risk')
      ax.set_ylabel('Returns')
      ax.scatter(min_VaR_port[2],min_VaR_port[0],marker=(5,1,0),color='r',s=500)

      st.pyplot(fig1)

      st.header('***CAGR*** = '+str(min_VaR_port[0])+' ***VaR*** = '+str(min_VaR_port[2]))
      st.write("")
            

      col1, col2 = st.beta_columns([1,1])

      with col1:

        st.subheader("Your Allocation")
        st.vega_lite_chart(pd.DataFrame({'Stocks':p_stocks,'Allocation':allocations}), {
        "width": 600,
        "height": 600,
        "encoding": {
        "theta": {"field": "Allocation", "type": "quantitative", "stack": True},
        "color": {"field": "Stocks", "type": "nominal"},
        "tooltip": {"field": "Allocation", "type": "quantitative"}
        },
        "layer": [{
            "mark": {"type": "arc", "outerRadius": 150}
        }, {
            "mark": {"type": "text", "radius": 190},
            "encoding": {
            "text": {"field": "Stocks", "type": "nominal"}
            }
        }]
        })

        #CAGR and VaR
        c,s,v=calc_portfolio_perf_VaR(np.array(allocations),cov,alpha,days)
        st.subheader('***CAGR*** = '+str(c))
        st.subheader('***VaR*** = '+str(v))

        # Portfolio1 Price Chart
        st.text("")
        st.subheader("Input Portfolio Performance")
        st.altair_chart(p1_chart,use_container_width=True)


      with col2:

        st.subheader("Recommended Allocation")
        st.vega_lite_chart(pd.DataFrame({'Stocks':p_stocks,'Allocation':list(round(min_VaR_port[p_stocks]*100,2))}), {
        "width": 600,
        "height": 600,
        "encoding": {
        "theta": {"field": "Allocation", "type": "quantitative", "stack": True},
        "color": {"field": "Stocks", "type": "nominal"},
        "tooltip": {"field": "Allocation", "type": "quantitative"}
        },
        "layer": [{
            "mark": {"type": "arc", "outerRadius": 150}
        }, {
            "mark": {"type": "text", "radius": 190},
            "encoding": {
            "text": {"field": "Stocks", "type": "nominal"}
            }
        }]
        })

        #CAGR and VaR
        st.subheader('***CAGR*** = '+str(min_VaR_port[0]))
        st.subheader('***VaR*** = '+str(min_VaR_port[2]))

        # Portfolio2 Price Chart
        st.text("")
        st.subheader("Recommended Portfolio Performance")
        sugg_portfolio_val=get_Position(list(round(min_VaR_port[p_stocks],4)),amount)
        p2_chart=alt.Chart(sugg_portfolio_val.reset_index(level=0)).mark_line().encode(x='Date',
        y='Total Position',color=alt.value('#34a853'),
        tooltip=alt.Tooltip(['Total Position'], format='.2f',title='INR')).properties(height=600).configure_view(strokeOpacity=0).configure_axis(grid=False).interactive()
        st.altair_chart(p2_chart,use_container_width=True)


      results_frame.to_csv("results_frame.csv",index=False) 
      st.write("")

      #Generating portfolio for Custom Returns

    try:

      results_frame=pd.read_csv("results_frame.csv")
      st.write(results_frame)
      st.subheader("Want more returns! Just enter your expected return by referring the above Portfolio Allocation chart to get the most optimal portfolio for your expected return")
      st.info("**NOTE - ** The input return must be within the range of achievable returns from the above chart")
      st.write("")
      alt_return=st.number_input("Enter the expected portfolio return",min_value=round(min(results_frame['ret']),4), max_value=round(max(results_frame['ret']),4),help="Enter your expected return by refering the above graph")
      if alt_return == round(min(results_frame['ret']),4):
        st.stop()
      alt_var=min((results_frame[(results_frame['ret']<alt_return+0.0005) & (results_frame['ret']>alt_return-0.0005)]).VaR)
      st.write(alt_return)
      #Plotting the chart

      #locate positon of portfolio with minimum VaR
      min_VaR_port = results_frame.query('VaR=='+str(alt_var)).iloc[0]
      #create scatter plot coloured by VaR
      fig2 = plt.figure()
      ax = fig2.add_subplot(1,1,1)
      ax.scatter(results_frame.VaR,results_frame.ret,c=results_frame.VaR,cmap='plasma')
      ax.set_xlabel('Value at Risk')
      ax.set_ylabel('Returns')
      ax.scatter(min_VaR_port[2],min_VaR_port[0],marker=(5,1,0),color='r',s=500)
      st.pyplot(fig2)
      st.write("")

      c1, c2 = st.beta_columns([1,1])

      with c1:
        st.vega_lite_chart(pd.DataFrame({'Stocks':p_stocks,'Allocation':list(round(min_VaR_port[p_stocks]*100,2))}), {
        "width": 600,
        "height": 600,
        "encoding": {
        "theta": {"field": "Allocation", "type": "quantitative", "stack": True},
        "color": {"field": "Stocks", "type": "nominal"},
        "tooltip": {"field": "Allocation", "type": "quantitative"}
        },
        "layer": [{
            "mark": {"type": "arc", "outerRadius": 150}
        }, {
            "mark": {"type": "text", "radius": 190},
            "encoding": {
            "text": {"field": "Stocks", "type": "nominal"}
            }
        }]
        })

      with c2:
        st.subheader('***CAGR*** = '+str(min_VaR_port[0]))
        st.subheader('***VaR*** = '+str(min_VaR_port[2]))
        # Portfolio 3 Price Chart
        st.text("")
        st.subheader("Portfolio Performance")
        new_portfolio_val=get_Position(list(round(min_VaR_port[p_stocks],4)),amount)
        p2_chart=alt.Chart(new_portfolio_val.reset_index(level=0)).mark_line().encode(x='Date',
        y='Total Position',color=alt.value('#34a853'),
        tooltip=alt.Tooltip(['Total Position'], format='.2f',title='INR')).properties(height=600).configure_view(strokeOpacity=0).configure_axis(grid=False).interactive()
        st.altair_chart(p2_chart,use_container_width=True)



    except Exception as e:
      # st.error("Error")
      # st.exception(e)
      pass
예제 #2
0
def main():
    st.title("Test Input")

    menu = ["Home", "About"]
    choice = st.sidebar.selectbox("Menu", menu)

    if choice == "Home":
        st.subheader("Home")
        first_test = st.radio(
            "Both hands strecth out to front and all fingers strecth out as big as they can for 30 seconds. Did your hands shake ? ",
            ("Yes", "No"))

        if first_test == 'Yes':
            result_first = 1
        elif first_test == 'No':
            result_first = 0

        second_test = st.radio(
            "Try to drink water from a cup. Did your hands shake ? ",
            ("Yes", "No"))
        if second_test == 'Yes':
            result_second = 1
        elif second_test == 'No':
            result_second = 0

        third_test = st.radio(
            "Put both hands on each hips and each hand pose like the alphabet 'C'. Did your hands shake ? ",
            ("Yes", "No"))

        if third_test == 'Yes':
            result_third = 1
        elif third_test == 'No':
            result_third = 0

        example_spiral = Image.open("Spiral.png")
        st.write(
            "Using a black pen and  a white, clean paper, draw a spiral like below without your drawing hand touching the paper"
        )
        st.image(example_spiral)
        st.write(
            "With your phone camera and the Flash On, Take a photo of your result"
        )
        image_file = st.file_uploader("Upload Your Spiral Result",
                                      type=['png', 'jpeg', 'jpg'])
        if image_file is not None:

            # file_bytes = np.asarray(bytearray(image_file.read()), dtype=np.uint8)
            # img = cv2.imdecode(file_bytes, 1)
            # st.image(img, channels="BGR")
            img = load_image(image_file)
            img = cv2.medianBlur(img, 5)
            status = bright_img(img)
            if status == "light":
                res = lightpre(img)
                st.write("light")
                st.write(res.shape)
                st.image(res, use_column_width=True)
            if status == "dark":
                res = darkpre(img)
                st.write("dark")
                st.write(res.shape)
                st.image(res, use_column_width=True)

        if st.button("Done"):
            st.write("[" + str(result_first) + " , " + str(result_second) +
                     " , " + str(result_third) + "]")
            st.write("The result is Essential Tremor")
    else:
        st.subheader("About")
        st.info("Built with Streamlit")
        st.info("Jesus Saves @JCharisTech")
        st.text("Jesse E.Agbe(JCharis)")
예제 #3
0
if st.button('Get random prediction'):
    response = requests.post(URI, data={})
    response = json.loads(response.text)
    preds = response.get('predictions')
    image = response.get('image')
    image = np.reshape(image, (28, 28))

    st.image(image, width=150)
    for layer, p in enumerate(preds):
        numbers = np.squeeze(np.array(p))
        plt.figure(figsize=(32, 4))
        if layer == 2:
            row = 1
            col = 10
        else:
            row = 2
            col = 16

        for i, number in enumerate(numbers):
            plt.subplot(row, col, i + 1)
            plt.imshow(number * np.ones((8, 8, 3)).astype('float32'))
            plt.xticks([])
            plt.yticks([])
            if layer == 2:
                plt.xlabel(str(i), fontsize=40)
        plt.subplots_adjust(wspace=0.05, hspace=0.05)
        plt.tight_layout()
        st.text('Layer {}'.format(layer + 1))
        st.pyplot()
예제 #4
0
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt

DATA_URL = "COVID_dataset_2july2020.csv"

@st.cache
def load_data(nrows):
	data = pd.read_csv(DATA_URL,nrows=nrows)
	lowercase = lambda x: str(x).lower()
	data.rename(lowercase, axis='columns', inplace=True)
	
	return data


st.title(" COVID-19")
st.text("Latest By  - 2nd July, 2020")
data = load_data(10000)
data.columns = data.columns.str.strip().str.lower().str.replace(' ', '_')



st.sidebar.subheader("Home")
if not st.sidebar.checkbox("Hide", True,key = '10'):
	st.write("Total Cases Confirmed: ")
	st.subheader(str(data['confirmed'].sum()))
	st.write("Total Deaths: ")
	st.subheader(str(data['deaths'].sum()))
	st.write("Total Recovered: ")
	st.subheader(str(data['recovered'].sum()))

st.sidebar.subheader("Click here to see the Raw data")
예제 #5
0
def view_dataset(data):
    st.text('A glance at top 5 rows of dataset')
    s = data.head().style.background_gradient(cmap='viridis')
    st.dataframe(s)  # output first 5 lines of dataset
    return None
예제 #6
0
                pickable=True,
                extruded=True,
            ),
        ],
    ))

hist_data = data[data['price'] < 2e6]
fig, ax = plt.subplots()

ax.hist(hist_data['price'], bins=50)
ax.set_title(
    f"Histogram of Housing Prices in {display_city if display_city != 'All' else 'King County'}"
)
ax.set_xlabel("Price")
ax.set_ylabel("Frequency")
st.pyplot(fig)

sns.jointplot(data=data, x='sqft_living', y='yr_built')
st.pyplot(fig)

bedrooms = st.slider('Bedrooms', 0, 10, 2)
bathrooms = st.slider('Bathrooms', 0, 8, 2)
sqft = st.slider('Square Feet', 200, 10000, 2000)

json = {'bedrooms': bedrooms, 'bathrooms': bathrooms, 'yr_built': sqft}

predicted_price = requests.post(url, json=json)
st.text(f"Predicted Price: {predicted_price.json()['price']}")

st.write(data)
예제 #7
0
	    st.image("medim.JPG")
	if st.checkbox("Super Resolution/ Image Upscaling"):
		picture = st.file_uploader("Upload Image to Upscale:",type=["png","jpg","JPG","JPEG"])
		if st.button("Convert"):
			if picture is None:
				st.warning("Please Upload Picture.")
			else:
				
				weights_dir = 'weights/article'
				#edsr_pre_trained = edsr(scale=4, num_res_blocks=16)
				#edsr_pre_trained.load_weights(os.path.join(weights_dir, 'weights-edsr-16-x4.h5'))
				edsr_fine_tuned = load_stuff()
				#edsr_fine_tuned = edsr(scale=4, num_res_blocks=16)
				#edsr_fine_tuned.load_weights(os.path.join(weights_dir, 'weights-edsr-16-x4-fine-tuned.h5'))
				
				st.text('Uploaded Image')
				st.image(picture,width=100)
				resolve_and_plot(edsr_fine_tuned, picture)
				
		st.text('  ')	    

	image = st.file_uploader("Upload Image to predict cancer:",type=["png","jpg","JPG","JPEG"])

	if image is not None:
	    st.success('You uploaded the following image:')
	    #size = st.slider('Change Image Size',300,800)
	    st.image(image,width=300)
	if st.button('Predict Outcome!'):
	    if image is None:
	    	st.error('Please upload an image before predicting.')
	    else:
예제 #8
0
import streamlit as st

st.title("Food Carbon Footprint")
st.subheader("DS4B Final Project")
st.text('Yan Zhou Chen, Britnie Nguyen, Angeline Utomo, and JoJo Zhang')
st.text('Spring 2021')

import pandas as pd
from PIL import Image

st.markdown(
    "We often underestimate the greenhouse gas (GHG) emissions associated with the food production chain when in reality, food production contributes 26% of the global GHG emissions. Using datasets from Hannah Ritchie and Max Roser's *Our World in Data* documentation (https://ourworldindata.org/environmental-impacts-of-food), we aim to visualize GHG emissions associated with different food groups across stages of the food production chain. We hope that the visualizations and food-associated GHG calculator we are providing can help to empower consumers to make more sustainable decisions when it comes to their diets."
)
st.markdown(" ")
st.markdown(" ")
st.markdown(" ")

#----------------------------JoJo----------------------------------------------------------------------------------------------------------------------------------

import streamlit.components.v1 as components
df = pd.read_csv("co2_emission.csv")

food_ghg_map = """<script type='text/javascript' src='https://prod-useast-b.online.tableau.com/javascripts/api/viz_v1.js'></script><div 
class='tableauPlaceholder' style='width: 1000px; height: 850px;'><object class='tableauViz' width='1000' height='850' style='display:none;'><param name='host_url' 
value='https%3A%2F%2Fprod-useast-b.online.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='&#47;t&#47;dsbfinal' /><param 
name='name' value='Food_GHG_1990-2015_by_tonnes&#47;Dashboard1' /><param name='tabs' value='yes' /><param name='toolbar' value='yes' /><param name='showAppBanner' value='false' /
></object></div>
"""

total_co2_map = """<script type='text/javascript' src='https://prod-useast-b.online.tableau.com/javascripts/api/viz_v1.js'>
</script><div class='tableauPlaceholder' style='width: 1000px; height: 850px;'><object class='tableauViz' width='1000' height='850' style='display:none;'>
예제 #9
0
                       value=400)

rooms = st.number_input('enter no. of rooms',
                        max_value=50,
                        min_value=1,
                        value=3)

age = st.number_input('age of house', max_value=500, min_value=0, value=1)
location = st.text_area("enter location address")

submit = st.button("make predictions")

if submit and location:
    try:
        entry = UserInput(house_area=area,
                          no_of_rooms=rooms,
                          age=age,
                          location=location)
        sess.add(entry)
        sess.commit()
        st.success("data added to database")
    except Exception as e:
        st.error(f"some error occurred : {e}")

if st.checkbox("view data"):
    results = sess.query(UserInput).all()
    for item in results:
        st.subheader(item.location)
        st.text(item.house_area)
        st.text(item.age)
        st.text(item.no_of_rooms)
def main():
    #"""Run this function to display the Streamlit app"""
    # st.info(__doc__)
    #st.markdown(STYLE, unsafe_allow_html=True)
    st.title("Visual Search")
    html_temp = """
    <div style="background-color:tomato;padding:10px">
    <h2 style="color:white;text-align:center;">Search 10 Similar Images </h2>
    </div>
"""
    st.markdown(html_temp, unsafe_allow_html=True)

    FILE_TYPES = ["csv", "py", "png", "jpg"]
    file = st.file_uploader("Upload file", type=FILE_TYPES)
    show_file = st.empty()
    if not file:
        show_file.info("Please upload a file of type: " +
                       ", ".join(FILE_TYPES))
        return
    content = file.getvalue()
    st.write("-----------")
    #st.write(file)
    #st.write(content)
    filename = "result.jpg"
    with open("result.jpg", "wb") as f:
        f.write(content)
    # IMAGE INTO VECTOR
    helper = TensorVector(FileName='result.jpg')
    vector = helper.process()

    res = base64.b64encode(content)
    base64data = res.decode("UTF-8")

    a1_vector = vector
    a1_image = base64data
    IMAGE_VECTOR = vector

    fig, ax = plt.subplots(2, figsize=(18, 10))
    ax[0].imshow(stringToRGB(a1_image))
    st.pyplot()

    counter = 0
    IMG = []
    FILE = []
    VEC = []

    for vector in df.iterrows():
        FileName = vector[1][0]  # Grabs the Filename of the image
        Vector_ = vector[1][1]  # Grabs the vector of the image
        Vector_ = ast.literal_eval(Vector_)  # Converting a String into list
        Image = vector[1][2]  # Image is basically a Base data of that image

        sim = cosineSim(
            Vector_,
            IMAGE_VECTOR)  # For each Image..we are computing Cosine Similarity

        if (float(sim) > 0.72):
            counter = counter + 1  # to track..the count of images
            IMG.append(Image)
            VEC.append(Vector_)
            FILE.append(FileName)

        if counter == 10:  #displaying 10 images
            break
    fig, ax = plt.subplots(10, figsize=(20, 30), dpi=80)

    for i in range(0, 10):
        ax[i].imshow(stringToRGB(IMG[i]), interpolation='nearest')
    st.pyplot()

    if st.button("About"):
        st.text("Developers-Jui and Priyanka")
        st.text("Built with Streamlit")
        DESCRIPTION: Clean texts, remove Stopwords and stemming

    Returns: A string of cleaned words
    -------
    """
    text = re.sub('[^a-zA-Z0-9]+', ' ', text).lower().split()
    ps = PorterStemmer()
    text = ' '.join(
        [ps.stem(w) for w in text if w not in set(stopwords.words('english'))])

    return text


cv = pickle.load(open('models/cv.pkl', 'rb'))
model = pickle.load(open('models/final_clf.pkl', 'rb'))

st.title('Email Spam/Ham Detector')
text = st.text_input('Enter your email message here :')
text = clean_text(text)
text = cv.transform([text])
pred = model.predict(text)[0]

st.write('Click predict to know your answer')
if st.button('Predict'):
    if pred == 1:
        st.error('SPAM Alert!!')
    else:
        st.success('NOT SPAM!! This may be important to you')

st.text('Author:RhitC')
def main():
    """Tweet Classifier App with Streamlit """

    # Creates a main title and subheader on your page -
    # these are static across all pages
    st.title("Tweet Classifer")
    st.subheader("Climate Change Tweet Classification")
    # Using PIL

    # Creating sidebar with selection box -
    # you can create multiple pages this way
    options = [
        "Information", "Exploratory Data Analysis", "Prediction", "Profile"
    ]
    selection = st.sidebar.selectbox("Choose Option", options)

    # Building out the "Information" page
    if selection == "Information":
        image = Image.open('img5.png')
        st.image(image, caption=None, use_column_width=True)
        st.info("General Information")
        # You can read a markdown file from supporting resources folder
        st.markdown(
            "Many companies are built around lessening one’s environmental impact or carbon footprint. They offer products and services that are environmentally friendly and sustainable, in line with their values and ideals. They would like to determine how people perceive climate change and whether or not they believe it is a real threat. This would add to their market research efforts in gauging how their product/service may be received."
        )
        #st.subheader("Who should use this tool")
        st.subheader(
            "==========================================================")
        st.subheader("Benefits of using this classification tool")
        st.subheader(
            "==========================================================")
        st.markdown(
            "1. Quicker near real-time results compared to a survey without having to pay for expensive reports"
        )
        st.markdown("2. Easily accessible on your internet browser")
        st.markdown(
            "3. You don't need to understand complicated statistical techniques, just need to understand insights"
        )
        st.markdown(
            "If you are a startup or even an established business looking to launch a new product, are you aware of your potential customers sentiments regarding climate change? As a not for profit organisation looking for donors for environmental projects, do you know what your donors thoughts are regarding climate change? Knowing this information can help you better prepare to take your organisations strategy forward. Not knowing this information can make you seem irrelevant to your target market and cause you to miss out on an opporunity of a lifetime. The tweet classifier will help you be more prepared and relevant to your audience."
        )
        st.subheader(
            "==========================================================")
        st.subheader("Instructions for using this tool")
        st.subheader(
            "==========================================================")
        st.markdown(
            "Let us help you turn insights from your potential customers to action."
        )
        st.markdown("Get started by:")
        st.markdown(
            "1. Navigating to the sidebar at the top left of this page")
        st.markdown(
            "2. Choose an option by clicking the 'Choose Option' dropdown")
        st.markdown("3. Select the option you wish to view")
        st.markdown("4. Get insights that will help you be better prepared")
        if st.checkbox('Choose to Preview Example'):
            st.subheader(
                "Example chart: What are the most frequent opinions regarding climate change?"
            )

            import plotly.figure_factory as ff
            # Add histogram data
            x1 = np.random.randn(200) + 1
            x2 = np.random.randn(200)
            x3 = np.random.randn(200)
            x4 = np.random.randn(200) - 1

            # Group data together
            hist_data = [x1, x2, x3, x4]

            group_labels = ['Anti: -1', 'Neutral: 0', 'Pro: 1', 'News: 2']

            # Create distplot with custom bin_size
            fig = ff.create_distplot(hist_data,
                                     group_labels,
                                     bin_size=[.1, .25, .5, .75])

            # Plot!
            st.plotly_chart(fig, use_container_width=True)

            st.markdown(
                "Your conclusion from the above example chart may be that those who are against ('Anti:-1') climate change are likely to have tweet more about  their opinions. The resulting insight from this tool may help you with your next step for formulating your brand messaging and positioning etc."
            )
            #chart_data1 = pd.DataFrame(np.random.randn(20, 3),columns=['a', 'b', 'c'])
            #st.line_chart(chart_data1)

        chart_data2 = {
            'Class': ['2', '1', '0', '-1'],
            'Description': [
                'News: the tweet links to factual news about climate change',
                'Pro: the tweet supports the belief of man-made climate change',
                'Neutral: the tweet neither supports nor refutes the belief of man-made climate change',
                'Anti: the tweet does not believe in man-made climate change'
            ]
        }
        df = pd.DataFrame(chart_data2)
        blankIndex = [''] * len(df)
        df.index = blankIndex
        st.subheader(
            "==========================================================")
        st.subheader("Table: Data dictionary")
        st.subheader(
            "==========================================================")
        st.table(df)
        st.subheader(
            "==========================================================")
        st.subheader("Raw Twitter data and label")
        st.subheader(
            "==========================================================")
        st.markdown(
            "The collection of this data which we use as our data source was funded by a Canada Foundation for Innovation JELF Grant to Chris Bauch, University of Waterloo. The dataset aggregates tweets pertaining to climate change collected between Apr 27, 2015 and Feb 21, 2018. In total, 43943 tweets were collected. Each tweet is labelled as one of the following classes in the table below:"
        )

        st.markdown(
            "Select tickbox to view raw data where the 'sentiment'column denotes the 'class' column in the above data dictionary table which is associated to a description ranging from 'Anti' to'News' as descriptions for tweet messages that classify a range people that do not believe to those that believe in climate change respectively."
        )
        if st.checkbox('Show raw data'):  # data is hidden if box is unchecked
            st.write(raw[['sentiment',
                          'message']])  # will write the df to the page

    # Building out the Exploratory Data Analysis page
    if selection == "Exploratory Data Analysis":
        st.markdown(
            "Exploratory Data Analysis refers to the critical process of performing initial investigations on data so as to discover patterns,to spot anomalies,to test hypothesis and to check assumptions with the help of summary statistics and diagramatic representations"
        )
        st.info("Tweet Data Insights")

        st.subheader("General Insights")
        st.markdown(
            "A subset of the dataset denoted by the 'Head' and the 'Tail' shows what raw tweet data looks like when placed in rows and columns. Building on our definition of the four sentiment classes defined in the information page, a handful of graphical plots are used to show the distribution of tweets by deniers and belivers of climate change. This includes:"
        )
        st.markdown(
            "1. Which proportion of tweets belong to the believer versus the denier group (or neutral) group. This can show which views are most widely help if we use tweets as our proxy for climate change belief sentiment i.e. Use Bar chart plot, Pie chart and Word Count plots to get a sense of the more widely held beliefs of climate change."
        )
        st.markdown(
            "2. Which common words exist and were predominantly in describing climate change i.e. Use the Word Cloud and ngram (Unigram, Bigram etc) plots to see what words were most prevelant amongst the climate change sentiment tweets."
        )
        #my_dataset = 'resources/train.csv'

        #Loading Dataset
        #@st.cache(persist=True)
        #def explore_data(dataset):
        #train_df = pd.read_csv(os.path.join(dataset))
        #return train_df

        #data = explore_data(my_dataset)

        DATA_URL = ('resources/train.csv')

        @st.cache(allow_output_mutation=True)
        def load_data(nrows):
            data = pd.read_csv(DATA_URL, nrows=nrows)
            lowercase = lambda x: str(x).lower()
            data.rename(lowercase, axis='columns', inplace=True)
            return data

        data_load_state = st.text('Loading data...')
        data = load_data(40000)
        data_load_state.text("Done! (using st.cache)")

        #Minimal cleaning
        import re

        #showing what our dataset is
        if st.checkbox('Choose to Preview Dataset and Visualisations'):
            #data = explore_data(my_dataset)
            @st.cache(allow_output_mutation=True)
            def remove_URL(message):
                url = re.compile(r'https?://\S+|www\.\S+')
                return url.sub(r'', message)

            if st.checkbox(
                    'Choose to remove URLs from data (may take long to run)'):
                st.markdown(
                    "***Unselect the box and stop running if it takes longer than 5 minutes***."
                )
                st.text(
                    "This selection allows you to clean URL's for the tweets but may take longer to run."
                )
                st.text(
                    "Leave this selection unselected for better run times.")
                data['message'] = data['message'].apply(
                    lambda x: remove_URL(x))
            if st.button('Head'):
                st.write(data.head())
            elif st.button('Tail'):
                st.write(data.tail())
            else:
                st.write(data.head(2))
            #Show entire Dataset
            if st.checkbox('Show all Dataset'):
                st.write(data)

            #Show Column Names
            if st.checkbox('Show Column Names'):
                st.write(data.columns)

            #Show Dimensions
            data_dim = st.selectbox('What Dimensions Do You Want to See?',
                                    ['Rows', 'Columns'])
            if data_dim == 'Rows':
                st.text('Showing Rows')
                st.write(data.shape[0])
            elif data_dim == 'Columns':
                st.text('Showing Columns')
                st.write(data.shape[1])

            #Select a Column
            col = st.selectbox('Select Column',
                               ('sentiment', 'message', 'tweetid'))
            if col == 'sentiment':
                st.write(data['sentiment'])
            elif col == 'message':
                st.write(data['message'])
            elif col == 'tweetid':
                st.write(data['tweetid'])
            else:
                st.write('Select Column')

            #Add Plots

            #Bar Chart
            if st.checkbox(
                    'Show Bar Chart Plot for distribution of tweets across sentiment classes'
            ):
                st.write(data['sentiment'].value_counts())
                st.bar_chart(data['sentiment'].value_counts())

            #Add Pie Chart
            if st.checkbox(
                    'Show Pie Chart for proportion of each sentiment class'):
                pie_labels = ['Pro', 'News', 'Neutral', 'Anti']
                fig1 = go.Figure(data=[
                    go.Pie(labels=pie_labels,
                           values=data['sentiment'].value_counts())
                ])
                st.plotly_chart(fig1)

            #Word count for distribution
            # Define subplot to see graphs side by side
            if st.checkbox(
                    'Show Word Count Plot for distribution of tweets across sentiment classes'
            ):
                data['word_count'] = data['message'].apply(
                    lambda x: len(x.split()))

                # Split so we can use updated train set with new feature
                data = data[:len(data)]

                # Define subplot to see graphs side by side
                fig, ax = plt.subplots(figsize=(10, 5))

                #create graphs
                sns.kdeplot(data['word_count'][data['sentiment'] == 0],
                            shade=True,
                            label='Neutral')
                sns.kdeplot(data['word_count'][data['sentiment'] == 1],
                            shade=True,
                            label='Pro')
                sns.kdeplot(data['word_count'][data['sentiment'] == 2],
                            shade=True,
                            label='News')
                sns.kdeplot(data['word_count'][data['sentiment'] == -1],
                            shade=True,
                            label='Anti')

                # Set title and plot
                plt.title('Distribution of Tweet Word Count')
                plt.xlabel('Word Count')
                plt.ylabel('Sentiments Proportions')
                st.pyplot()
            #Show word cloud chart
            if st.checkbox(
                    'Show Word Cloud to see the most words in the climate change tweets'
            ):
                from wordcloud import WordCloud
                Allwords = ' '.join([tweets for tweets in data['message']])
                wordCloud = WordCloud(width=700,
                                      height=500,
                                      random_state=21,
                                      max_font_size=150).generate(Allwords)
                plt.imshow(wordCloud, interpolation='bilinear')
                plt.axis('off')
                st.pyplot()

            #Show Ngram bar chart
            @st.cache(allow_output_mutation=True)
            def get_top_tweet_unigrams(corpus, n=None):
                vec = CountVectorizer(ngram_range=(1, 1)).fit(corpus)
                bag_of_words = vec.transform(corpus)
                sum_words = bag_of_words.sum(axis=0)
                words_freq = [(word, sum_words[0, idx])
                              for word, idx in vec.vocabulary_.items()]
                words_freq = sorted(words_freq,
                                    key=lambda x: x[1],
                                    reverse=True)
                return words_freq[:n]

            if st.checkbox(
                    'Show Unigram Plot for top 20 common single words in tweets'
            ):
                plt.figure(figsize=(10, 5))
                top_tweet_unigrams = get_top_tweet_unigrams(
                    data['message'])[:20]
                x, y = map(list, zip(*top_tweet_unigrams))
                sns.barplot(x=y, y=x)
                st.pyplot()

            #anyone can add from here

    # Building out the predication
    #loading models
    def load_prediction_models(models):
        loaded_models = joblib.load(open(os.path.join(models), "rb"))
        return loaded_models

    if selection == "Prediction":
        st.info("Prediction with ML Models")
        st.markdown(
            "Predictive modeling is a process that uses data and statistics to predict outcomes with classification data models. These models can also be used to predict our twitter data. We get predictions from models such as Logistic Regression, LinearSVC, Naive Bayes Classifier and many more."
        )
        st.markdown(
            "LogisticRegression- Is used to obtain odds ratios in the presence of more than one exploratory variable. It explains the relationship between one dependent binary variable and one or more independent variables"
        )
        st.markdown(
            "Support Vector Machine- It analyzes data used for classification and regression analysis. It separates data points using hyperplane with the largest amount of margin"
        )
        st.markdown(
            "Naive Bayes Classifier- It uses the principle of Bayes Theorem to make classification. This model is quick and simple to build but it is not the most accurate. Its advantage is that it is useful for large dataset"
        )
        # Creating a text box for user input
        tweet_text = st.text_area("Enter Text", "Type Here")
        # Transforming user input with vectorizer
        vect_text = tweet_cv.transform([tweet_text]).toarray()
        #load some models used
        all_models = [
            "LinearSVC", "LogisticRegression", "Naive Bayes Classifier"
        ]
        model_choice = st.selectbox("Choose ML Model", all_models)

        def load_prediction_models(models):
            loaded_models = joblib.load(open(os.path.join(models), "rb"))
            return loaded_models

        if st.button("Classify"):
            # Load your .pkl file with the model of your choice + make predictions
            # Try loading in multiple models to give the user a choice
            if model_choice == 'LinearSVC':
                predictor = joblib.load(
                    open(os.path.join("resources/clf_ndu.pkl"), "rb"))
                prediction = predictor.predict(vect_text)

            elif model_choice == 'LogisticRegression':
                predictor = joblib.load(
                    open(os.path.join("resources/lr_model_ndu.pkl"), "rb"))
                prediction = predictor.predict(vect_text)

            elif model_choice == 'Naive Bayes Classifier':
                predictor = joblib.load(
                    open(os.path.join("resources/nb_model_ndu.pkl"), "rb"))
                prediction = predictor.predict(vect_text)

            def getAnalysis(prediction):
                if prediction == -1:
                    return "Anti  (i.e. a denier of man-made climate change)"
                elif prediction == 0:
                    return "Neutral  (i.e. Neutral in beliefs about man-made climate change)"
                elif prediction == 1:
                    return "Pro  (i.e. Believes that climate change is man-made)"
                else:
                    return "News  (i.e. Has factual sources that climate change is man-made)"

            # When model has successfully run, will print prediction
            # You can use a dictionary or similar structure to make this output
            # more human interpretable.
            st.success("Text Categorized as: {}".format(
                getAnalysis(prediction)))

    #Building Profile Page
    if selection == "Profile":
        st.info("Explore Academy Data Scientists")
        st.markdown("Nduduzo Phili :0716709471")
        st.markdown("Victoria Chepape :0797433734")
        st.markdown("Nondumiso Magudulela :0825210964")
        st.markdown("Jamie Japhta :0731947015")
        st.markdown("Oarabile Tiro :0787359249")
예제 #13
0
        del draw

    return image


if st.button(label="SEND PAYLOAD"):

    if test_mode_on:
        st.warning("Simulating a dummy request to {}".format(model_url))
        result = make_dummy_request(model_url=model_url, model=model_name, image=image)
    else:
        result = make_request(model_url=model_url, model=model_name, image=image)
        print(result.detections)

    st.balloons()

    st.markdown("## Display")

#    st.markdown("Make something pretty, draw polygons and confidence..., here's an ugly output")
    
    image = draw_preds(image, result)

    st.image(image, width=512, caption="Output of {} on your picture".format(result.model))

    st.text("Model : {}".format(result.model))
    st.text("Processing time : {}s".format(result.time))

#    for detection in result.detections:
#        st.json(detection.json())
        
def stock_analysis():
  st.header("Enter the stock name")
  user_input = st.text_input("",help="Enter the ticker symbol of any stock on BSE/NSE. Ex - TCS")


  if(user_input):
      stock_name = user_input.upper()
      try:
          soup = rk.stock_data(stock_name)
          stock = yf.Ticker(stock_name+".NS")
      except:
          st.error("❗ Check your connection / Enter a valid name")
          st.stop()
      cmp = soup.find("span", class_="Number")
      #st.write("Current Market Price - ₹",cmp.text,sep='.')

      
      stock_info = get_ticker_info(stock)

      st.text("")

      #Company_description
      html1 = '''
          <html>
          <head>
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
          <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
          <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <style>
          @media screen and (min-width: 601px){
              h1{
                  font-size: 30px;
              }
          }
          .jumbotron{
              background-color:#F0F2F6;
              margin-top: 50px;
          }
          img{
              position: absolute;
              z-index: 2;
              right: 20px;
              border: 5px solid grey;
              border-width: thin;
              top: -110px;
              box-shadow: 1px 1px 3px 0.5px;
          }
          .container{
            paddin
          }
          </style>
          </head>        
          <body>
          <main role="main">
          <!-- Main jumbotron for a primary marketing message or call to action -->
          <div class="jumbotron">

      <div style="position: relative; z-index: 1;">
      <img src=%s style="position: absolute; z-index: 2;" />

      </div>
              <div class="container">
              <h1 class="display-3">%s</h1>
              <p style="font-weight: 500;margin-bottom: 32px;">Industry >> %s</p>
              <p><h5><span style="color: white;" class="sc-hover badge bg-dark" data-cardsize="small" data-quantity="2" data-ordertype="BUY">%s</span></h5>%s</p><br>
              <p><a class="btn btn-primary btn-lg" href=%s role="button" target="_blank">Learn more &raquo;</a></p>
              </div>
          </div>
          </main>
          <script async src="https://www.gateway-tt.in/assets/embed.js"></script>
          </body>
      </html>
      ''' %(stock_info['logo_url'],stock_info['longName'],stock_info['industry'],stock_name,stock_info['longBusinessSummary'],stock_info['website'])
      components.html(html1,height=720)
      
      #Financial info
      c1,c2,c3 = st.beta_columns(3)

      with c1:
          '''
          ### Market Cap: ₹**%d Cr.**
          ### EPS: ₹**%.2f**
          ### Book Value: ₹**%.2f **
          ### Stock PE: ** %.2f **
          ### Beta: ** %.2f **
          ''' %(stock_info['marketCap']//10000000,stock_info['trailingEps'],stock_info['bookValue']*70,stock_info['trailingPE'],stock_info['beta'])


      with c2:
          '''
          ### Earnings Growth(QoQ):** %.2f%% ** 
          ### Forward PE:** %.2f **
          ### Forward EPS: ₹**%.2f**
          ### Sector:** %s **
          ### 50 DMA: ₹**%.2f **
          ''' %(stock_info['earningsQuarterlyGrowth']*100,stock_info['forwardPE'],stock_info['forwardEps'],stock_info['sector'],stock_info['fiftyDayAverage'])


      with c3:
          '''
          ### 52 Week High / Low: ₹**%.2f / %.2f **
          ### Promoter Holding:** %.2f%% **
          ### Dividend Yield:** %.2f%% **
          ### 200 DMA: ₹**%.2f **
          ### CMP: ₹**%s ** 
          
          ''' %(stock_info['fiftyTwoWeekHigh'],stock_info['fiftyTwoWeekLow'],stock_info['heldPercentInsiders']*100,stock_info['dividendYield']*100,stock_info['twoHundredDayAverage'],cmp.text)

      ''' ***** '''
      st.text("")

      # strength & limitations
      col1, col2 = st.beta_columns(2)

      #Strengths
      col1.header("Strengths")
      strength = soup.find("ul", class_="strength").text
      strength = strength.strip().replace('\n','  \n')
      if strength=='':
        col1.success('No Strength')
      else:
        col1.success(strength)

      #Limitations
      col2.header("Limitations")
      limitations = soup.find("ul", class_="limitations").text
      limitations = limitations.strip().replace('\n','  \n')
      if limitations=='':
            col2.error("No Limitations")
      else:
            col2.error(limitations)
      
      #Price Chart
      st.text("")
      st.header("Price Chart")
      ticker = user_input
      new_ticker = '\"'+'BSE:'+ticker+'\"'
      chart='''
      <!-- TradingView Widget BEGIN -->
      <div class="tradingview-widget-container">
        <div id="basic-area-chart"></div>
        <div class="tradingview-widget-copyright"><a href="https://www.tradingview.com/symbols/'''+ticker+'''/" rel="noopener" target="_blank"><span class="blue-text">'''+ticker+''' Chart</span></a> by TradingView</div>
        <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
        <script type="text/javascript">
        new TradingView.widget(
        {
        "container_id": "basic-area-chart",
        "width": 1200,
        "height": 700,
        "symbol": '''+new_ticker+''',
        "interval": "D",
        "timezone": "exchange",
        "theme": "light",
        "style": "3",
        "toolbar_bg": "#f1f3f6",
        "hide_top_toolbar": true,
        "save_image": false,
        "locale": "en"
      }
        );
        </script>
      </div>
      <!-- TradingView Widget END -->
      '''
      components.html(chart,width=1400,height=700)

      #Annual Report
      reports = rk.balance_sheet(stock_name)
      annual_report = reports[1].rename(columns={'Unnamed: 0':' '})
      if 'TTM' in annual_report.columns:
          annual_report.drop('TTM',axis=1,inplace=True)
      years=np.array(annual_report.columns[1:])
      years= [int(item.split()[1]) for item in years]

      revenue=annual_report.iloc[0][1:]
      revenue = [int(item) for item in revenue]

      #Revenue (YOY)
      st.text("")
      st.header("Revenue (YOY) in Cr.")
      c=alt.Chart(pd.DataFrame({"Revenue":revenue,"Year":years})).mark_bar(size=50).encode(x='Year:O',y='Revenue',tooltip=['Revenue','Year'],opacity=alt.value(0.7),
      color=alt.value('#26c6da')).configure_view(strokeWidth=0).properties(height=500)
      st.altair_chart(c,use_container_width=True)

      #Profit (YOY)
      profit=annual_report.iloc[9][1:]
      profit = [int(item) for item in profit]

      st.text("")
      st.header("Profits (YOY) in Cr.")
      c=alt.Chart(pd.DataFrame({"Profit":profit,"Year":years})).mark_bar(size=50).encode(x='Year:O',y='Profit',tooltip=['Profit','Year'],opacity=alt.value(0.7),
      color=alt.value('#48e421')).configure_view(strokeWidth=0).properties(height=500)
      st.altair_chart(c,use_container_width=True)

      #Balance Sheet
      st.text("")
      st.header("Balance Sheet")
      balance_sheet = reports[6].rename(columns={'Unnamed: 0':' '})
      st.write(balance_sheet)

      #Shareholding pattern
      st.text("")
      st.header("Shareholding Pattern ")
      shareholders = list(reports[9]['Unnamed: 0'])
      shareholders = [i.rstrip("\xa0+") for i in shareholders]
      shareholding = list(reports[9][reports[9].columns[-1]])

      col1, col2, col3 = st.beta_columns([1,2,1])

      col1.write("")

      col2.vega_lite_chart(pd.DataFrame({'Shareholders':shareholders,'Shareholding':shareholding}), {
      "width": 600,
      "height": 600,
      "encoding": {
      "theta": {"field": "Shareholding", "type": "quantitative", "stack": True},
      "color": {"field": "Shareholders", "type": "nominal"},
      "tooltip": {"field": "Shareholding", "type": "quantitative"}
      },
      "layer": [{
          "mark": {"type": "arc", "outerRadius": 150}
      }, {
          "mark": {"type": "text", "radius": 190},
          "encoding": {
          "text": {"field": "Shareholders", "type": "nominal"}
          }
      }]
      })

      col3.write("")

      
      #Competitor analysis
      st.text("")
      st.header("Comparison with other stocks")
      stocks=[]
      stocks.append(stock.history(period="20y"))

      user_input2 = st.text_input("Enter stock 1",help="Enter a stock to compare with"+user_input)
      if user_input2!='':
          stock1 = yf.Ticker(user_input2.upper()+".NS")
          stocks.append(stock1.history(period="20y"))
          if (stocks[1].empty):
                  st.error("Error.....Incorrect")
                  st.stop()

      user_input3 = st.text_input("Enter stock 2",help="Enter a stock to compare with"+user_input)
      if user_input3!='':
          stock2 = yf.Ticker(user_input3.upper()+".NS")
          stocks.append(stock2.history(period="20y"))
          if (stocks[2].empty):
                  st.error("Error.....Incorrect")
                  st.stop()


      if user_input2!='' and user_input3!='':

        stocks[0]['symbol']=user_input
        stocks[1]['symbol']=user_input2
        stocks[2]['symbol']=user_input3
        #st.write(stocks[0].tail(5))
        df = pd.concat([s[['Close','Volume','symbol']] for s in stocks])
        df.reset_index(level=0, inplace=True) #make Date a column instead of index
        st.text("")
        st.header("Comparative Price Chart")
        c=alt.Chart(df,height=650).mark_line().encode(
        x='Date',
        y='Close',
        color='symbol',
        tooltip=alt.Tooltip(['Close'], format='.2f',title='INR')
        ).interactive()
        st.altair_chart(c,use_container_width=True)
        
        #volume
        st.text("")
        st.header("Traded Volumes")
        selection = alt.selection_multi(fields=['symbol'], bind='legend')
        c=alt.Chart(df,height=650).mark_line().encode(
        x='Date',
        y='Volume',
        color='symbol',
        tooltip=alt.Tooltip(['Volume']),
        opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
        ).add_selection(selection)
        st.altair_chart(c,use_container_width=True)

        #Histogram
        st.text("")
        st.header("Daily Percentage Change")
        col1, col2, col3 = st.beta_columns(3)
        for i,col,name in (zip(range(3),[col1,col2,col3],[user_input,user_input2,user_input3])):
            stocks[i]['Returns']=stocks[i]['Close'].pct_change(1)
            col.altair_chart(alt.Chart(stocks[i]).mark_bar().encode(
                x=alt.X("Returns:Q", bin=alt.Bin(extent=[-0.100,0.100],step=0.005),title=name),
                y=alt.Y(aggregate="count",title="",type="quantitative")
            ).properties(height=500).interactive(),use_container_width=True)

        #Scatter Matrix
        st.text("")
        st.header("Scatter Matrix - (Finding Correlation)")
        st.text("")
        box_df = pd.concat([stocks[0]['Returns'],stocks[1]['Returns'],stocks[2]['Returns']],axis=1)
        box_df.columns = [user_input+" Returns",user_input2+" Returns",user_input3+" Returns"]
        st.altair_chart(alt.Chart(box_df).mark_circle().encode(
            alt.X(alt.repeat("column"), type='quantitative'),
            alt.Y(alt.repeat("row"), type='quantitative'),
            color='Origin:N'
        ).properties(
            width=385,
            height=185
        ).repeat(
            row=list(box_df.columns),
            column=list(box_df.columns[::-1])
        ).interactive(),use_container_width=True)
예제 #15
0
import pandas as pd
import pickle5 as pickle
import pandas as pd
import streamlit as st
import plotly.express as px
import SessionState
import preditc
my_page = st.sidebar.radio('Select Option Below :',
                           ['Data Visualization', 'Predictions', 'Raw Data'])

st.title("NewYork Airbnb (EDA and Predictions)")
st.markdown(
    "Data Collected from Air Bnb website for the period of Jan-2020 To Dec-2020"
)

data_load_state = st.text("")
#st.balloons()

# Region Starts Global Methods
# Reading Pickle File


def load_data(path):
    with open(path, 'rb') as f:
        data = pickle.load(f)
    return data


# Region Ends Global Methods

# Region Starts Global Variables
예제 #16
0
# import libraries
import streamlit as st

# import local app libraries
import pandas
from pandas.plotting import scatter_matrix
from sklearn.linear_model import LinearRegression
import numpy
import matplotlib.pyplot as plt

# add title
st.title("Make predictions web app")

# add a instruction
st.text("Please, upload your file in the sidebar")

# add a instruction
st.sidebar.text("Upload your file here")

# add uploader file
uploadFile = st.sidebar.file_uploader("Upload your excel file", type=[".xlsx"])

# user input
userToPredict = st.sidebar.number_input("Temperature to predict")

# start analusis button
startAnalysis = st.sidebar.button("Start analysis")

# if strt the analysis
if startAnalysis:
예제 #17
0
#importando as bibliotecas
import pandas as pd
import streamlit as st

#importando os dados de 2017
df_17 = pd.read_csv("DM_CURSO.csv", delimiter='|')

st.title("Cursos disponíveis nas Universidades brasileiras (2017)")
st.text('')
st.text('')
st.image('inep.jpg')
st.markdown("""
    Esse bancos de dados foi extraído do [site do INEP](https://www.gov.br/inep/pt-br/acesso-a-informacao/dados-abertos/microdados/censo-da-educacao-superior) 
    corresponde aos mais de **35 mil** cursos ofertados pelas Universidades Brasileiras.
""")

#soma da coluna QT_MATRICULA_TOTAL com os seguintes filtros:
#- TP-CATEGORIA_ADMINISTRATIVA == 2)
#- TP_ORGANIZACAO_ACADEMICA == 1
#- CO_UF == 42 (equivalente ao Estado de SANTA CATARINA)
#- TP-GRAU_ACADEMICO == 2

if st.sidebar.checkbox('Visualizar cabeçalho da tabela? '):
    st.header("Cabeçalho da tabela DM_CURSO.csv:")
    st.write(df_17.head())
    st.markdown("""
        **Fonte:** INEP
        """)

st.sidebar.info(
    f"O Dataset de 2017 completo possui {df_17.shape[0]} linhas e {df_17.shape[1]} colunas."
예제 #18
0
    csv = df.to_csv(index=False)
    b64 = base64.b64encode(csv.encode()).decode(
    )  # some strings <-> bytes conversions necessary here
    href = f'<a href="data:file/csv;base64,{b64}">Download csv file</a>'
    return href


# create table if not exists
table_name = "ExpensesTable2021"
try:
    sql_table_query = 'create table ' + table_name + '(DateTime text PRIMARY KEY, Amount REAL, Reason text)'
    cursor.execute(sql_table_query)
except:
    pass

st.text("Expense Manager 2021")
written_state = 0

# encode passcode to bytes
passcode = str.encode(st.text_input(" passcode", ''))
try:
    cipher_suite = Fernet(passcode)
    with open(".pickachu.pckl", "rb") as handle:
        message = cipher_suite.decrypt(pickle.load(handle))
    encoded_text = cipher_suite.encrypt(message)
    decoded_text = cipher_suite.decrypt(encoded_text)
    try:
        expense_name, amount_spent = st.text_input(" reason, amount",
                                                   '').split(',')
        expense_name = expense_name.strip()
        amount_spent = float(amount_spent.strip())
예제 #19
0
def main():
    st.title("Bank Data Analysis 🏦")
    st.sidebar.title("Bank Data Analysis 🏦")
    st.markdown("This Application is for Bank Data Analysis")
    st.sidebar.markdown("The data is related with direct marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls.")
    activities = ["Home", "Predict Fixed Deposit Creation"]
    choice = st.sidebar.selectbox("Choose activity", activities)

    if choice == 'Predict Fixed Deposit Creation':
        st.info("Prediction if Customer creates fixed deposit or not")
        age = st.number_input("Age",18,100)
        job   = st.selectbox("Occupation", tuple(job_dict.keys()) )
        housing	 = st.radio("Has housing loan?", tuple(feature_dict.keys()) )
        month	 = st.selectbox("Whiich month was the client last contacted in? ",tuple(month_dict.keys()) )
        duration  = st.number_input("Duration of last call in seconds", 1, 5000)
        pdays = st.text_input("Number of days that passed by after the client was last contacted(-1 if not contacted) " )
        previous = st.text_input("Number of contacts performed before this campaign and for this client " )

        feature_list = [age,get_value(job,job_dict),get_fvalue(housing),get_value(month, month_dict),duration,pdays, previous]
        single_sample = np.array(feature_list).reshape(1,-1)


        model_choice = st.selectbox("Select Model",["Random Forest Classification","Decision Tree Classifier", "KNN Classifier"])

        st.text("")
	
        if st.button("Predict Outcome"):
            if model_choice == "Random Forest Classification":
                prediction = RF_classifier.predict(single_sample)
                pred_prob = RF_classifier.predict_proba(single_sample)
  

            if prediction == 0:
                st.text("")
                st.warning("Customer doesn't create Bank Term Deposit")
                pred_probability_score = {"Not creating account":pred_prob[0][0]*100,"Creating Account":pred_prob[0][1]*100}
                #st.markdown(result_temp,unsafe_allow_html=True)
                st.text("")
                st.subheader("Prediction Probability Score using {}".format(model_choice))
                st.info(pred_probability_score)
                	
							
            else:
                st.text("")
                st.success("Customer creates Bank Term Deposit")
                pred_probability_scoreY = {"Not creating account":pred_prob[0][0]*100,"Creating Account":pred_prob[0][1]*100}
                #st.markdown(result_temp,unsafe_allow_html=True)
                st.text("")
                st.subheader("Prediction Probability Score using {}".format(model_choice))
                st.json(pred_probability_scoreY)    
        
    





    

    else:
       # st.markdown("<h1 style='text-align: center; color: black; font-size: 60px'>Bank Data Analysis 🏦</h1>", unsafe_allow_html=True)
        
        st.markdown("<p style='text-align: center; color: black; font-size: 20px'>This application makes 4 different types of predictions using the Bank Marketing Dataset.</p>", unsafe_allow_html=True)
        st.markdown("<p style='text-align: center; color: black; font-size: 20px'>The predictions are: </p>", unsafe_allow_html=True)
        st.markdown("<h5 style='text-align: center; color: black; font-size: 20px'>1. Predicts if a customer creates a Fixed Deposit account or not </h5>", unsafe_allow_html=True)
        st.markdown("<h5 style='text-align: center; color: black; font-size: 20px'>2. Predicts if a customer is suitable to give a Bank Loan </h5>", unsafe_allow_html=True)
        st.markdown("<h5 style='text-align: center; color: black; font-size: 20px'>3. Predicts if a customer may take a Housing Loan </h5>", unsafe_allow_html=True)
        st.markdown("<h5 style='text-align: center; color: black; font-size: 20px'>4. Predicts if a customer may take a Personal Loan </h5>", unsafe_allow_html=True)
        

        @st.cache(allow_output_mutation=True)
        def get_base64_of_bin_file(bin_file):
            with open(bin_file, 'rb') as f:
                data = f.read()
            return base64.b64encode(data).decode()

        def set_png_as_page_bg(jpg_file):
            bin_str = get_base64_of_bin_file(jpg_file)
            page_bg_img = '''
            <style>
            body {
            background-image: url("data:uu/jpg;base64,%s");
            background-size: cover;
            }
            </style>
            ''' % bin_str
            
            st.markdown(page_bg_img, unsafe_allow_html=True)
            return

        set_png_as_page_bg('ii4.jpg')
예제 #20
0
# Copyright 2018-2022 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st

st.text("The space between this...")
st.text("..and this should be the same as between this...")
st.empty()
st.text("...and this")
예제 #21
0
def output(input):
    if input == "":
        output = ""
    else:
        output = get_genre(input)
    return output


def output2(input1, input2):
    if input2 == "":
        output2 = ""
    else:
        output2 = is_spoiler(input1, input2)
    return output2


# Create a text element and let the reader know the data is loading.
data_load_state = st.text('Loading data...')
# Processing the data
genres = output(user_input)
# Notify the reader that the data was successfully loaded.
#data_load_state.text('Loading data...done!')

st.subheader(f'The genre(s) of the movie: \n {(genres)}')
data_load_state.text('')

user_input2 = st.text_area("Please write a review")

st.subheader(f'Is it a spoiler? \n {(output2(user_input, user_input2))}')
예제 #22
0
import streamlit as st
from tensorflow.keras.models import load_model
import wget
from PIL import Image
import tensorflow.keras as keras
import io
import cv2
import numpy as np
from gradcam import GradCam
import io
st.markdown(
    "<h1 style='text-align: center; color: black;'>Phneumonia detection website</h1>",
    unsafe_allow_html=True)
st.text("Plase upload your lungs x-ray here")
uploaded_file = st.file_uploader("Upload Files", type=['png', 'jpeg', 'jpg'])
model = load_model('model.hdf5')

grad = GradCam(model)


def predict(matrix):

    overlay = grad.get_gradcam_overlay(matrix, 0)
    prediction = int(np.round(grad.score.numpy()))
    return (overlay, prediction)


def load_img(bytes):
    nparr = np.fromstring(bytes, np.uint8)
    img_np = cv2.imdecode(nparr,
                          cv2.IMREAD_COLOR)  # cv2.IMREAD_COLOR in OpenCV 3.1
예제 #23
0
</div> 
"""

# display the front end aspect
st.markdown(html_temp, unsafe_allow_html=True)

#create containers
header = st.beta_container()
dataset = st.beta_container()
features = st.beta_container()
model_training = st.beta_container()

#write in header section
with header:
    st.title("PCADS- CAPSTONE PROJECT")
    st.text('Developed by ....Subramanian Hariharan ')
    st.text('Date ...........February 2021')
    st.markdown(
        "> “You can have data without information, but you cannot have information without data.” \n\n—Daniel Keys Moran"
    )
    st.header('Problem Statement')
    st.markdown(
        """The dataset is sourced from open domain and is about data related to a hospital in Greenland. It is the responsibility of Hospital Administration to provide efficient and timely patient care to ensure that the individual concerned recovers from the illness completely. The Hospital admistration is seeking answers for improving the standard 
                of medical care by addressing related factors. The data is related to a particular department in the Hospital where mortality rate is beyond acceptable levels. Accordingly, it is understood that towards this, the data related to patient has been obtained from multiple SQL tables in the database and collated. The historical data collates information 
                regarding demographics of the patient as well as treatment and medical condition and includes a binary variable which indicates whether the patient survived at the end of 12 months of care. The attributes  which affect the patient survival in a significant way can also be flagged.
                The **Objective** of the Project is to analyse the factors given in the dataset and predict chance of survival of patient at the end of 12 months of treatment. 
                with dataset:""")
    st.header('PATIENT DATASET')
    st.text('This Dataset is available in open domain...https://dphi.tech/')
data = pd.read_csv('dataset/patient_survival.csv')  #read the csv file into df
예제 #24
0
def write():
    st.title("Company")
    df = get_tw_equity()

    symbol_lst = get_symbol_lst()  # Full symbol with .TW
    new_symbol_lst = [symbol[:-3]
                      for symbol in symbol_lst]  # Symbol with no .TW

    tw_equity_sector = sorted(df["sector"].unique().tolist())
    tw_sector = st.sidebar.selectbox("Select sector", tw_equity_sector)
    stock = st.sidebar.text_input("Enter symbol", value="")
    stock_lst = df[df.sector == tw_sector].rename(
        columns={"longName": "Company Name"})
    st.write(f"Sector: {tw_sector}")

    # Symbol input condition
    if stock in symbol_lst:
        stock = stock
    elif stock in new_symbol_lst:
        stock = stock + ".TW"

    # App condition
    if stock == "":
        st.table(stock_lst[["symbol", "Company Name"]].reset_index(drop=True))
    else:
        company_info = get_company_info(stock)
        st.write(f"Company Name: {company_info['longName']}")
        st.write(f"Industry: {company_info['industry']}")
        business_summary = st.checkbox("Business Summary")
        if business_summary:
            st.write(company_info['longBusinessSummary'])
        contact_info = st.checkbox("Contact Info")
        if contact_info:
            st.write(f"City: {company_info['city']}")
            st.write(f"Phone: {company_info['phone']}")
            st.write(f"Website: {company_info['website']}")

        st.sidebar.header("Finance")
        market_info = st.sidebar.checkbox("Market Info")

        if market_info:
            st.subheader("Open - High - Low - Close")
            st.text("1 Month History Data")
            time_range = "1mo"
            st.dataframe(stock_ohlc(stock, time_range))
        stock_pred = st.sidebar.checkbox("Stock Price Prediction")
        if stock_pred:
            st.subheader("Next day stock predictions")

            option = {
                "High": "highest",
                "Low": "lowest",
                "Open": "open",
                "Close": "close"
            }

            def format_func(item):
                return option[item]

            word = st.selectbox('Select a feature you want to predict',
                                options=list(option.keys()))

            num_days = st.text_input("Enter a number of days", "1")
            num_days = int(num_days)
            st.info(
                f"Predict the {format_func(word)} price of the next deal day based on past {num_days} days"
            )

            df = get_stock_history(stock)
            df_new = df[[word]]
            dataset = df_new.values
            #test:train = 3:7
            training_data_len = math.ceil(len(dataset) * .7)
            scaler = MinMaxScaler(feature_range=(0, 1))
            scaled_data = scaler.fit_transform(dataset)

            #Create a training data set that contains the past 1 day closing price values
            #that we want to use to predict the 15st closing price value.
            train_data = scaled_data[0:training_data_len, :]
            x_train, y_train = [], []
            for i in range(num_days, training_data_len):
                x_train.append(scaled_data[i - num_days:i, 0])
                y_train.append(scaled_data[i, 0])
            x_train, y_train = np.array(x_train), np.array(y_train)
            x_train = np.reshape(x_train,
                                 (x_train.shape[0], x_train.shape[1], 1))

            lstm = Sequential()
            lstm.add(
                LSTM(units=50,
                     return_sequences=True,
                     input_shape=(x_train.shape[1], 1)))
            lstm.add(LSTM(units=50))
            lstm.add(Dense(1))
            lstm.compile(loss='mean_squared_error', optimizer='adam')

            if st.button('Train the model'):
                with st.spinner(
                        "Training may take time based on number of days. Please wait..."
                ):
                    history_lstm = lstm.fit(x_train,
                                            y_train,
                                            epochs=25,
                                            batch_size=10,
                                            verbose=2)
                    st.success("Model is ready!")

                test_data = scaled_data[training_data_len - num_days:, :]
                x_test = []
                y_test = dataset[training_data_len:, :]
                for i in range(num_days, len(test_data)):
                    x_test.append(test_data[i - num_days:i, 0])
                x_test = np.array(x_test)
                x_test = np.reshape(x_test,
                                    (x_test.shape[0], x_test.shape[1], 1))

                pred = lstm.predict(x_test)
                pred = scaler.inverse_transform(pred)

                st.header("Prediction")
                #inputs are data of past ? days
                inputs = df_new.iloc[len(df_new) - num_days:len(df_new)].values
                inputs = inputs.reshape(-1, 1)
                inputs = scaler.fit_transform(inputs)
                p = inputs.reshape(1, num_days,
                                   1)  #(Samples,time_step,features)
                result = lstm.predict(p)
                result = scaler.inverse_transform(result)
                st.write("The {} price of next deal day is :".format(word))
                st.info(round(float(result), 2))

                def get_mape(y_true, y_pred):
                    """
                    Compute mean absolute percentage error (MAPE)
                    """
                    y_true, y_pred = np.array(y_true), np.array(y_pred)
                    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100

                st.header("Model Evaluation")
                st.write('R Square - ', round(metrics.r2_score(y_test, pred),
                                              2))
                st.write('Mean absolute percentage error(MAPE) - ',
                         round(get_mape(y_test, pred), 2))
                st.write(
                    'Root Mean Square Error(RMSE) -',
                    round(np.sqrt(metrics.mean_squared_error(y_test, pred)),
                          2))
                st.write('Mean Absolute Error(MAE) - ',
                         round(metrics.mean_absolute_error(y_test, pred), 2))
예제 #25
0
def main():
    """Common ML Data Explorer """
    st.title("Common ML Dataset Explorer")
    st.subheader("Simple DataScience App with Streamlit")

    html_temp = """
	<div style="background-color:tomato;"><p style="color:white;font-size:60px;"> Streamlit is Awesome</p></div>
	"""
    st.markdown(html_temp, unsafe_allow_html=True)

    # img_list = glob.glob("images/*.png")
    # # st.write(img_list)
    # # for i in img_list:
    # # 	c_image = Image.open(i)
    # # 	st.image(i)
    # all_image = [Image.open(i) for i in img_list]
    # st.image(all_image)

    # def file_selector(folder_path='./datasets'):
    #     filenames = os.listdir(folder_path)
    #     selected_filename = st.selectbox('Select a file', filenames)
    #     return os.path.join(folder_path, selected_filename)

    filename = "iris.csv"
    st.write('You selected `{0}`'.format(filename))
    df = pd.read_csv(filename)

    # Show Dataset
    if st.checkbox("Show DataSet"):
        number = st.number_input("Number of Rows to View", 1, 100)
        st.dataframe(df.head(number))
    # Show Column Names
    if st.button("Columns Names"):
        st.write(df.columns)

    # Show Shape of Dataset
    if st.checkbox("Shape of Dataset"):
        st.write(df.shape)
        data_dim = st.radio("Show Dimension by", ("Rows", "Columns"))
        if data_dim == 'Rows':
            st.text("Number of  Rows")
            st.write(df.shape[0])
        elif data_dim == 'Columns':
            st.text("Number of Columns")
            st.write(df.shape[1])
    # Show Columns By Selection
    if st.checkbox("Select Columns To Show"):
        all_columns = df.columns.tolist()
        selected_columns = st.multiselect('Select', all_columns)
        new_df = df[selected_columns]
        st.dataframe(new_df)

    # Datatypes
    if st.button("Data Types"):
        st.write(df.dtypes)

    # Value Counts
    if st.button("Value Counts"):
        st.text("Value Counts By Target/Class")
        st.write(df.iloc[:, -1].value_counts())

    # Summary
    if st.checkbox("Summary"):
        st.write(df.describe())

    st.subheader("Data Visualization")
    # Show Correlation Plots
    # Matplotlib Plot
    if st.checkbox("Correlation Plot [Matplotlib]"):
        plt.matshow(df.corr())
        st.pyplot()

    # Seaborn Plot
    if st.checkbox("Correlation Plot with Annotation[Seaborn]"):
        st.write(sns.heatmap(df.corr(), annot=True))
        st.pyplot()

    # Counts Plots
    if st.checkbox("Plot of Value Counts"):
        st.text("Value Counts By Target/Class")

        all_columns_names = df.columns.tolist()
        primary_col = st.selectbox('Select Primary Column To Group By',
                                   all_columns_names)
        selected_column_names = st.multiselect('Select Columns',
                                               all_columns_names)
        if st.button("Plot"):
            st.text("Generating Plot for: {} and {}".format(
                primary_col, selected_column_names))
            if selected_column_names:
                vc_plot = df.groupby(
                    primary_col)[selected_column_names].count()
            else:
                vc_plot = df.iloc[:, -1].value_counts()
            st.write(vc_plot.plot(kind='bar'))
            st.pyplot()

    # Pie Plot
    if st.checkbox("Pie Plot"):
        all_columns_names = df.columns.tolist()
        # st.info("Please Choose Target Column")
        # int_column =  st.selectbox('Select Int Columns For Pie Plot',all_columns_names)
        if st.button("Generate Pie Plot"):
            # cust_values = df[int_column].value_counts()
            # st.write(cust_values.plot.pie(autopct="%1.1f%%"))
            st.write(df.iloc[:, -1].value_counts().plot.pie(autopct="%1.1f%%"))
            st.pyplot()

    # Barh Plot
    if st.checkbox("BarH Plot"):
        all_columns_names = df.columns.tolist()
        st.info("Please Choose the X and Y Column")
        x_column = st.selectbox('Select X Columns For Barh Plot',
                                all_columns_names)
        y_column = st.selectbox('Select Y Columns For Barh Plot',
                                all_columns_names)
        barh_plot = df.plot.barh(x=x_column, y=y_column, figsize=(10, 10))
        if st.button("Generate Barh Plot"):
            st.write(barh_plot)
            st.pyplot()

    # Custom Plots
    st.subheader("Customizable Plots")
    all_columns_names = df.columns.tolist()
    type_of_plot = st.selectbox("Select the Type of Plot",
                                ["area", "bar", "line", "hist", "box", "kde"])
    selected_column_names = st.multiselect('Select Columns To Plot',
                                           all_columns_names)
    # plot_fig_height = st.number_input("Choose Fig Size For Height",10,50)
    # plot_fig_width = st.number_input("Choose Fig Size For Width",10,50)
    # plot_fig_size =(plot_fig_height,plot_fig_width)
    cust_target = df.iloc[:, -1].name

    if st.button("Generate Plot"):
        st.success("Generating A Customizable Plot of: {} for :: {}".format(
            type_of_plot, selected_column_names))
        # Plot By Streamlit
        if type_of_plot == 'area':
            cust_data = df[selected_column_names]
            st.area_chart(cust_data)
        elif type_of_plot == 'bar':
            cust_data = df[selected_column_names]
            st.bar_chart(cust_data)
        elif type_of_plot == 'line':
            cust_data = df[selected_column_names]
            st.line_chart(cust_data)
        elif type_of_plot == 'hist':
            custom_plot = df[selected_column_names].plot(kind=type_of_plot,
                                                         bins=2)
            st.write(custom_plot)
            st.pyplot()
        elif type_of_plot == 'box':
            custom_plot = df[selected_column_names].plot(kind=type_of_plot)
            st.write(custom_plot)
            st.pyplot()
        elif type_of_plot == 'kde':
            custom_plot = df[selected_column_names].plot(kind=type_of_plot)
            st.write(custom_plot)
            st.pyplot()
        else:
            cust_plot = df[selected_column_names].plot(kind=type_of_plot)
            st.write(cust_plot)
            st.pyplot()

    st.subheader("Our Features and Target")

    if st.checkbox("Show Features"):
        all_features = df.iloc[:, 0:-1]
        st.text('Features Names:: {}'.format(all_features.columns[0:-1]))
        st.dataframe(all_features.head(10))

    if st.checkbox("Show Target"):
        all_target = df.iloc[:, -1]
        st.text('Target/Class Name:: {}'.format(all_target.name))
        st.dataframe(all_target.head(10))

    # Make Downloadable file as zip,since markdown strips to html
    st.markdown("""[google.com](iris.zip)""")

    # def make_zip(data):
    # 	output_filename = '{}_archived'.format(data)
    # 	return shutil.make_archive(output_filename,"zip",os.path.join("downloadfiles"))

    def makezipfile(data):
        output_filename = '{}_zipped.zip'.format(data)
        with ZipFile(output_filename, "w") as z:
            z.write(data)
        return output_filename

    if st.button("Download File"):
        DOWNLOAD_TPL = f'[{filename}]({makezipfile(filename)})'
        # st.text(DOWNLOAD_TPL)
        st.text(DOWNLOAD_TPL)
        st.markdown(DOWNLOAD_TPL)
예제 #26
0
data = os.listdir("ML\Data")


@st.cache
def load_data(name):
    return pds.read_csv("ML\\Data\\" + name)


rad = st.sidebar.radio(
    "Sommaire", ["Home", "Affichage des datasets", "Visualisation graphique"])

if rad == "Home":
    st.title("Streamlit Crash course")
    st.subheader("Home")
    st.text("Voici le cours de streamlit")

if rad == "Affichage des datasets":
    st.title("Affichage des datasets")
    option = st.selectbox("Choisi un dataset", data)

    df = load_data(option)
    nb_line = st.number_input("Nombre de lignes à charger : ",
                              min_value=1,
                              max_value=len(df))

    st.subheader("Affichage des {} premieres lignes : ".format(nb_line))

    st.dataframe(df.head(nb_line))
    st.subheader("Types : ")
예제 #27
0
    fig.update_yaxes(showticklabels=False)
    fig.update_layout(
        title_text="Your Text's Probability of Correlating with Depression")
    fig.update_yaxes(title_text='')

    fig
    st.subheader(message)
    st.markdown(rec)

    for i in warning_list:
        if i in text_input:
            st.markdown(
                'Your input may contain references to self-harm or suicide. If you are considering self-harm or suicide, please reach out to the [Crisis Text Line](https://www.crisistextline.org/topics/self-harm/#what-is-self-harm-1) or call the suicide hotline number at [800-273-8255](Tel:800-273-8255).'
            )

st.text("")
st.text("")
st.text("")
st.text("")

# Mood Tracker
st.title('Mood Tracker')
st.subheader(
    'Enter journal entries indicating how you have been feeling over 7 days')

day_1 = st.text_input('Answer Day 1:')
day_2 = st.text_input('Answer Day 2:')
day_3 = st.text_input('Answer Day 3:')
day_4 = st.text_input('Answer Day 4:')
day_5 = st.text_input('Answer Day 5:')
day_6 = st.text_input('Answer Day 6:')
        max = 1000

    def form2():
        with st.form(key='form2'):
            text_input = st.text_input(label=f"Enter Prediction Dataset range (MAX: {max})")
            submit_button = st.form_submit_button(label='Submit')
        return text_input


    review_count = form2()

    if review_count != "":
        review_count = int(float(review_count))
        r = int(review_count/5)
        count = 0
        st.text('Downloading Reviews....')
        with open('test.tsv', 'w+') as f:
            f.write('Review\n')
            for i in range(r):
                url=f'https://developers.zomato.com/api/v2.1/reviews?res_id={res_id}&start={count}&count=5'
                response=requests.get(url,headers=header)
                data=response.json()
                reviews=data['user_reviews']
                for i in range(len(reviews)):
                    x = reviews[i]['review']['review_text'].strip()
                    if x != '':
                        f.write(x+'\n')

                count += 5

        st.text('Finished')
def main():
    st.title("Face Detection App")
    st.text("Built with Streamlit and Open CV")

    activities = ["Detection", "About"]
    choice = st.sidebar.selectbox("Select Activity", activities)

    if choice == 'Detection':
        st.subheader("Face Detection")

        image_file = st.file_uploader(
            "Upload Image", type=['jpg', 'png', 'jpeg'])

        if image_file is not None:
            our_image = Image.open(image_file)
            st.text("Original Image")
            st.image(our_image, width=500)

        enhance_type = st.sidebar.radio(
            "Enhance Type", ["Original", "Gray-Scale", "Contrast", "Brightness", "Blurring"])
        if enhance_type == "Gray-Scale":
            new_img = np.array(our_image.convert('RGB'))
            img = cv2.cvtColor(new_img, 1)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            st.image(gray, width=500)
        if enhance_type == "Contrast":
            c_rate = st.sidebar.slider("Contrast", 0.5, 3.5)
            enhancer = ImageEnhance.Contrast(our_image)
            img_output = enhancer.enhance(c_rate)
            st.image(img_output, width=500)
        if enhance_type == "Brightness":
            c_rate = st.sidebar.slider("Brightness", 0.5, 3.5)
            enhancer = ImageEnhance.Brightness(our_image)
            img_output = enhancer.enhance(c_rate)
            st.image(img_output, width=500)
        if enhance_type == "Blurring":
            new_img = np.array(our_image.convert('RGB'))
            blur_rate = st.sidebar.slider("Blur", 0.5, 3.5)
            img = cv2.cvtColor(new_img, 1)
            blur_img = cv2.GaussianBlur(img, (11, 11), blur_rate)
            st.image(blur_img, width=500)

        # Face Detection
        task = ["Faces", "Smiles", "Eyes", "Cannize", "Cartonize"]
        feature_choice = st.sidebar.selectbox("Find Features", task)
        if st.button("Process"):

            if feature_choice == 'Faces':
                result_img, result_faces = detect_faces(our_image)
                st.image(result_img, width=500)
                st.success("Found {} faces".format(len(result_faces)))

            elif feature_choice == 'Eyes':
                result_img = detect_eyes(our_image)
                st.image(result_img, width=500)

            elif feature_choice == 'Smiles':
                result_img = detect_smiles(our_image)
                st.image(result_img, width=500)

            elif feature_choice == 'Cannize':
                result_img = cannize_image(our_image)
                st.image(result_img, width=500)

            elif feature_choice == 'Cartonize':
                result_img = cartonize_image(our_image)
                st.image(result_img, width=500)

    elif choice == 'About':
        st.subheader("About")
        st.text("A Face Detection Application built with Streamlit and Open CV in Python. \nIt provides features of \n- Editing Your Image\n- Face Detection\n- Smile Detection\n- Eyes Detection\n- Cartoonizing your image")
        st.subheader("\n\n\nBuilt by Mihir Pesswani")
예제 #30
0
파일: app.py 프로젝트: tlkh/mini-dlperf
    with st.spinner("Running: " + exp_name):
        progress_bar.progress(67)
        results = utils.run_command("python3 run_cnn.py --threads " + threads +
                                    " --huge_cnn --batch_size " + batch_size)
        if results[-1].split(",")[0] == "PASS":
            hugecnn_10gb = exp_name + "," + results[-1]
            st.success(hugecnn_10gb)
        else:
            st.error(exp_name, "FAIL")
        progress_bar.progress(99)

    end_time = time.time()

    progress_bar.progress(100)

    st.text("Total time taken:", int(end_time - start_time), "seconds.")

    cols = [
        "name", "passed", "avg_fps", "avg_sm_%", "avg_mem_io_%", "avg_pcie_%",
        "pcie_gbps", "avg_pwr_%", "pwr_watts", "avg_temp", "max_vram",
        "avg_nvlink", "throttle"
    ]
    df = pd.DataFrame([
        rn50_10gb.split(","),
        rn50_imgaug_10gb.split(","),
        hugecnn_10gb.split(",")
    ],
                      columns=cols)

    st.dataframe(df)