0% found this document useful (0 votes)
7 views7 pages

Advanced Stock Market Analysis With Python

The document outlines a Python script that retrieves and analyzes stock prices for Apple, Microsoft, NVIDIA, and Google over the last three months using the yfinance library. It includes calculations for moving averages, volatility, and correlation between the stock prices of different companies, along with visualizations using Plotly. The analysis aims to provide insights into stock market performance and relationships between the companies' stocks.

Uploaded by

ayushgoel.9817
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Advanced Stock Market Analysis With Python

The document outlines a Python script that retrieves and analyzes stock prices for Apple, Microsoft, NVIDIA, and Google over the last three months using the yfinance library. It includes calculations for moving averages, volatility, and correlation between the stock prices of different companies, along with visualizations using Plotly. The analysis aims to provide insights into stock market performance and relationships between the companies' stocks.

Uploaded by

ayushgoel.9817
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import pandas as pd

import yfinance as yf
from datetime import datetime, timedelta

# Calculate start and end dates for the last 3 months


end_date = [Link]()
start_date = end_date - timedelta(days=90)

tickers = ['AAPL', 'MSFT', 'NVDA', 'GOOG']

df_list = []

for ticker in tickers:


data = [Link](ticker, start=start_date, end=end_date)
df_list.append(data)

df = [Link](df_list, keys=tickers, names=['Ticker', 'Date'])


print([Link]())

[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
[*********************100%%**********************] 1 of 1 completed
Open High Low Close \
Ticker Date
AAPL 2024-02-05 188.14999390 189.25000000 185.83999634 187.67999268
2024-02-06 186.86000061 189.30999756 186.77000427 189.30000305
2024-02-07 190.63999939 191.05000305 188.61000061 189.41000366
2024-02-08 189.38999939 189.53999329 187.35000610 188.32000732
2024-02-09 188.64999390 189.99000549 188.00000000 188.85000610

Adj Close Volume


Ticker Date
AAPL 2024-02-05 187.44081116 69668800
2024-02-06 189.05876160 43490800
2024-02-07 189.16862488 53439000
2024-02-08 188.08001709 40962000
2024-02-09 188.85000610 45155200
In the code above, we first brought in the necessary Python tools and got the past three months stock prices for four companies: Apple, Microsoft, NVIDIA,
and Google. Within this dataset, the Date column serves as the index in the DataFrame. Before proceeding further, we must reset the index.
df = df.reset_index()
print([Link]())

Ticker Date Open High Low Close \


0 AAPL 2024-02-05 188.14999390 189.25000000 185.83999634 187.67999268
1 AAPL 2024-02-06 186.86000061 189.30999756 186.77000427 189.30000305
2 AAPL 2024-02-07 190.63999939 191.05000305 188.61000061 189.41000366
3 AAPL 2024-02-08 189.38999939 189.53999329 187.35000610 188.32000732
4 AAPL 2024-02-09 188.64999390 189.99000549 188.00000000 188.85000610

Adj Close Volume


0 187.44081116 69668800
1 189.05876160 43490800
2 189.16862488 53439000
3 188.08001709 40962000
4 188.85000610 45155200

Now let’s have a look at the performance in the stock market of all the companies:

import [Link] as px
fig = [Link](df, x='Date',
y='Close',
color='Ticker',
title="Stock Market Performance for the Last 3 Months")
[Link]()
Stock Market Performance for the Last 3 Months

Ticker
900 AAPL
MSFT
800 NVDA
GOOG
700

600
Close

500

400

300

200

100
Feb 11 Feb 25 Mar 10 Mar 24 Apr 7 Apr 21
2024

Date

Now, let’s examine the segmented area chart. It helps us compare how various companies are doing and spot any similarities or
differences in their stock price changes.

fig = [Link](df, x='Date', y='Close', color='Ticker',


facet_col='Ticker',
labels={'Date':'Date', 'Close':'Closing Price', 'Ticker':'Company'},
title='Stock Prices for Apple, Microsoft, NVIDIA, and Google')
[Link]()

Now, let’s examine moving averages, which offers a useful method for spotting trends and patterns in the stock price movements of each
company over a specific duration.

df['MA10'] = [Link]('Ticker')['Close'].rolling(window=10).mean().reset_index(0, drop=True)


df['MA20'] = [Link]('Ticker')['Close'].rolling(window=20).mean().reset_index(0, drop=True)

for ticker, group in [Link]('Ticker'):


print(f'Moving Averages for {ticker}')
print(group[['MA10', 'MA20']])
Moving Averages for AAPL
MA10 MA20
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
.. ... ...
58 168.38699951 169.54699936
59 168.48199921 169.62149963
60 168.61199951 169.60400009
61 169.21100006 169.81449966
62 171.04900055 170.50449982

[63 rows x 2 columns]


Moving Averages for GOOG
MA10 MA20
189 NaN NaN
190 NaN NaN
191 NaN NaN
192 NaN NaN
193 NaN NaN
.. ... ...
247 160.45700073 158.54700012
248 161.32100067 158.98550034
249 162.19000092 159.44550095
250 163.29000092 160.27150116
251 164.61700134 161.02400131

[63 rows x 2 columns]


Moving Averages for MSFT
MA10 MA20
63 NaN NaN
64 NaN NaN
65 NaN NaN
66 NaN NaN
67 NaN NaN
.. ... ...
121 405.50099792 413.89499969
122 402.97599792 412.28949890
123 401.28599854 411.01399841
124 400.64299927 410.01199799
125 401.39700012 409.06899872

[63 rows x 2 columns]


Moving Averages for NVDA
MA10 MA20
126 NaN NaN
127 NaN NaN
128 NaN NaN
129 NaN NaN
130 NaN NaN
.. ... ...
184 832.06300049 854.36050110
185 831.05000000 852.83550110
186 830.05599976 849.87399902
187 831.20199585 849.82999878
188 843.79099731 850.22049866

[63 rows x 2 columns]

Now here’s how to visualize the moving averages of all companies:

for ticker, group in [Link]('Ticker'):


fig = [Link](group, x='Date', y=['Close', 'MA10', 'MA20'],
title=f"{ticker} Moving Averages")
[Link]()
Now, we’ll examine the volatility of all the companies. Volatility measures how much and how frequently the stock price or market
changes over a set period. Here’s how we can visualize the volatility of all companies:

df['Volatility'] = [Link]('Ticker')['Close'].pct_change().rolling(window=10).std().reset_index(0, drop=True)


fig = [Link](df, x='Date', y='Volatility',
color='Ticker',
title='Volatility of All Companies')
[Link]()
High volatility means that the stock or market goes through big and frequent price changes, whereas low volatility means that the market
sees smaller or less frequent price shifts. Now let’s analyze the correlation between the stock prices of Apple and Microsoft:

# create a DataFrame with the stock prices of Apple and Microsoft


apple = [Link][df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'AAPL'})
microsoft = [Link][df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'MSFT'})
df_corr = [Link](apple, microsoft, on='Date')

