|
import streamlit as st |
|
import yfinance as yf |
|
import pandas as pd |
|
import plotly.graph_objs as go |
|
|
|
|
|
def calculate_ema(data, span): |
|
return data.ewm(span=span, adjust=False).mean() |
|
|
|
|
|
def get_data_with_ema(ticker, start_date, end_date, short_ema, long_ema): |
|
data = yf.download(ticker, start=start_date, end=end_date) |
|
data['Short_EMA'] = calculate_ema(data['Close'], short_ema) |
|
data['Long_EMA'] = calculate_ema(data['Close'], long_ema) |
|
data['Signal'] = 0 |
|
data['Signal'][short_ema:] = \ |
|
(data['Short_EMA'][short_ema:] > data['Long_EMA'][short_ema:]).astype(int) |
|
data['Position'] = data['Signal'].diff() |
|
return data |
|
|
|
|
|
st.sidebar.title("2 EMA Crossover Trading Strategy") |
|
ticker = st.sidebar.text_input("Enter the ticker symbol", "AAPL") |
|
short_ema = st.sidebar.number_input("Short EMA length", min_value=5, max_value=50, value=20) |
|
long_ema = st.sidebar.number_input("Long EMA length", min_value=10, max_value=200, value=50) |
|
start_date = st.sidebar.date_input("Start Date", pd.to_datetime("2020-01-01")) |
|
end_date = st.sidebar.date_input("End Date", pd.to_datetime("today")) |
|
|
|
if st.sidebar.button("Analyze"): |
|
data = get_data_with_ema(ticker, start_date, end_date, short_ema, long_ema) |
|
|
|
fig = go.Figure() |
|
fig.add_trace(go.Candlestick(x=data.index, |
|
open=data['Open'], high=data['High'], |
|
low=data['Low'], close=data['Close'], name='Candlestick')) |
|
fig.add_trace(go.Scatter(x=data.index, y=data['Short_EMA'], line=dict(color='blue', width=1.5), name='Short EMA')) |
|
fig.add_trace(go.Scatter(x=data.index, y=data['Long_EMA'], line=dict(color='red', width=1.5), name='Long EMA')) |
|
|
|
buys = data[data['Position'] == 1] |
|
sells = data[data['Position'] == -1] |
|
fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', marker=dict(color='green', size=10), name='Buy Signal')) |
|
fig.add_trace(go.Scatter(x=sells.index, y=sells['Close'], mode='markers', marker=dict(color='red', size=10), name='Sell Signal')) |
|
|
|
fig.update_layout(title=f"2 EMA Crossover Trading Analysis for {ticker}", |
|
xaxis_title="Date", |
|
yaxis_title="Price", |
|
xaxis_rangeslider_visible=False) |
|
fig.update_xaxes(type='category') |
|
st.plotly_chart(fig, use_container_width=True) |
|
|
|
st.title("2 EMA Crossover Trading Strategy App") |
|
st.markdown(""" |
|
This app visualizes the 2 EMA Crossover Trading Strategy for any stock ticker available on Yahoo Finance. |
|
Select the ticker symbol, EMA lengths, start and end date for the analysis in the sidebar and click analyze to see the results. |
|
**Instructions:** |
|
1. Enter the stock ticker symbol (e.g., AAPL, GOOGL). |
|
2. Choose the lengths for the Short and Long EMAs. |
|
3. Set the desired time period for analysis. |
|
4. Click the 'Analyze' button to view the interactive chart with buy and sell signals. |
|
""") |
|
|