BreakoutTrading / app.py
netflypsb's picture
Create app.py
df1eb78 verified
raw
history blame
3.54 kB
import streamlit as st
import yfinance as yf
import pandas as pd
import pandas_ta as ta
import matplotlib.pyplot as plt
# Caching the stock data fetch function to improve performance
@st.cache(allow_output_mutation=True)
def fetch_stock_data(ticker, period, interval):
try:
data = yf.download(ticker, period=period, interval=interval)
return data
except Exception as e:
st.error(f"Failed to fetch data: {e}")
return pd.DataFrame() # Return an empty DataFrame on failure
# Streamlit interface setup
st.title("Enhanced Breakout Trading Analysis Tool with Multiple Logic")
# User inputs
ticker = st.text_input("Enter Stock Ticker:", value="AAPL")
timeframe_options = ["1d", "1wk", "1mo"]
timeframe = st.selectbox("Select Time Frame:", options=timeframe_options, index=0)
period = st.selectbox("Select Period:", options=["6mo", "1y", "2y"], index=1)
analyze_button = st.button("Analyze Breakout Points")
if analyze_button:
stock_data = fetch_stock_data(ticker, period, timeframe)
if stock_data.empty:
st.error("No data found for the specified ticker. Please try another ticker.")
else:
# Calculating technical indicators
stock_data['SMA9'] = ta.sma(stock_data['Close'], length=9)
stock_data['SMA20'] = ta.sma(stock_data['Close'], length=20)
stock_data['SMA50'] = ta.sma(stock_data['Close'], length=50)
stock_data['SMA200'] = ta.sma(stock_data['Close'], length=200)
stock_data.dropna(subset=['SMA9', 'SMA20', 'SMA50', 'SMA200'], inplace=True)
if stock_data.empty:
st.error("Insufficient data for the selected period to compute all moving averages. Try a longer period.")
else:
# Identifying breakout points for all three logics after ensuring data validity
crossover_points_logic1 = stock_data[(stock_data['SMA9'] > stock_data['SMA20']) & (stock_data['SMA9'].shift(1) < stock_data['SMA20'].shift(1))]
crossover_points_logic2 = stock_data[(stock_data['SMA20'] > stock_data['SMA50']) & (stock_data['SMA20'].shift(1) < stock_data['SMA50'].shift(1))]
crossover_points_original = stock_data[(stock_data['SMA50'] > stock_data['SMA200']) & (stock_data['SMA50'].shift(1) < stock_data['SMA200'].shift(1))]
# Plotting
fig, ax = plt.subplots(2, 1, figsize=(10, 12), sharex=True)
# Price, SMAs, and breakout points for all logics
ax[0].plot(stock_data['Close'], label='Close Price', color='skyblue')
ax[0].plot(stock_data['SMA9'], label='9-Day SMA', color='orange')
ax[0].plot(stock_data['SMA20'], label='20-Day SMA', color='purple')
ax[0].plot(stock_data['SMA50'], label='50-Day SMA', color='green')
ax[0].plot(stock_data['SMA200'], label='200-Day SMA', color='red')
ax[0].scatter(crossover_points_logic1.index, crossover_points_logic1['Close'], color='gold', label='Logic 1 Breakouts', zorder=5)
ax[0].scatter(crossover_points_logic2.index, crossover_points_logic2['Close'], color='violet', label='Logic 2 Breakouts', zorder=5)
ax[0].scatter(crossover_points_original.index, crossover_points_original['Close'], color='magenta', label='Original Logic Breakouts', zorder=5)
ax[0].set_title(f"{ticker} Breakout Points Analysis")
ax[0].legend()
# Additional technical indicators (if necessary) could be plotted here
# Display plot in Streamlit
st.pyplot(fig)