File size: 2,501 Bytes
cbd6be0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
import plotly.graph_objects as go

# Initialize the Streamlit app
st.title('Momentum Reversal Trading Strategy Analysis')

# User input for asset ticker, start date, and end date
ticker = st.text_input('Enter the ticker symbol of the asset:', 'AAPL')
start_date = st.date_input('Start Date')
end_date = st.date_input('End Date')
analyze_button = st.button('Analyze')

if analyze_button:
    # Fetch historical data from Yahoo Finance
    data = yf.download(ticker, start=start_date, end=end_date)

    # Calculate RSI
    delta = data['Adj Close'].diff()
    gain = (delta.where(delta > 0, 0)).fillna(0)
    loss = (-delta.where(delta < 0, 0)).fillna(0)
    avg_gain = gain.rolling(window=14, min_periods=14).mean()
    avg_loss = loss.rolling(window=14, min_periods=14).mean()
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))

    # Calculate MACD
    exp1 = data['Adj Close'].ewm(span=12, adjust=False).mean()
    exp2 = data['Adj Close'].ewm(span=26, adjust=False).mean()
    macd = exp1 - exp2
    signal = macd.ewm(span=9, adjust=False).mean()

    # Identify buy and sell signals
    buy_signals = (macd > signal) & (macd.shift(1) <= signal.shift(1))
    sell_signals = (macd < signal) & (macd.shift(1) >= signal.shift(1))
    data['Buy Signal'] = buy_signals
    data['Sell Signal'] = sell_signals

    # Plotting
    fig = go.Figure()
    fig.add_trace(go.Candlestick(x=data.index,
                                 open=data['Open'],
                                 high=data['High'],
                                 low=data['Low'],
                                 close=data['Close'], name='Market data'))
    fig.add_trace(go.Scatter(x=data.index, y=rsi, name='RSI'))
    fig.add_trace(go.Scatter(x=data.index, y=macd, name='MACD', line=dict(color='blue')))
    fig.add_trace(go.Scatter(x=data.index, y=signal, name='Signal Line', line=dict(color='orange')))
    fig.update_layout(title='Trading Signals', xaxis_title='Date', yaxis_title='Price')
    st.plotly_chart(fig)

    # Display Buy and Sell Signals in a table
    signals = pd.DataFrame(index=data.index)
    signals['Price'] = data['Adj Close']
    signals['Buy'] = data['Buy Signal']
    signals['Sell'] = data['Sell Signal']
    signals_filtered = signals[(signals['Buy'] | signals['Sell'])]
    st.table(signals_filtered)

# Streamlit app will run when this script is called