0% found this document useful (0 votes)
4 views1 page

1111.py

This document contains Python code that fetches stock data using the yfinance library, plots the closing prices of a specified stock, and calculates the 50-day simple moving average (SMA). It includes functions for fetching stock data, plotting the stock prices, and calculating the SMA. An example usage is provided for Apple stock (AAPL) over the year 2023.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

1111.py

This document contains Python code that fetches stock data using the yfinance library, plots the closing prices of a specified stock, and calculates the 50-day simple moving average (SMA). It includes functions for fetching stock data, plotting the stock prices, and calculating the SMA. An example usage is provided for Apple stock (AAPL) over the year 2023.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import yfinance as yf

import matplotlib.pyplot as plt

# Function to fetch stock data


def fetch_stock_data(ticker, start_date, end_date):
stock = yf.Ticker(ticker)
data = stock.history(start=start_date, end=end_date)
return data

# Function to plot stock closing prices


def plot_stock_data(data, ticker):
plt.figure(figsize=(10, 6))
plt.plot(data['Close'], label=f'{ticker} Close Price')
plt.title(f'{ticker} Stock Price History')
plt.xlabel('Date')
plt.ylabel('Close Price (USD)')
plt.legend()
plt.grid(True)
plt.show()

# Function to calculate simple moving average (SMA)


def calculate_sma(data, window=50):
return data['Close'].rolling(window=window).mean()

# Example usage
ticker = 'AAPL' # Apple stock as an example
start_date = '2023-01-01'
end_date = '2024-01-01'

# Fetch stock data


stock_data = fetch_stock_data(ticker, start_date, end_date)

# Plot the stock price


plot_stock_data(stock_data, ticker)

# Calculate and plot SMA


sma = calculate_sma(stock_data)
plt.figure(figsize=(10, 6))
plt.plot(stock_data['Close'], label=f'{ticker} Close Price')
plt.plot(sma, label='50-Day SMA', linestyle='--')
plt.title(f'{ticker} Stock Price and 50-Day Moving Average')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.show()

You might also like