Spaces:
Sleeping
Sleeping
import gradio as gr | |
import pandas as pd | |
import pandas_ta as ta | |
import plotly.graph_objects as go | |
from plotly.subplots import make_subplots | |
# Sample OHLCV data (replace this with actual data) | |
data = pd.read_csv('data/brent_futures.csv') | |
data['Date'] = pd.to_datetime(data['Date']) | |
data.set_index('Date', inplace=True) | |
data.sort_index(inplace=True) | |
def plot_chart(ma_length, draw_mode): | |
# Calculate Moving Average and Bollinger Bands | |
data['MA'] = ta.sma(data['Close'], length=ma_length) | |
bbands = ta.bbands(data['Close'], length=20) | |
data['BB_upper'], data['BB_middle'], data['BB_lower'] = bbands.iloc[:, 2], bbands.iloc[:, 1], bbands.iloc[:, 0] | |
# Create a subplot figure with 2 rows: OHLC and Volume | |
fig = make_subplots( | |
rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05, | |
row_heights=[0.7, 0.3], subplot_titles=('OHLC with Moving Average and Bollinger Bands', 'Volume') | |
) | |
# Plot OHLC candlestick | |
fig.add_trace(go.Candlestick( | |
x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name="OHLC"), row=1, col=1) | |
# Add Moving Average and Bollinger Bands | |
fig.add_trace(go.Scatter(x=data.index, y=data['MA'], mode='lines', name=f'MA {ma_length}', line=dict(color='blue')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['BB_upper'], mode='lines', name='BB Upper', line=dict(color='purple')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['BB_middle'], mode='lines', name='BB Middle', line=dict(color='gray')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['BB_lower'], mode='lines', name='BB Lower', line=dict(color='purple')), row=1, col=1) | |
# Plot Volume | |
fig.add_trace(go.Bar(x=data.index, y=data['Volume'], name='Volume', marker=dict(color='green')), row=2, col=1) | |
# Customize layout | |
fig.update_layout( | |
height=700, showlegend=True, | |
legend=dict(orientation='h', yanchor='bottom', y=-0.15, xanchor='center', x=0.5), | |
xaxis_rangeslider_visible=False, dragmode='drawline' if draw_mode else 'zoom' | |
) | |
# Enable dynamic y-axis range | |
fig.update_yaxes(autorange=True) | |
return fig | |
# Gradio UI | |
def update_chart(ma_length, drawline_button): | |
draw_mode = True if drawline_button == 'Draw Line' else False | |
return plot_chart(ma_length, draw_mode) | |
ma_length_input = gr.Number(value=10, label="Moving Average Length", interactive=True, step=1, minimum=1) | |
drawline_button = gr.Button("Draw Line") | |
chart_output = gr.Plot() | |
gr.Interface( | |
fn=update_chart, | |
inputs=[ma_length_input, drawline_button], | |
outputs=[chart_output], | |
title="Interactive Technical Analysis Dashboard", | |
description="Choose moving average length and toggle line drawing mode." | |
).launch() |