riteshcp commited on
Commit
7274f0a
·
verified ·
1 Parent(s): 4a0cae7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -26
app.py CHANGED
@@ -1,11 +1,13 @@
 
 
1
  # Import required libraries
2
  import streamlit as st
3
  import yfinance as yf
4
  from datetime import date
5
  import pandas as pd
6
- import os
7
  import matplotlib.pyplot as plt
8
- import pandas_ta as ta # Import pandas_ta for technical indicators
 
9
 
10
  # Set the title of the app
11
  st.title('Indian Stock Data Downloader and Volume Analyzer')
@@ -13,16 +15,16 @@ st.title('Indian Stock Data Downloader and Volume Analyzer')
13
  # Sidebar for user inputs
14
  st.sidebar.header('Select Stocks and Options')
15
 
16
- # Path to your new CSV file
17
- csv_file_path = 'stock_list.csv' # Update this to the path where you saved the CSV
18
 
19
  # Check if the file exists
20
  if not os.path.isfile(csv_file_path):
21
- st.error(f"The stock list file was not found at: {csv_file_path}")
22
  else:
23
  # Read the CSV file into a DataFrame
24
  stock_df = pd.read_csv(csv_file_path)
25
-
26
  # Ensure that the required columns are present
27
  required_columns = {'Symbol', 'Company Name'}
28
  if not required_columns.issubset(stock_df.columns):
@@ -30,14 +32,14 @@ else:
30
  else:
31
  # Create a dictionary mapping company names to stock symbols
32
  stock_dict = pd.Series(stock_df['Symbol'].values, index=stock_df['Company Name']).to_dict()
33
-
34
  # Multiselect widget for stock selection
35
  selected_stocks = st.sidebar.multiselect('Select Stocks:', list(stock_dict.keys()))
36
-
37
  # Date input widgets for date range selection
38
  start_date = st.sidebar.date_input('Start Date', date(2021, 1, 1))
39
  end_date = st.sidebar.date_input('End Date', date.today())
40
-
41
  # Checkbox for selecting data options
42
  st.sidebar.header('Data Options')
43
  data_options = st.sidebar.multiselect(
@@ -45,14 +47,14 @@ else:
45
  ['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'],
46
  default=['Open', 'High', 'Low', 'Close', 'Volume']
47
  )
48
-
49
  # Technical Indicators selection
50
  st.sidebar.header('Technical Indicators')
51
  indicators = st.sidebar.multiselect(
52
  'Select Technical Indicators to Calculate:',
53
  ['OBV (Amount)', 'RSI', 'MACD']
54
  )
55
-
56
  # Download button
57
  if st.sidebar.button('Download Data'):
58
  if selected_stocks:
@@ -72,20 +74,20 @@ else:
72
  stock_data = stock_data[data_options]
73
  st.write(f"**Data for {company_name} ({ticker}):**")
74
  st.dataframe(stock_data)
75
-
76
  # Reset index to get 'Date' as a column
77
  stock_data = stock_data.reset_index()
78
-
79
  # Calculate Amount (Close * Volume)
80
  stock_data['Amount'] = stock_data['Close'] * stock_data['Volume']
81
-
82
  # OBV in terms of Amount
83
  if 'OBV (Amount)' in indicators:
84
  # Calculate direction
85
  stock_data['Daily_Return'] = stock_data['Close'].pct_change()
86
  stock_data['Direction'] = stock_data['Daily_Return'].apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))
87
  stock_data['OBV_Amount'] = (stock_data['Amount'] * stock_data['Direction']).cumsum()
88
-
89
  # Plot OBV in Amount
90
  fig_obv_amount, ax = plt.subplots(figsize=(12, 4))
91
  ax.plot(stock_data['Date'], stock_data['OBV_Amount'], label='OBV (Amount)', color='orange')
@@ -94,7 +96,7 @@ else:
94
  ax.set_title(f"{company_name} OBV (Amount)")
95
  ax.legend()
96
  st.pyplot(fig_obv_amount)
97
-
98
  # RSI
99
  if 'RSI' in indicators:
100
  stock_data['RSI'] = ta.rsi(stock_data['Close'], length=14)
@@ -108,7 +110,7 @@ else:
108
  ax.axhline(30, color='blue', linestyle='--')
109
  ax.legend()
110
  st.pyplot(fig_rsi)
111
-
112
  # MACD
113
  if 'MACD' in indicators:
114
  macd = ta.macd(stock_data['Close'])
@@ -123,47 +125,47 @@ else:
123
  ax.set_title(f"{company_name} MACD")
