File size: 4,276 Bytes
19e5d93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8c9279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19e5d93
 
 
 
 
 
 
 
 
2d63453
19e5d93
 
5936d70
19e5d93
 
 
2d63453
19e5d93
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
import gradio as gr
import os

def fetch_data(ticker, period):
    data = yf.download(ticker, period=period)
    return data

def compute_rsi(data, window=14):
    delta = data['Close'].diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()

    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

def compute_macd(data, slow=26, fast=12, signal=9):
    exp1 = data['Close'].ewm(span=fast, adjust=False).mean()
    exp2 = data['Close'].ewm(span=slow, adjust=False).mean()
    macd = exp1 - exp2
    signal_line = macd.ewm(span=signal, adjust=False).mean()
    histogram = macd - signal_line
    return macd, signal_line, histogram

def buy_sell_signals(data, rsi, macd, signal_line):
    buy_signals = []
    sell_signals = []
    for i in range(2, len(data)):
        # RSI Buy Signal (RSI < 30)
        if rsi[i-1] < 30 and rsi[i] >= 30:
            buy_signals.append(data['Close'][i])
            sell_signals.append(float('nan'))
        # RSI Sell Signal (RSI > 70)
        elif rsi[i-1] > 70 and rsi[i] <= 70:
            sell_signals.append(data['Close'][i])
            buy_signals.append(float('nan'))
        # MACD Buy Signal (MACD crosses above Signal)
        elif macd[i-1] < signal_line[i-1] and macd[i] >= signal_line[i]:
            buy_signals.append(data['Close'][i])
            sell_signals.append(float('nan'))
        # MACD Sell Signal (MACD crosses below Signal)
        elif macd[i-1] > signal_line[i-1] and macd[i] <= signal_line[i]:
            sell_signals.append(data['Close'][i])
            buy_signals.append(float('nan'))
        else:
            buy_signals.append(float('nan'))
            sell_signals.append(float('nan'))
    return buy_signals, sell_signals


def plot_with_gr_plot(data, buy_signals_rsi, sell_signals_rsi, buy_signals_macd, sell_signals_macd):
    fig = make_subplots(rows=2, cols=1, shared_xaxes=True)
    
    # Add the candlestick chart
    fig.add_trace(go.Candlestick(x=data.index, open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name='Market Data'), row=1, col=1)
    
    fig.add_trace(go.Scatter(x=list(buy_signals_rsi.keys()), y=list(buy_signals_rsi.values()), mode='markers', marker_symbol='triangle-up', marker_color='green', name='Buy Signal RSI', text=["RSI Buy"]*len(buy_signals_rsi), hoverinfo='text+y'), row=1, col=1)
    fig.add_trace(go.Scatter(x=list(sell_signals_rsi.keys()), y=list(sell_signals_rsi.values()), mode='markers', marker_symbol='triangle-down', marker_color='red', name='Sell Signal RSI', text=["RSI Sell"]*len(sell_signals_rsi), hoverinfo='text+y'), row=1, col=1)
    
    fig.add_trace(go.Scatter(x=list(buy_signals_macd.keys()), y=list(buy_signals_macd.values()), mode='markers', marker=dict(symbol='triangle-up', color='blue', size=10), name='Buy Signal MACD', text=["MACD Buy"]*len(buy_signals_macd), hoverinfo='text+y'), row=1, col=1)
    fig.add_trace(go.Scatter(x=list(sell_signals_macd.keys()), y=list(sell_signals_macd.values()), mode='markers', marker=dict(symbol='triangle-down', color='purple', size=10), name='Sell Signal MACD', text=["MACD Sell"]*len(sell_signals_macd), hoverinfo='text+y'), row=1, col=1)
    
    # Update layout if needed
    fig.update_layout(title='Stock Analysis with RSI and MACD Signals')
    
    return fig

def main_interface(ticker, period):
    data = fetch_data(ticker, period)
    rsi = compute_rsi(data)
    macd, signal_line, _ = compute_macd(data)
    buy_signals, sell_signals = buy_sell_signals(data, rsi, macd, signal_line)
    plot_filename = plot_data(data, buy_signals, sell_signals)
    return plot_filename

# Step 7: Set Up Gradio Interface with corrected type parameter
iface = gr.Interface(fn=main_interface,
                     inputs=[gr.Textbox(label="Asset Ticker"), gr.Textbox(label="Period: (e.g., 1y, 2y, 5y)")],
                     outputs=gr.Plot(),  # Corrected type parameter
                     title="Stock Analysis Tool",
                     description="Enter a stock ticker and period to analyze buy/sell signals based on RSI and MACD.")


iface.launch()