Skip to content

Commit 9ba4c07

Browse files
authored
Merge pull request #315 from vikabi/stock-updates
Stock analysis update
2 parents 73c2d62 + 53781f7 commit 9ba4c07

File tree

3 files changed

+69
-58
lines changed

3 files changed

+69
-58
lines changed
Loading
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
StockAnalysis
22

3-
This program has ability to analyse stock and compare its price over today,yesterday,lastmonth,lastyear and plot the trend.
4-
Program allows to input stock tickers explcitly or get 'n' stock based on S&P index.
3+
This program empowers users to analyze stock data and compare its price trends over various timeframes: today, yesterday, last month, and last year. The program offers the flexibility to input specific stock tickers or retrieve 'n' stocks based on the S&P index.
4+
Usage
55

6+
The program provides insights into stock performance and visualizes trends. Users can input stock tickers or opt for automatic retrieval based on the S&P index.
67
Sample Output
78

8-
For eg: Here it can analyse how AAPL is performed over yesterday,lastmonth,lastyear and plot
9+
For instance, the program can analyze the performance of AAPL over the past day, month, and year, plotting the trends for visual understanding.
910

11+
![image](https://user-images.githubusercontent.com/16798480/225775468-f9332a85-8181-47eb-a48f-8d36f85e9d5a.png)
1012

13+
Changes Made
1114

12-
![image](https://user-images.githubusercontent.com/16798480/225775468-f9332a85-8181-47eb-a48f-8d36f85e9d5a.png)
15+
The program underwent significant enhancements:
16+
17+
1. Input Validation: Implemented robust user input validation for seamless data retrieval.
18+
2. Data Fetching Enhancement: Utilized the Yahoo Finance API to fetch accurate stock data.
19+
3. Improved Data Plotting: Enhanced data plotting with titles and labels for clearer visualization.
20+
4. Handling No Data: Addressed scenarios where no data is available for specific stocks, ensuring smoother execution.
21+
5. Code Organization: Structured the code for better organization and readability.
Original file line numberDiff line numberDiff line change
@@ -1,64 +1,66 @@
11
import yfinance as yf
22
import pandas as pd
3-
import datetime
4-
from datetime import date
5-
from pandas_datareader import data as pdr
6-
import pandas as pd
3+
from datetime import datetime, timedelta
74
import matplotlib.pyplot as plt
85

9-
stocknum=10
10-
option=1
11-
tickerlist = []
12-
while True:
13-
try:
14-
option = int(input("You have 2 options 1: Do you want to analyse top stocks in S&P index 2: Specific Stocks, 1/2 ?"))
15-
16-
if option==1:
17-
stocknum=int(input("How many stocks you want to analyse? give a number"))
18-
toptickers = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
19-
tickerlist= toptickers.head(stocknum).Symbol.to_list()
20-
print(tickerlist)
21-
elif option==2:
22-
inputstr = input("Enter comma separated ticker symbols of interested stocks ")
23-
print("Input string: ", inputstr)
24-
25-
# conver to the list
26-
tickerlist = inputstr.upper().split (",")
27-
print("list: ", list)
28-
else:
29-
raise ValueError
30-
break
31-
except ValueError:
32-
print("Please input valid integer only...")
33-
continue
34-
35-
data = pd.DataFrame(columns=tickerlist)
6+
# Function to get a list of tickers for analysis
7+
def get_ticker_list():
8+
while True:
9+
try:
10+
option = int(input("You have 2 options:\n1. Analyze top stocks in S&P index\n2. Specific Stocks\nEnter option (1/2): "))
3611

37-
for ticker in tickerlist:
38-
y = yf.Ticker(ticker)
39-
if(y==0):
40-
print("No data found for ",ticker)
41-
break
42-
try:
43-
today=date.today()
44-
yesterday=today + datetime.timedelta(days=-1)
45-
lastmonth=today + datetime.timedelta(days=-30)
46-
lastyear=today + datetime.timedelta(days=-365)
47-
df2=yf.download(tickerlist,today,today+datetime.timedelta(days=1), auto_adjust=True)['Close']
48-
df3=yf.download(tickerlist,yesterday,yesterday+datetime.timedelta(days=1), auto_adjust=True)['Close']
49-
df4=yf.download(tickerlist,lastmonth,lastmonth+datetime.timedelta(days=1), auto_adjust=True)['Close']
50-
df5=yf.download(tickerlist,lastyear,lastyear+datetime.timedelta(days=1), auto_adjust=True)['Close']
51-
data=data.append(df2)
52-
data=data.append(df3)
53-
data=data.append(df4)
54-
data=data.append(df5)
55-
data.plot()
12+
if option == 1:
13+
stocknum = int(input("How many stocks do you want to analyze? Enter a number: "))
14+
toptickers = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')[0]
15+
return toptickers.head(stocknum).Symbol.to_list()
16+
elif option == 2:
17+
inputstr = input("Enter comma-separated ticker symbols of interested stocks: ")
18+
return inputstr.upper().split(",")
19+
else:
20+
print("Please enter a valid option (1/2).")
21+
except ValueError:
22+
print("Please input a valid integer only.")
5623

57-
print(data.head())
58-
except:
59-
print("Error occured while processing. Please try again.")
24+
# Function to get the time period for analysis
25+
def get_time_period():
26+
try:
27+
start_date = input("Enter the start date (YYYY-MM-DD): ")
28+
end_date = input("Enter the end date (YYYY-MM-DD): ")
29+
return start_date, end_date
30+
except ValueError:
31+
print("Invalid date format. Please use the format YYYY-MM-DD.")
6032

33+
# Main function
34+
def main():
35+
tickerlist = get_ticker_list()
36+
37+
start_date, end_date = get_time_period() # Get time period for analysis
38+
39+
data = pd.DataFrame()
6140

41+
# Loop through each ticker to fetch data
42+
for ticker in tickerlist:
43+
try:
44+
y = yf.Ticker(ticker)
45+
df = y.history(period="1d", start=start_date, end=end_date)
46+
if not df.empty:
47+
data[ticker] = df["Close"]
48+
else:
49+
print("No data found for", ticker)
50+
except Exception as e:
51+
print("An error occurred while fetching data for", ticker, ":", str(e))
6252

63-
53+
if not data.empty:
54+
# Plotting the data
55+
data.plot(title="Stock Price Analysis")
56+
plt.xlabel("Date")
57+
plt.ylabel("Price")
58+
plt.show()
59+
60+
print(data.head())
61+
else:
62+
print("No data available for analysis.")
6463

64+
# Entry point of the program
65+
if __name__ == "__main__":
66+
main()

0 commit comments

Comments
 (0)