netflypsb commited on
Commit
6344d72
·
verified ·
1 Parent(s): 1c0d933

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -48
app.py CHANGED
@@ -1,69 +1,66 @@
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()
 
1
  import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
+ import plotly.graph_objects as go
5
 
6
+ # Function to fetch data from Yahoo Finance
7
  def fetch_data(ticker, start_date, end_date):
8
  data = yf.download(ticker, start=start_date, end=end_date)
9
  return data
10
 
11
+ # Calculate indicators based on user-defined window sizes
12
+ def calculate_indicators(data, window_short, window_long):
13
+ data['High Short'] = data['High'].rolling(window=window_short).max()
14
+ data['Low Short'] = data['Low'].rolling(window=window_short).min()
15
+ data['High Long'] = data['High'].rolling(window=window_long).max()
16
+ data['Low Long'] = data['Low'].rolling(window=window_long).min()
 
17
  return data
18
 
19
+ # Identify buy and sell signals based on breakout strategy
20
  def identify_signals(data):
21
+ data['Buy Signal'] = (data['Close'] > data['High Short'].shift(1))
22
+ data['Sell Signal'] = (data['Close'] < data['Low Short'].shift(1))
23
+ return data
 
 
 
 
 
 
 
 
 
 
24
 
25
+ # Plotting function using Plotly for interactive charts
26
  def plot_data(data):
27
+ fig = go.Figure()
28
+ # Add traces for Close price, High, and Low bands
29
+ fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price', line=dict(color='blue')))
30
+ fig.add_trace(go.Scatter(x=data.index, y=data['High Short'], name='High Short', line=dict(dash='dot')))
31
+ fig.add_trace(go.Scatter(x=data.index, y=data['Low Short'], name='Low Short', line=dict(dash='dot')))
32
+
33
+ # Add buy and sell signal markers
34
+ buys = data[data['Buy Signal']]
35
+ sells = data[data['Sell Signal']]
36
+ 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))
37
+ 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))
38
+
39
+ # Update layout for better visualization
40
+ fig.update_layout(title='Stock Price and Trading Signals', xaxis_title='Date', yaxis_title='Price', template='plotly_dark')
41
+ return fig
42
 
43
+ # Main application function
44
  def main():
45
+ st.title("Enhanced Turtle Trading Strategy Visualization")
46
+
47
+ # Sidebar for user inputs
48
+ with st.sidebar:
49
+ ticker = st.text_input("Enter the ticker symbol, e.g., 'AAPL'")
50
+ start_date = st.date_input("Select the start date")
51
+ end_date = st.date_input("Select the end date")
52
+ window_short = st.number_input("Short term window", min_value=5, max_value=60, value=20)
53
+ window_long = st.number_input("Long term window", min_value=5, max_value=120, value=55)
54
+
55
  if st.button("Analyze"):
56
  data = fetch_data(ticker, start_date, end_date)
57
+ if not data.empty:
58
+ data = calculate_indicators(data, window_short, window_long)
59
+ data = identify_signals(data)
60
+ fig = plot_data(data)
61
+ st.plotly_chart(fig, use_container_width=True)
 
 
62
  else:
63
+ st.error("No data found for the selected ticker and date range.")
64
 
65
  if __name__ == "__main__":
66
  main()