# create a scatter plot to visualize the correlation


fig = [Link](df_corr, x='AAPL', y='MSFT',
trendline='ols',
title='Correlation between Apple and Microsoft')
[Link]()

Now let’s analyze the correlation between the stock prices of NVIDIA and GOOGLE:

# create a DataFrame with the stock prices of Apple and Microsoft


apple = [Link][df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'NVDA'})
microsoft = [Link][df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'GOOG'})
df_corr = [Link](apple, microsoft, on='Date')

# create a scatter plot to visualize the correlation


fig = [Link](df_corr, x='NVDA', y='GOOG',
trendline='ols',
title='Correlation between Nvidia and Google')
[Link]()

Summary
In conclusion, analyzing stock market performance includes tasks like calculating moving averages, assessing volatility, conducting
correlation analysis, and examining different aspects of the market. This helps us understand what influences stock prices and how
stocks of different companies relate to each other.

Common questions

Powered by AI

Different visualization methods, such as area charts and scatter plots, provide varied perspectives on the stock data, enhancing comprehension of different aspects of market dynamics. Area charts are effective in illustrating cumulative quantities and trends over time, while scatter plots are invaluable for identifying correlations and relationships between variables, such as price movements between two stocks like AAPL and MSFT. These diverse perspectives facilitate deeper insights and better-informed investment decisions .

Differences in volatility among companies like MSFT and NVDA can be attributed to several factors, including company size, market influence, the diversity of revenue streams, investor base, and exposure to market trends or disruptive technologies. MSFT, as a larger and more diversified entity, might have lower volatility compared to NVDA, which might be more sensitive to semiconductor sector-specific trends and rapid technological advancements .

Resetting the DataFrame index is essential to ensure the dataset is structured correctly for analysis and visualization. It particularly helps when merging datasets from different companies like Apple, Microsoft, NVIDIA, and Google because it removes the index set by the data fetching operations, allowing a unified format that supports operations such as date-based filtering and aggregation across multiple tickers .

Segmented area charts allow for the visualization of the absolute differences in stock prices and their relative performances over time. By comparing segmented areas representing different companies, such as Apple, Microsoft, NVIDIA, and Google, investors can easily identify how these stocks are performing against each other, uncovering trends, divergences, or convergence points that may signal strategic investment insights .

Calculating the percentage change in closing prices helps standardize the movement of stock prices in relative terms, enabling comparisons across different stocks regardless of their absolute price levels. This metric provides a clearer picture of the stock's performance, highlighting gains or losses over time and helping identify trends, momentum, or periods of particular investor activity across companies like AAPL and MSFT .

Volatility measures the extent and frequency of price changes in a stock or market over a specific period. High volatility indicates large and frequent price changes, making the market more unpredictable, whereas low volatility suggests smaller, less frequent shifts. In the case of NVIDIA and Google, comparing their volatilities can reveal which company's stock is more stable and which offers more risk and potential reward due to bigger price fluctuations .

Moving averages like MA10 and MA20 provide insights into the medium-term direction of a stock, but their effectiveness can vary between different companies due to varying volumes, volatilities, and market environments. For example, MSFT might exhibit more stable moving averages if it has less volatile price swings compared to GOOG, reflecting steadier investor sentiment or differing market influences. Thus, analyzing these averages across companies helps to benchmark performance under different market conditions .

Correlation analysis between stocks like Apple and Microsoft helps in understanding how the price changes in one stock mirror, differ, or complement those in another. A high positive correlation suggests that stock prices tend to move together, possibly indicating shared market influences or investor sentiments, while a low or negative correlation might imply diversification benefits when holding both stocks concurrently .

Moving averages, such as MA10 and MA20, provide a method to smooth out the short-term fluctuations in stock prices, making it easier to identify longer-term trends. They help in determining the direction of the trend – whether a stock like Apple or Microsoft is in an uptrend, downtrend, or moving sideways. The MA10 averages the closing prices over the past ten days, while the MA20 does the same for twenty days, which helps investors to identify whether the current price action is aligning with the longer-term trend .

Rolling standard deviations, calculated over a moving window (e.g., 10 days), can graphically depict the volatility of a stock like Google by illustrating how much its price varies over time. This metric shows periods of high and low volatility, allowing investors to understand when the stock's price was more stable or erratic, which can impact risk assessments and timing for buy/sell decisions .

You might also like