netflypsb commited on
Commit
fbe5046
·
verified ·
1 Parent(s): 7181b7f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -59
app.py CHANGED
@@ -1,83 +1,69 @@
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
- import plotly.graph_objects 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, window_short, window_long):
11
- data['High Short'] = data['High'].rolling(window=window_short).max()
12
- data['Low Short'] = data['Low'].rolling(window=window_short).min()
 
 
 
 
13
  return data
14
 
15
  def identify_signals(data):
16
- data['Buy Signal'] = (data['Close'] > data['High Short'].shift(1))
17
- data['Sell Signal'] = (data['Close'] < data['Low Short'].shift(1))
18
- return data
19
-
20
- def collect_signals(data):
21
- signals = pd.DataFrame()
22
- signals['Date'] = data.index
23
- signals['Price'] = data['Close'] # This will now display the price at which the signal was triggered
24
-
25
- # Initialize all signals to None and update based on the data's indices
26
- signals['Signal'] = None
27
- buy_indices = data[data['Buy Signal']].index
28
- sell_indices = data[data['Sell Signal']].index
29
-
30
- signals.loc[signals['Date'].isin(buy_indices), 'Signal'] = 'Buy'
31
- signals.loc[signals['Date'].isin(sell_indices), 'Signal'] = 'Sell'
32
-
33
- signals = signals.dropna(subset=['Signal']) # Ensure that only rows with signals are kept
34
-
35
- return signals
36
 
37
  def plot_data(data):
38
- fig = go.Figure()
39
- fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='blue')))
40
- buys = data[data['Buy Signal']]
41
- sells = data[data['Sell Signal']]
42
- fig.add_trace(go.Scatter(x=buys.index, y=buys['Close'], mode='markers', name='Buy Signal', marker_symbol='triangle-up', marker_color='green', marker_size=10))
43
- fig.add_trace(go.Scatter(x=sells.index, y=sells['Close'], mode='markers', name='Sell Signal', marker_symbol='triangle-down', marker_color='red', marker_size=10))
44
- fig.update_layout(title='Stock Price and Trading Signals', xaxis_title='Date', yaxis_title='Price', template='plotly_dark')
45
- return fig
 
 
 
 
 
 
46
 
47
  def main():
48
  st.title("Turtle Trading Strategy Visualization")
49
-
50
- st.markdown("""
51
- ## Description
52
- This app visualizes the Turtle Trading Strategy, a well-known systematic trading method that follows trends to decide on buying and selling positions based on historical price breakouts. Users can test different short and long window sizes to see how the strategy performs with different settings.
53
-
54
- ## How to Use
55
- 1. **Enter the Ticker Symbol:** Input the stock symbol you want to analyze (e.g., 'AAPL', 'GOOGL').
56
- 2. **Select Date Range:** Choose the start and end dates for the data you wish to analyze.
57
- 3. **Set Window Sizes:** Adjust the window sizes for the short and long term indicators.
58
- 4. **Analyze:** Press the analyze button to see the trading signals and performance charts.
59
- 5. **Review the Outputs:** The chart and the signals table provide visual and data-driven insights respectively.
60
- """)
61
-
62
- with st.sidebar:
63
- ticker = st.text_input("Enter the ticker symbol, e.g., 'AAPL'")
64
- start_date = st.date_input("Select the start date")
65
- end_date = st.date_input("Select the end date")
66
- window_short = st.number_input("Short term window", min_value=5, max_value=60, value=20)
67
- window_long = st.number_input("Long term window", min_value=5, max_value=120, value=55)
68
-
69
  if st.button("Analyze"):
70
  data = fetch_data(ticker, start_date, end_date)
71
- if not data.empty:
72
- data = calculate_indicators(data, window_short, window_long)
73
- data = identify_signals(data)
74
- signals = collect_signals(data)
75
- fig = plot_data(data)
76
- st.plotly_chart(fig, use_container_width=True)
77
  st.write("Trading Signals:")
78
  st.dataframe(signals)
79
  else:
80
- st.error("No data found for the selected ticker and date range.")
81
 
82
  if __name__ == "__main__":
83
  main()
 
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
+ import matplotlib.pyplot as plt
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):
11
+ # High and low for the breakout signals
12
+ data['20 Day High'] = data['High'].rolling(window=20).max()
13
+ data['20 Day Low'] = data['Low'].rolling(window=20).min()
14
+ data['55 Day High'] = data['High'].rolling(window=55).max()
15
+ data['55 Day Low'] = data['Low'].rolling(window=55).min()
16
+
17
  return data
18
 
19
  def identify_signals(data):
20
+ # Buy signals are generated when the price exceeds the 20-day high
21
+ data['Buy Signal'] = (data['Close'] > data['20 Day High'].shift(1))
22
+ # Sell signals are generated when the price drops below the 20-day low
23
+ data['Sell Signal'] = (data['Close'] < data['20 Day Low'].shift(1))
24
+
25
+ signals = []
26
+ for index, row in data.iterrows():
27
+ if row['Buy Signal']:
28
+ signals.append({'Date': index, 'Signal Type': 'Buy', 'Price': row['Close']})
29
+ if row['Sell Signal']:
30
+ signals.append({'Date': index, 'Signal Type': 'Sell', 'Price': row['Close']})
31
+
32
+ return data, pd.DataFrame(signals)
 
 
 
 
 
 
 
33
 
34
  def plot_data(data):
35
+ plt.figure(figsize=(12, 6))
36
+ plt.plot(data['Close'], label='Close Price')
37
+
38
+ buy_signals = data[data['Buy Signal']]
39
+ sell_signals = data[data['Sell Signal']]
40
+ plt.scatter(buy_signals.index, buy_signals['Close'], marker='^', color='green', s=100, label='Buy Signal')
41
+ plt.scatter(sell_signals.index, sell_signals['Close'], marker='v', color='red', s=100, label='Sell Signal')
42
+
43
+ plt.title('Stock Price and Turtle Trading Signals')
44
+ plt.xlabel('Date')
45
+ plt.ylabel('Price')
46
+ plt.legend()
47
+ plt.grid(True)
48
+ plt.show()
49
 
50
  def main():
51
  st.title("Turtle Trading Strategy Visualization")
52
+ ticker = st.text_input("Enter the ticker symbol, e.g., 'AAPL'")
53
+ start_date = st.date_input("Select the start date")
54
+ end_date = st.date_input("Select the end date")
55
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  if st.button("Analyze"):
57
  data = fetch_data(ticker, start_date, end_date)
58
+ data = calculate_indicators(data)
59
+ data, signals = identify_signals(data)
60
+ plot_data(data)
61
+ st.pyplot(plt)
62
+ if not signals.empty:
 
63
  st.write("Trading Signals:")
64
  st.dataframe(signals)
65
  else:
66
+ st.write("No trading signals found for the selected period.")
67
 
68
  if __name__ == "__main__":
69
  main()