124
  ax.legend()
125
  st.pyplot(fig_macd)
126
-
127
  # Calculate moving averages
128
  stock_data['Volume_MA_5'] = stock_data['Volume'].rolling(window=5).mean()
129
  stock_data['Volume_MA_20'] = stock_data['Volume'].rolling(window=20).mean()
130
-
131
  # Plotting price and volume
132
  fig, ax1 = plt.subplots(figsize=(12, 6))
133
-
134
  # Plot the closing price
135
  ax1.plot(stock_data['Date'], stock_data['Close'], color='blue', label='Close Price')
136
  ax1.set_xlabel('Date')
137
  ax1.set_ylabel('Close Price', color='blue')
138
  ax1.tick_params(axis='y', labelcolor='blue')
139
-
140
  # Create a second y-axis for volume
141
  ax2 = ax1.twinx()
142
  ax2.bar(stock_data['Date'], stock_data['Volume'], color='gray', alpha=0.3, label='Volume')
143
-
144
  # Plot moving averages of volume
145
  ax2.plot(stock_data['Date'], stock_data['Volume_MA_5'], color='red', label='5-Day MA')
146
  ax2.plot(stock_data['Date'], stock_data['Volume_MA_20'], color='green', label='20-Day MA')
147
  ax2.set_ylabel('Volume', color='gray')
148
  ax2.tick_params(axis='y', labelcolor='gray')
149
-
150
  # Add legends and title
151
  fig.legend(loc='upper left', bbox_to_anchor=(0.15, 0.85))
152
  plt.title(f"{company_name} Price and Volume Chart with Moving Averages")
153
  fig.tight_layout()
154
  st.pyplot(fig)
155
-
156
  # Volume analysis
157
  stock_data['Volume_Pct_Change'] = stock_data['Volume'].pct_change() * 100
158
  average_volume = stock_data['Volume'].mean()
159
  current_volume = stock_data['Volume'].iloc[-1]
160
  volume_trend = 'increasing' if current_volume > average_volume else 'decreasing'
161
-
162
  st.subheader(f"Volume Analysis for {company_name}")
163
  st.write(f"- **Average Volume:** {average_volume:,.0f}")
164
  st.write(f"- **Current Volume:** {current_volume:,.0f}")
165
  st.write(f"- **Volume is currently {volume_trend}.**")
166
-
167
  # Convert data to CSV
168
  csv = stock_data.to_csv(index=False).encode('utf-8')
169
  # Download button for CSV
 
1
+ # app.py
2
+
3
  # Import required libraries
4
  import streamlit as st
5
  import yfinance as yf
6
  from datetime import date
7
  import pandas as pd
 
8
  import matplotlib.pyplot as plt
9
+ import pandas_ta as ta # For technical indicators
10
+ import os
11
 
12
  # Set the title of the app
13
  st.title('Indian Stock Data Downloader and Volume Analyzer')
 
15
  # Sidebar for user inputs
16
  st.sidebar.header('Select Stocks and Options')
17
 
18
+ # Path to your CSV file (adjusted for HF)
19
+ csv_file_path = 'stock_list.csv' # Ensure this file is uploaded to HF
20
 
21
  # Check if the file exists
22
  if not os.path.isfile(csv_file_path):
23
+ st.error(f"The stock list file was not found. Please upload 'stock_list.csv' to your app.")
24
  else:
25
  # Read the CSV file into a DataFrame
26
  stock_df = pd.read_csv(csv_file_path)
27
+
28
  # Ensure that the required columns are present
29
  required_columns = {'Symbol', 'Company Name'}
30
  if not required_columns.issubset(stock_df.columns):
 
32
  else:
33
  # Create a dictionary mapping company names to stock symbols
34
  stock_dict = pd.Series(stock_df['Symbol'].values, index=stock_df['Company Name']).to_dict()
35
+
36
  # Multiselect widget for stock selection
37
  selected_stocks = st.sidebar.multiselect('Select Stocks:', list(stock_dict.keys()))
38
+
39
  # Date input widgets for date range selection
40
  start_date = st.sidebar.date_input('Start Date', date(2021, 1, 1))
41
  end_date = st.sidebar.date_input('End Date', date.today())
42
+
43
  # Checkbox for selecting data options
44
  st.sidebar.header('Data Options')
45
  data_options = st.sidebar.multiselect(
 
47
  ['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'],
48
  default=['Open', 'High', 'Low', 'Close', 'Volume']
49
  )
50
+
51
  # Technical Indicators selection
