CoolFace
Apppublic

PocketTanks/GradioInterface

sourceHugging Faceapache-2.0updated 3y agoView on Hugging Face
0likes
app.py107 linesDownload Raw Back to root
1import gradio as gr2import yfinance as yf3import plotly.graph_objects as go4import plotly.express as px5from datetime import datetime6import matplotlib.pyplot as plt7import numpy as np8import pandas as pd9 10# Function to construct the pie chart11def get_pie_graph(data):12  data['Change'] = data['Open'] - data['Close'].shift(1)13  data['Movement'] = data['Change'].apply(lambda x : 'Up' if x > 0 else 'Down')14  fig, ax = plt.subplots()15  ax.pie(data['Movement'].value_counts(), labels=[f"{label}: {count}" for label, count in zip(data['Movement'].unique(), data['Movement'].value_counts().tolist())])16  return fig17 18# Function to construct the chart with markers19def get_trading_markers(data, t, tll):20    val = data['Close']21    th = []22    marker = []23 24    for i in range(len(data)):25        if(i == 0):26            th.append(0)27        else:28            x = val[i] - val[i-1]29            x =  (x / val[i-1] )*1030            th.append(abs(x))31 32    data['Value'] = th33    data['Marker'] = np.where(data['Value'] > t, 'yes', 'no')34 35    df = data[data['Marker'] == 'yes']36    df = df.Close37 38    x = pd.DataFrame({tll: data["Close"]})39    plt.plot(x)40    plt.scatter(df.index, df, marker = 'x', c = 'b' , s = 60, zorder=2)41    plt.title(tll)42 43    return plt44 45def get_stock_data(start_date, end_date, stock_ticker, graph_type, t):46    # Validate date format47    try:48        start_date = datetime.strptime(start_date, "%Y-%m-%d").date()49        end_date = datetime.strptime(end_date, "%Y-%m-%d").date()50    except ValueError:51        return "Invalid date format. Please use the YYYY-MM-DD format."52 53    # Fetch stock data using Yahoo Finance API54    data = yf.download(stock_ticker, start=start_date, end=end_date)55    data.reset_index(inplace=True)  # Reset index to get separate "Date" column56 57    # Return a different graph type depending on which option the user selected58    match graph_type:59      case 'Line chart of open prices':60        # Create the line plot using Plotly Express61        line_fig = px.line(data, x='Date', y='Open', title='Open Price')62        return line_fig63 64      case 'Candle chart of stocks':65        candle_fig = go.Figure(data=[go.Candlestick(x=data['Date'],66                open=data['Open'],67                high=data['High'],68                low=data['Low'],69                close=data['Close'])])70        return candle_fig71 72      case 'Chart of volume traded':73        bar_fig = px.line(data, x = 'Date', y = 'Volume', title = 'Volume Traded')74        return bar_fig75 76      case 'Pie chart of stock movement':77        pie_fig = get_pie_graph(data)78        return pie_fig79 80      case 'Chart of trading markers':81        trade_markers_fig = get_trading_markers(data,t, stock_ticker)82        return trade_markers_fig83 84outputs = [gr.Plot(label="Plot")]85 86iface = gr.Interface(87    fn=get_stock_data,88    inputs=[89        gr.inputs.Textbox(placeholder="YYYY-MM-DD", label="Start Date"),90        gr.inputs.Textbox(placeholder="YYYY-MM-DD", label="End Date"),91        gr.inputs.Textbox(placeholder="AAPL", label="Stock Ticker"),92        # Dropdown of different choices of graphs to display93        gr.inputs.Dropdown(choices=['Line chart of open prices',94                                    'Candle chart of stocks',95                                    'Chart of volume traded',96                                    'Pie chart of stock movement',97                                    'Chart of trading markers'],98                            label='Graph type'),99        gr.inputs.Number(label="Marker value")100 101    ],102    outputs=outputs,103    title="Stock Data Viewer",104    description="Enter the start date, end date, and stock ticker to view the stock data.",105)106 107iface.launch()