turtle_trading / app.py
netflypsb's picture
Update app.py
fbe5046 verified
import streamlit as st
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
def fetch_data(ticker, start_date, end_date):
data = yf.download(ticker, start=start_date, end=end_date)
return data
def calculate_indicators(data):
# High and low for the breakout signals
data['20 Day High'] = data['High'].rolling(window=20).max()
data['20 Day Low'] = data['Low'].rolling(window=20).min()
data['55 Day High'] = data['High'].rolling(window=55).max()
data['55 Day Low'] = data['Low'].rolling(window=55).min()
return data
def identify_signals(data):
# Buy signals are generated when the price exceeds the 20-day high
data['Buy Signal'] = (data['Close'] > data['20 Day High'].shift(1))
# Sell signals are generated when the price drops below the 20-day low
data['Sell Signal'] = (data['Close'] < data['20 Day Low'].shift(1))
signals = []
for index, row in data.iterrows():
if row['Buy Signal']:
signals.append({'Date': index, 'Signal Type': 'Buy', 'Price': row['Close']})
if row['Sell Signal']:
signals.append({'Date': index, 'Signal Type': 'Sell', 'Price': row['Close']})
return data, pd.DataFrame(signals)
def plot_data(data):
plt.figure(figsize=(12, 6))
plt.plot(data['Close'], label='Close Price')
buy_signals = data[data['Buy Signal']]
sell_signals = data[data['Sell Signal']]
plt.scatter(buy_signals.index, buy_signals['Close'], marker='^', color='green', s=100, label='Buy Signal')
plt.scatter(sell_signals.index, sell_signals['Close'], marker='v', color='red', s=100, label='Sell Signal')
plt.title('Stock Price and Turtle Trading Signals')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.grid(True)
plt.show()
def main():
st.title("Turtle Trading Strategy Visualization")
ticker = st.text_input("Enter the ticker symbol, e.g., 'AAPL'")
start_date = st.date_input("Select the start date")
end_date = st.date_input("Select the end date")
if st.button("Analyze"):
data = fetch_data(ticker, start_date, end_date)
data = calculate_indicators(data)
data, signals = identify_signals(data)
plot_data(data)
st.pyplot(plt)
if not signals.empty:
st.write("Trading Signals:")
st.dataframe(signals)
else:
st.write("No trading signals found for the selected period.")
if __name__ == "__main__":
main()