Spaces:
Sleeping
Sleeping
import streamlit as st | |
import yfinance as yf | |
import plotly.graph_objs as go | |
from datetime import datetime | |
# Function to load data | |
def load_data(ticker, start_date, end_date): | |
data = yf.download(ticker, start=start_date, end=end_date) | |
data.reset_index(inplace=True) | |
return data | |
# Function to identify buy and sell signals | |
def identify_signals(data): | |
# Assume bearish and bullish candles that are significantly larger than usual as signals | |
data['Signal'] = 'None' # Default no signal | |
avg_body_size = (abs(data['Open'] - data['Close'])).mean() # Average body size of the candles | |
for i in range(1, len(data)): | |
body_size = abs(data['Open'][i] - data['Close'][i]) | |
if body_size > avg_body_size * 1.5: # Threshold of 150% of average body size | |
if data['Close'][i] < data['Open'][i]: | |
data['Signal'][i] = 'Sell' # Bearish candle | |
elif data['Close'][i] > data['Open'][i]: | |
data['Signal'][i] = 'Buy' # Bullish candle | |
return data | |
# Function to plot candlestick chart with signals | |
def plot_candlestick_chart(data): | |
fig = go.Figure(data=[go.Candlestick( | |
x=data['Date'], | |
open=data['Open'], high=data['High'], | |
low=data['Low'], close=data['Close'], | |
increasing_line_color='green', decreasing_line_color='red', | |
name='Candlestick')]) | |
# Add signals to the plot | |
buys = data[data['Signal'] == 'Buy'] | |
sells = data[data['Signal'] == 'Sell'] | |
for i in buys.index: | |
fig.add_annotation(x=buys['Date'][i], y=buys['High'][i], | |
text='Buy', showarrow=True, arrowhead=1, arrowcolor='green', arrowsize=3) | |
for i in sells.index: | |
fig.add_annotation(x=sells['Date'][i], y=sells['Low'][i], | |
text='Sell', showarrow=True, arrowhead=1, arrowcolor='red', arrowsize=3) | |
fig.update_layout(title='Candlestick Chart with Buy and Sell Signals', xaxis_rangeslider_visible=False) | |
return fig | |
# Streamlit user interface | |
st.sidebar.header('User Input Features') | |
ticker = st.sidebar.text_input('Ticker', 'AAPL') | |
start_date = st.sidebar.date_input('Start Date', datetime(2020, 1, 1)) | |
end_date = st.sidebar.date_input('End Date', datetime.today()) | |
button = st.sidebar.button('Analyze') | |
st.title('Fight the Tiger Trading Strategy Visualization') | |
st.markdown(""" | |
This app analyzes and visualizes the "Fight the Tiger" trading strategy using historical stock data fetched from Yahoo Finance. | |
Enter a stock ticker and select a date range to view the candlestick chart with potential buy and sell signals based on significant candlestick formations. | |
""") | |
if button: | |
if start_date < end_date: | |
data = load_data(ticker, start_date, end_date) | |
data = identify_signals(data) # Call to identify signals | |
fig = plot_candlestick_chart(data) | |
st.plotly_chart(fig, use_container_width=True) | |
else: | |
st.error('Error: End date must be after start date.') | |