52
  st.sidebar.header('Technical Indicators')
53
  indicators = st.sidebar.multiselect(
54
  'Select Technical Indicators to Calculate:',
55
  ['OBV (Amount)', 'RSI', 'MACD']
56
  )
57
+
58
  # Download button
59
  if st.sidebar.button('Download Data'):
60
  if selected_stocks:
 
74
  stock_data = stock_data[data_options]
75
  st.write(f"**Data for {company_name} ({ticker}):**")
76
  st.dataframe(stock_data)
77
+
78
  # Reset index to get 'Date' as a column
79
  stock_data = stock_data.reset_index()
80
+
81
  # Calculate Amount (Close * Volume)
82
  stock_data['Amount'] = stock_data['Close'] * stock_data['Volume']
83
+
84
  # OBV in terms of Amount
85
  if 'OBV (Amount)' in indicators:
86
  # Calculate direction
87
  stock_data['Daily_Return'] = stock_data['Close'].pct_change()
88
  stock_data['Direction'] = stock_data['Daily_Return'].apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))
89
  stock_data['OBV_Amount'] = (stock_data['Amount'] * stock_data['Direction']).cumsum()
90
+
91
  # Plot OBV in Amount
92
  fig_obv_amount, ax = plt.subplots(figsize=(12, 4))
93
  ax.plot(stock_data['Date'], stock_data['OBV_Amount'], label='OBV (Amount)', color='orange')
 
96
  ax.set_title(f"{company_name} OBV (Amount)")
97
  ax.legend()
98
  st.pyplot(fig_obv_amount)
99
+
100
  # RSI
101
  if 'RSI' in indicators:
102
  stock_data['RSI'] = ta.rsi(stock_data['Close'], length=14)
 
110
  ax.axhline(30, color='blue', linestyle='--')
111
  ax.legend()
112
  st.pyplot(fig_rsi)
113
+
114
  # MACD
115
  if 'MACD' in indicators:
116
  macd = ta.macd(stock_data['Close'])
 
125
  ax.set_title(f"{company_name} MACD")
126
  ax.legend()
127
  st.pyplot(fig_macd)
128
+
129
  # Calculate moving averages
130
  stock_data['Volume_MA_5'] = stock_data['Volume'].rolling(window=5).mean()
131
  stock_data['Volume_MA_20'] = stock_data['Volume'].rolling(window=20).mean()
132
+
133
  # Plotting price and volume
134
  fig, ax1 = plt.subplots(figsize=(12, 6))
135
+
136
  # Plot the closing price
137
  ax1.plot(stock_data['Date'], stock_data['Close'], color='blue', label='Close Price')
138
  ax1.set_xlabel('Date')
139
  ax1.set_ylabel('Close Price', color='blue')
140
  ax1.tick_params(axis='y', labelcolor='blue')
141
+
142
  # Create a second y-axis for volume
143
  ax2 = ax1.twinx()
144
  ax2.bar(stock_data['Date'], stock_data['Volume'], color='gray', alpha=0.3, label='Volume')
145
+
146
  # Plot moving averages of volume
147
  ax2.plot(stock_data['Date'], stock_data['Volume_MA_5'], color='red', label='5-Day MA')
148
  ax2.plot(stock_data['Date'], stock_data['Volume_MA_20'], color='green', label='20-Day MA')
149
  ax2.set_ylabel('Volume', color='gray')
150
  ax2.tick_params(axis='y', labelcolor='gray')
151
+
152
  # Add legends and title
153
  fig.legend(loc='upper left', bbox_to_anchor=(0.15, 0.85))
154
  plt.title(f"{company_name} Price and Volume Chart with Moving Averages")
155
  fig.tight_layout()
156
  st.pyplot(fig)
157
+
158
  # Volume analysis
159
  stock_data['Volume_Pct_Change'] = stock_data['Volume'].pct_change() * 100
160
  average_volume = stock_data['Volume'].mean()
161
  current_volume = stock_data['Volume'].iloc[-1]
162
  volume_trend = 'increasing' if current_volume > average_volume else 'decreasing'
163
+
164
  st.subheader(f"Volume Analysis for {company_name}")
165
  st.write(f"- **Average Volume:** {average_volume:,.0f}")
166
  st.write(f"- **Current Volume:** {current_volume:,.0f}")
167
  st.write(f"- **Volume is currently {volume_trend}.**")
168
+
169
  # Convert data to CSV
170
  csv = stock_data.to_csv(index=False).encode('utf-8')
171
  # Download button for CSV