Method314's picture
Create app.py
9175035 verified
raw
history blame
4.1 kB
import gradio as gr
import yfinance as yf
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime
def download_stock_data(ticker, start_date, end_date):
stock = yf.Ticker(ticker)
df = stock.history(start=start_date, end=end_date)
return df
def plot_interactive_logarithmic_stock_chart(ticker, start_date, end_date):
try:
stock = yf.Ticker(ticker)
data = stock.history(start=start_date, end=end_date)
if data.empty:
return "No data available for the specified date range."
x = (data.index - data.index[0]).days
y = np.log(data['Close'])
slope, intercept = np.polyfit(x, y, 1)
future_days = 365 * 10
all_days = np.arange(len(x) + future_days)
log_trend = np.exp(intercept + slope * all_days)
inner_upper_band = log_trend * 2
inner_lower_band = log_trend / 2
outer_upper_band = log_trend * 4
outer_lower_band = log_trend / 4
extended_dates = pd.date_range(start=data.index[0], periods=len(all_days), freq='D')
fig = go.Figure()
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price', line=dict(color='blue')))
fig.add_trace(go.Scatter(x=extended_dates, y=log_trend, mode='lines', name='Log Trend', line=dict(color='red')))
fig.add_trace(go.Scatter(x=extended_dates, y=inner_upper_band, mode='lines', name='Inner Upper Band', line=dict(color='green')))
fig.add_trace(go.Scatter(x=extended_dates, y=inner_lower_band, mode='lines', name='Inner Lower Band', line=dict(color='green')))
fig.add_trace(go.Scatter(x=extended_dates, y=outer_upper_band, mode='lines', name='Outer Upper Band', line=dict(color='orange')))
fig.add_trace(go.Scatter(x=extended_dates, y=outer_lower_band, mode='lines', name='Outer Lower Band', line=dict(color='orange')))
fig.update_layout(
title=f'{ticker} Stock Price (Logarithmic Scale) with Extended Trend Lines and Outer Bands',
xaxis_title='Date',
yaxis_title='Price (Log Scale)',
yaxis_type="log",
height=800,
legend=dict(x=0.01, y=0.99, bgcolor='rgba(255, 255, 255, 0.8)'),
hovermode='x unified'
)
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
return fig
except Exception as e:
return f"An error occurred: {str(e)}"
# Get the current date
current_date = datetime.now().strftime("%Y-%m-%d")
# Custom CSS to make charts full-width and larger
custom_css = """
.container {max-width: 100% !important; padding: 0 !important;}
.plot-container {height: 800px !important; width: 100% !important;}
.react-plotly-container {height: 100% !important; width: 100% !important;}
"""
# Create Gradio interface
with gr.Blocks(css=custom_css, title="Alan's Logarithmic Charting Tool") as iface:
gr.Markdown("# Alan's Logarithmic Charting Tool")
gr.Markdown("Enter a stock ticker and date range to generate a logarithmic chart.")
with gr.Row():
ticker = gr.Textbox(label="Stock Ticker", value="MSFT")
start_date = gr.Textbox(label="Start Date", value="2015-01-01")
end_date = gr.Textbox(label="End Date", value=current_date)
submit_button = gr.Button("Generate Chart")
with gr.Row():
log_plot = gr.Plot(label="Logarithmic Stock Chart")
submit_button.click(
plot_interactive_logarithmic_stock_chart,
inputs=[ticker, start_date, end_date],
outputs=[log_plot]
)
# Launch the app
iface.launch()