-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
78 lines (63 loc) · 2.21 KB
/
main.py
File metadata and controls
78 lines (63 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# %%
# imports
import yfinance as yf
import pandas as pd
from tabulate import tabulate
import matplotlib.pyplot as plt
# %%
# df link
df_link = "https://raw.githubusercontent.com/nmelgar/tickers-web-scrap-python/refs/heads/main/stock_tickers_data.json"
df = pd.read_json(df_link)
# print(df.to_string())
# %%
# first col
symbol_col = df["symbol"]
print(symbol_col.count())
# %%
# check if symbol existand display basic stock info
symbol = input("Enter a symbol to analyze: ").upper()
if symbol in symbol_col.values:
ticker_details = yf.Ticker(symbol)
info = ticker_details.info
print(f"Symbol: {symbol}")
print(f"Name: {info.get('shortName', 'N/A')}")
print(f"Market: {info.get('market', 'N/A')}")
print(f"Sector: {info.get('sector', 'N/A')}")
start_date = "2022-02-28"
end_date = "2025-02-28"
stock = yf.Ticker(symbol)
historical_data = stock.history(start=start_date, end=end_date)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", None)
print(f"Historical Data for {symbol} from {start_date} to {end_date}")
formatted_data = pd.concat([historical_data.head(), historical_data.tail()])
print(tabulate(formatted_data, headers="keys", tablefmt="psql"))
print("\nShowing only the first and last 5 rows of data:")
print(tabulate(formatted_data, headers="keys", tablefmt="grid"))
else:
print("Please enter a valid symbol :)")
# %%
data = stock.history(start=start_date, end=end_date)
# calculate 20-day moving average
data["20_Day_MA"] = data["Close"].rolling(window=20).mean()
# calculate daily returns
data["Daily_Return"] = data["Close"].pct_change() * 100
# plot closing price and 20-day moving average
plt.figure(figsize=(12, 6))
plt.plot(data["Close"], label="Close Price", color="blue")
plt.plot(data["20_Day_MA"], label="20-Day Moving Average", color="orange")
plt.title(f"{symbol} Closing Price and 20-Day Moving Average")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.show()
# plot daily returns
plt.figure(figsize=(12, 6))
plt.plot(data["Daily_Return"], label="Daily Returns", color="purple")
plt.title(f"{symbol} Daily Returns")
plt.xlabel("Date")
plt.ylabel("Daily Return (%)")
plt.legend()
plt.grid(True)
plt.show()