netflypsb commited on
Commit
12d8ef6
·
verified ·
1 Parent(s): 19f5e1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -61
app.py CHANGED
@@ -3,68 +3,58 @@ import yfinance as yf
3
  import pandas as pd
4
  import plotly.graph_objs as go
5
 
6
- def fetch_data(ticker, start_date, end_date):
7
- data = yf.download(ticker, start=start_date, end=end_date)
8
- return data
9
-
10
- def calculate_indicators(data, short_ema, long_ema):
11
- # Exponential Moving Averages
12
- data['EMA_Short'] = data['Close'].ewm(span=short_ema, adjust=False).mean()
13
- data['EMA_Long'] = data['Close'].ewm(span=long_ema, adjust=False).mean()
14
- return data
15
 
16
- def identify_signals(data):
17
- data['Position'] = (data['EMA_Short'] > data['EMA_Long']).astype(int)
18
- data['Signal'] = data['Position'].diff()
19
- data['Buy Signal'] = data['Signal'] == 1
20
- data['Sell Signal'] = data['Signal'] == -1
 
 
 
 
21
  return data
22
 
23
- def plot_data(data):
 
 
 
 
 
 
 
 
 
 
24
  fig = go.Figure()
25
-
26
- # Adding Close price trace
27
- fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='blue', width=2)))
28
-
29
- # Adding EMAs
30
- fig.add_trace(go.Scatter(x=data.index, y=data['EMA_Short'], name=f'EMA {short_ema}', line=dict(color='green', width=1.5)))
31
- fig.add_trace(go.Scatter(x=data.index, y=data['EMA_Long'], name=f'EMA {long_ema}', line=dict(color='red', width=1.5)))
32
-
33
- # Adding Buy and Sell signals
34
- buys = data[data['Buy Signal']]
35
- sells = data[data['Sell Signal']]
36
- fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', name='Buy Signal', marker=dict(symbol='triangle-up', size=12, color='green')))
37
- fig.add_trace(go.Scatter(x=sells.index, y=sells['Close'], mode='markers', name='Sell Signal', marker=dict(symbol='triangle-down', size=12, color='red')))
38
-
39
- # Layout updates
40
- fig.update_layout(title='2 EMA Crossover Trading Strategy Visualization', xaxis_title='Date', yaxis_title='Price', template='plotly_dark')
41
- fig.update_xaxes(rangeslider_visible=True)
42
-
43
- return fig
44
-
45
- def main():
46
- st.sidebar.title("Settings")
47
- ticker = st.sidebar.text_input("Enter the ticker symbol, e.g., 'AAPL'", 'AAPL')
48
- start_date = st.sidebar.date_input("Select the start date")
49
- end_date = st.sidebar.date_input("Select the end date")
50
- short_ema = st.sidebar.number_input("Enter the shorter EMA period", min_value=1, value=12)
51
- long_ema = st.sidebar.number_input("Enter the longer EMA period", min_value=1, value=26)
52
-
53
- st.title("2 EMA Crossover Trading Strategy")
54
- st.markdown("""
55
- ## Description
56
- This application visualizes a 2 Exponential Moving Average (EMA) Crossover Strategy on historical stock data.
57
- The strategy involves two EMAs: a shorter period EMA and a longer period EMA.
58
- A **buy signal** is generated when the shorter EMA crosses above the longer EMA, and a **sell signal** is generated when the shorter EMA crosses below the longer EMA.
59
- """)
60
-
61
- if st.sidebar.button("Analyze"):
62
- data = fetch_data(ticker, start_date, end_date)
63
- data = calculate_indicators(data, short_ema, long_ema)
64
- data = identify_signals(data)
65
- fig = plot_data(data)
66
- st.plotly_chart(fig, use_container_width=True)
67
-
68
- if __name__ == "__main__":
69
- main()
70
-
 
3
  import pandas as pd
4
  import plotly.graph_objs as go
5
 
6
+ # Function to calculate EMA
7
+ def calculate_ema(data, span):
8
+ return data.ewm(span=span, adjust=False).mean()
 
 
 
 
 
 
9
 
10
+ # Function to get data and calculate EMAs
11
+ def get_data_with_ema(ticker, start_date, end_date, short_ema, long_ema):
12
+ data = yf.download(ticker, start=start_date, end=end_date)
13
+ data['Short_EMA'] = calculate_ema(data['Close'], short_ema)
14
+ data['Long_EMA'] = calculate_ema(data['Close'], long_ema)
15
+ data['Signal'] = 0
16
+ data['Signal'][short_ema:] = \
17
+ (data['Short_EMA'][short_ema:] > data['Long_EMA'][short_ema:]).astype(int)
18
+ data['Position'] = data['Signal'].diff()
19
  return data
20
 
21
+ # Streamlit interface
22
+ st.sidebar.title("2 EMA Crossover Trading Strategy")
23
+ ticker = st.sidebar.text_input("Enter the ticker symbol", "AAPL")
24
+ short_ema = st.sidebar.number_input("Short EMA length", min_value=5, max_value=50, value=20)
25
+ long_ema = st.sidebar.number_input("Long EMA length", min_value=10, max_value=200, value=50)
26
+ start_date = st.sidebar.date_input("Start Date", pd.to_datetime("2020-01-01"))
27
+ end_date = st.sidebar.date_input("End Date", pd.to_datetime("today"))
28
+
29
+ if st.sidebar.button("Analyze"):
30
+ data = get_data_with_ema(ticker, start_date, end_date, short_ema, long_ema)
31
+ # Plotting
32
  fig = go.Figure()
33
+ fig.add_trace(go.Candlestick(x=data.index,
34
+ open=data['Open'], high=data['High'],
35
+ low=data['Low'], close=data['Close'], name='Candlestick'))
36
+ fig.add_trace(go.Scatter(x=data.index, y=data['Short_EMA'], line=dict(color='blue', width=1.5), name='Short EMA'))
37
+ fig.add_trace(go.Scatter(x=data.index, y=data['Long_EMA'], line=dict(color='red', width=1.5), name='Long EMA'))
38
+ # Buy signals
39
+ buys = data[data['Position'] == 1]
40
+ sells = data[data['Position'] == -1]
41
+ fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', marker=dict(color='green', size=10), name='Buy Signal'))
42
+ fig.add_trace(go.Scatter(x=sells.index, y=sells['Close'], mode='markers', marker=dict(color='red', size=10), name='Sell Signal'))
43
+
44
+ fig.update_layout(title=f"2 EMA Crossover Trading Analysis for {ticker}",
45
+ xaxis_title="Date",
46
+ yaxis_title="Price",
47
+ xaxis_rangeslider_visible=False)
48
+ fig.update_xaxes(type='category')
49
+ st.plotly_chart(fig, use_container_width=True)
50
+
51
+ st.title("2 EMA Crossover Trading Strategy App")
52
+ st.markdown("""
53
+ This app visualizes the 2 EMA Crossover Trading Strategy for any stock ticker available on Yahoo Finance.
54
+ Select the ticker symbol, EMA lengths, start and end date for the analysis in the sidebar and click analyze to see the results.
55
+ **Instructions:**
56
+ 1. Enter the stock ticker symbol (e.g., AAPL, GOOGL).
57
+ 2. Choose the lengths for the Short and Long EMAs.
58
+ 3. Set the desired time period for analysis.
59
+ 4. Click the 'Analyze' button to view the interactive chart with buy and sell signals.
60
+ """)