1+ import yfinance as yf
2+ import numpy as np
3+ import pandas as pd
4+ from sklearn .cluster import KMeans
5+
6+ tickers = ['AAPL' , 'MSFT' , 'GOOGL' , 'AMZN' , 'META' , 'TSLA' , 'NFLX' , 'NVDA' ]
7+
8+ stock_dt = yf .download (tickers , start = "2023-09-01" , end = "2024-09-01" , group_by = 'ticker' )
9+ stock_prices = []
10+ for ticker in tickers :
11+ closing_prices = stock_dt [ticker ]['Close' ].values [:200 ]
12+ stock_prices .append (closing_prices )
13+ stock_prices_numpyy = np .array (stock_prices )
14+ print (stock_prices_numpyy .shape )
15+
16+
17+ # Date
18+ stock_dt .index = pd .to_datetime (stock_dt .index )
19+
20+ # Monthly averages, max and mins
21+ def calculate_monthly_stats ():
22+ monthly_stats = {}
23+ for ticker in tickers :
24+ # Group data in month and calc mean max min
25+ monthly_data = stock_dt [ticker ]['Close' ].resample ('M' ).agg (['mean' , 'max' , 'min' ])
26+ monthly_stats [ticker ] = monthly_data
27+ return monthly_stats
28+
29+
30+ #Task3 daily price change
31+ def calculate_the_daily_share_price_change ():
32+ daily_returns = {}
33+ for ticker in tickers :
34+ daily_returns [ticker ]= stock_dt [ticker ]['Close' ].pct_change ().dropna ()
35+ return daily_returns
36+
37+ daily_returns = calculate_the_daily_share_price_change ()
38+
39+
40+ #Task3 highest share price change
41+ def highest_single_day_changes ():
42+ highest_increase = {}
43+ highest_decrease = {}
44+
45+ for ticker in tickers :
46+ highest_decrease [ticker ]= daily_returns [ticker ].idxmin (), daily_returns [ticker ].min ()
47+ highest_increase [ticker ]= daily_returns [ticker ].idxmax (), daily_returns [ticker ].max ()
48+
49+ return highest_decrease , highest_increase
50+
51+ highest_decrease ,highest_increase = highest_single_day_changes ()
52+ print ("The highest single day price increases: " )
53+
54+ for ticker , (date , change ) in highest_increase .items ():
55+ print (f"{ ticker } { date } with increase of { change :.2%} " )
56+
57+ print ("\n Highest single day decrease " )
58+
59+ for ticker ,(date , change ) in highest_decrease .items ():
60+ print (f"{ ticker } :{ date } with decrease of { change :.2%} " )
61+
62+ volatility = {ticker : np .std (daily_returns [ticker ]) for ticker in daily_returns .keys ()}
63+ most_volatile_element_ticker = max (volatility ,key = volatility .get )
64+
65+ print (f"\n Most Volatile stock: { most_volatile_element_ticker } with volatility { volatility [most_volatile_element_ticker ]:.4f} " )
66+
67+ #Task 4
68+ def cluster_stocks (number_clusters = 3 ):
69+ the_returned_matrix = np .array ([daily_returns [ticker ] for ticker in tickers ])
70+ kmeans_algorithm = KMeans (n_clusters = number_clusters , random_state = 42 )
71+ kmeans_algorithm .fit (the_returned_matrix )
72+ return kmeans_algorithm .labels_
73+
74+ the_stock_clusters = cluster_stocks (number_clusters = 3 )
75+
76+ print ("Stock Clusters" )
77+
78+ for ticker ,cluster in zip (tickers , the_stock_clusters ):
79+ print (f"{ ticker } is within the cluster { cluster } " )
80+
81+ monthly_stats = calculate_monthly_stats ()
82+ for ticker , stats in monthly_stats .items ():
83+ print (f"{ ticker } Monthly Stats:\n " , stats )
84+
85+ # Find how many days Tesla stock was above $500
86+ def days_above_500 (ticker , threshold = 500 ):
87+ above_threshold = stock_dt [ticker ]['Close' ][stock_dt [ticker ]['Close' ] > threshold ].count ()
88+ return above_threshold
89+
90+ tesla_above_500 = days_above_500 ('TSLA' , 500 )
91+ print (f"The tesla share price was above $500 on { tesla_above_500 } days." )
92+
93+ def find_top_5_days (ticker ):
94+ top5days = stock_dt [ticker ]['Close' ].nlargest (5 )
95+ return top5days
96+
97+ for ticker in tickers :
98+ top_5 = find_top_5_days (ticker )
99+ print (f"Top 5 days for { ticker } :\n " , top_5 )
100+
101+
102+
103+ def high_and_low ():
104+ highest_price = stock_dt .xs ('Close' , level = 1 , axis = 1 ).idxmax (axis = 1 )
105+ lowest_price = stock_dt .xs ('Close' , level = 1 , axis = 1 ).idxmin (axis = 1 )
106+ return highest_price , lowest_price
107+
108+ highest_price , lowest_price = high_and_low ()
109+ print (f"Company with highest prices on each day:\n { highest_price } " )
110+ print (f"Company with lowest prices on each day:\n { lowest_price } " )
111+
112+ #Task 4
113+ company_idx = 2
114+ google_prices = stock_prices_numpyy [company_idx , :]
115+
116+
117+ #Task 5 finding the mean and std and generate 200 values
118+ the_mean = np .mean (google_prices )
119+ standard_deviation = np .std (google_prices )
120+ new_stock_prices = np .random .normal (the_mean , standard_deviation , 200 )
121+ new_stock_prices = new_stock_prices .reshape (1 ,- 1 )
122+ updated_stock_share_price = np .concatenate ((stock_prices_numpyy , new_stock_prices ))
123+ print ("Updated stock share price shape: " ,updated_stock_share_price .shape )
124+
125+
126+ #Task 6 META
127+ company_idx = 4
128+ meta_share_price = stock_prices_numpyy [company_idx , :]
129+
130+ meta_share_price_changes = np .diff (meta_share_price )/ meta_share_price [:- 1 ]
131+
132+ ## mean
133+ mean_percent_diff = np .mean (meta_share_price_changes )
134+ standard_percent_change = np .std (meta_share_price_changes )
135+
136+ #daily percentage
137+ number_of_days = 30
138+ forecast_percent_difference = np .random .normal (mean_percent_diff , standard_percent_change , number_of_days )
139+
140+
141+ forecasted_prices = [meta_share_price [- 1 ]]
142+
143+ for standard_percent_change in forecast_percent_difference :
144+ upcoming_price = forecasted_prices [- 1 ]* (1 + standard_percent_change )
145+ forecasted_prices .append (upcoming_price )
146+
147+ forecasted_prices = np .array (forecasted_prices [1 :])
148+
149+ print ("The predicted price of Meta is for the next 30 days: " )
150+ print (forecasted_prices )
151+
152+ predicted_days_in_time = pd .date_range (start = stock_dt .index [- 1 ],periods = number_of_days , freq = 'D' )
153+ predicted_data_frame = pd .DataFrame ({'Date' : predicted_days_in_time , 'Predicted Share Price' : forecasted_prices })
154+
155+
156+ print (predicted_data_frame )
157+
158+
159+ #saved file
160+ np .savetxt ("file.txt" ,stock_prices_numpyy )
0 commit comments