Spaces:
Sleeping
Sleeping
| import yfinance as yf | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import mplfinance as mpf | |
| def create_beginner_friendly_candlestick_chart(ticker, period="6mo", interval="1d"): | |
| try: | |
| # Fetch stock data | |
| stock = yf.Ticker(ticker) | |
| df = stock.history(period=period, interval=interval) | |
| if df.empty: | |
| return "No data found for the stock", None | |
| # Ensure the index is a DatetimeIndex | |
| df.index = pd.to_datetime(df.index) | |
| # Prepare data for mplfinance | |
| df_mpl = df[['Open', 'High', 'Low', 'Close', 'Volume']] | |
| # Create a more straightforward mplfinance plot | |
| style = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size':10}) | |
| # Save plot directly using mplfinance | |
| plot_path = f'{ticker}_candlestick_chart.png' | |
| mpf.plot( | |
| df_mpl, | |
| type='candle', | |
| volume=True, | |
| title=f'{ticker} Stock Price - Candlestick Chart', | |
| style=style, | |
| savefig=plot_path | |
| ) | |
| # Generate a beginner-friendly explanation | |
| explanation = f""" | |
| 🕯️ Candlestick Chart Explained for {ticker}: | |
| What is a Candlestick? | |
| - Each 'candle' represents one day of trading | |
| - Shows four key price points: Open, Close, High, Low | |
| How to Read the Candles: | |
| 🟢 Green Candle = Price Went Up | |
| - Bottom of candle = Opening Price | |
| - Top of candle = Closing Price | |
| 🔴 Red Candle = Price Went Down | |
| - Top of candle = Opening Price | |
| - Bottom of candle = Closing Price | |
| Additional Insights: | |
| - Candle 'Wicks' show the highest and lowest prices of the day | |
| - Volume chart below shows how many shares were traded | |
| Recent Performance: | |
| - Latest Close Price: ${df['Close'][-1]:.2f} | |
| - Price Change: ${df['Close'][-1] - df['Close'][-2]:.2f} | |
| - Percentage Change: {((df['Close'][-1] / df['Close'][-2] - 1) * 100):.2f}% | |
| """ | |
| return explanation, plot_path | |
| except Exception as e: | |
| return f"Error creating chart: {e}", None | |
| # Gradio Interface for Candlestick Chart | |
| import gradio as gr | |
| def candlestick_interface(ticker, period, interval): | |
| explanation, plot_path = create_beginner_friendly_candlestick_chart(ticker, period, interval) | |
| return explanation, plot_path | |
| # Create Gradio Interface | |
| iface = gr.Interface( | |
| fn=candlestick_interface, | |
| inputs=[ | |
| gr.Textbox(label="Stock Ticker (e.g., AAPL, MSFT)", value="AAPL"), | |
| gr.Textbox(label="Time Period (e.g., 6mo, 1y)", value="6mo"), | |
| gr.Textbox(label="Data Interval (e.g., 1d, 1h)", value="1d") | |
| ], | |
| outputs=[ | |
| gr.Textbox(label="Candlestick Chart Explanation"), | |
| gr.Image(label="Candlestick Chart") | |
| ], | |
| title="Candlestick Chart Explained", | |
| description="Understand stock price movements with an easy-to-read candlestick chart" | |
| ) | |
| # Launch the interface | |
| iface.launch(share=True) |