5 python code examples to analyze stock market
Below are 5 Python code examples tailored for analyzing the stock market. These examples utilize popular Python libraries such as pandas for data manipulation, matplotlib for data visualization, and yfinance to fetch financial data. Ensure you have these libraries installed in your environment before running the codes.
1. Fetching Stock Data
This example uses the yfinance library to fetch historical stock data for a given ticker symbol (e.g., AAPL for Apple Inc.) over a specified period.
python
import yfinance as yf
# Fetch historical data for Apple Inc.
ticker_symbol = "AAPL"
ticker_data = yf.Ticker(ticker_symbol)
# Get historical prices for this ticker
ticker_df = ticker_data.history(period="1mo") # 1 month of data
print(ticker_df)
Explanation: This code uses the yfinance library to obtain historical data for a specified stock, in this case, Apple Inc. (AAPL). By calling yf.Ticker(ticker_symbol), we create an object that allows access to various data about the stock, including historical prices. ticker_data.history(period="1mo") fetches the last month's worth of price data. The data includes open, high, low, close prices, and volume for each trading day within the specified period.
2. Calculating Moving Averages
This example calculates the 20-day and 50-day moving averages of a stock's closing price, which are common indicators used in trading.
python
import pandas as pd
import yfinance as yf
# Fetch historical data
ticker_symbol = "AAPL"
ticker_data = yf.Ticker(ticker_symbol)
ticker_df = ticker_data.history(period="6mo") # 6 months of data
# Calculate moving averages
ticker_df['MA20'] = ticker_df['Close'].rolling(window=20).mean()
ticker_df['MA50'] = ticker_df['Close'].rolling(window=50).mean()
print(ticker_df[['Close', 'MA20', 'MA50']])
Explanation: Moving averages smooth out price data over a specified period, making it easier to identify the trend direction. This code calculates the 20-day and 50-day moving averages of the closing prices for Apple Inc. (AAPL) over the last six months. The .rolling(window=20).mean() method is used to compute these averages, which are then added to the dataframe as new columns (MA20 and MA50). This approach is helpful in trend analysis and trading decision-making.
3. Visualizing Stock Data
This code plots the stock's closing price along with its 20-day and 50-day moving averages.
python
import matplotlib.pyplot as plt
import yfinance as yf
# Fetch data
ticker_symbol = "AAPL"
ticker_data = yf.Ticker(ticker_symbol)
ticker_df = ticker_data.history(period="1y") # 1 year of data
# Calculate moving averages
ticker_df['MA20'] = ticker_df['Close'].rolling(window=20).mean()
ticker_df['MA50'] = ticker_df['Close'].rolling(window=50).mean()
# Plot
plt.figure(figsize=(14, 7))
plt.plot(ticker_df['Close'], label='Close Price')
plt.plot(ticker_df['MA20'], label='20-Day MA')
plt.plot(ticker_df['MA50'], label='50-Day MA')
plt.title(f'{ticker_symbol} Stock Price and Moving Averages')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()
Explanation: This code visually represents the stock's closing price along with its 20-day and 50-day moving averages over the past year. Using matplotlib, it plots these three series on the same graph, allowing for a visual comparison. Such visualizations are crucial for identifying trends, potential support/resistance levels, and crossover points that might indicate buy or sell signals.
4. Calculating Daily Returns
This example calculates the daily returns of a stock, which is a measure of how much the price of the stock changes each day.
python
import yfinance as yf
# Fetch data
ticker_symbol = "AAPL"
ticker_data = yf.Ticker(ticker_symbol)
ticker_df = ticker_data.history(period="3mo") # 3 months of data
# Calculate daily returns
ticker_df['Daily Return'] = ticker_df['Close'].pct_change()
print(ticker_df[['Close', 'Daily Return']])
Explanation: Daily returns represent the percentage change in stock price from one day to the next, offering insights into the stock's daily volatility. The .pct_change() method calculates these returns. This code fetches three months of Apple Inc. (AAPL) data, computes the daily returns, and adds them to the dataframe. Analyzing daily returns can help in understanding the stock's risk profile and in constructing diversified portfolios.
5. Comparing Stocks
This final example fetches and compares the closing prices of two stocks, visualizing their performance over the same period.
python
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
# Fetch data for two stocks
tickers = ["AAPL", "MSFT"]
data = yf.download(tickers, start="2023-01-01", end="2023-12-31")['Close']
# Plot
plt.figure(figsize=(14, 7))
plt.plot(data['AAPL'], label='Apple')
plt.plot(data['MSFT'], label='Microsoft')
plt.title('Stock Comparison: Apple vs. Microsoft')
plt.xlabel('Date')
plt.ylabel('Closing Price')
plt.legend()
plt.show()
Explanation: This code compares the performance of two major stocks, Apple Inc. (AAPL) and Microsoft Corp. (MSFT), over a specified time frame. It fetches the closing prices of both stocks for the year 2023 and plots them on the same graph for direct comparison. Visual comparison can be extremely useful for investors looking to evaluate the relative performance of different investments, understand market trends, and make informed decisions based on historical data patterns.
Each of these examples serves a unique purpose in stock market analysis, from basic data fetching and visualization to the calculation of key trading indicators and performance comparison. Remember, investing in the stock market involves risk, and these examples are intended for educational purposes only.
Fore More Analysis and latest updates in algo Trading visit : usdmonitor.com