0% found this document useful (0 votes)
51 views16 pages

Exploring Financial Markets With Python - A Simple Guide To Stock - by Dotun Alex Omoboye - Medium

Uploaded by

Danilo Freitas
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)
51 views16 pages

Exploring Financial Markets With Python - A Simple Guide To Stock - by Dotun Alex Omoboye - Medium

Uploaded by

Danilo Freitas
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
You are on page 1/ 16

Open in app Sign up Sign in

Faça login em Medium com o Google


Search

Danilo Freitas
[email protected]

Exploring Financial Markets Continuar


with Python-
como Danilo A
Simple Guide to StockPara criar a conta, o Google compartilhará seu
nome, endereço de e-mail e sua foto do perfil com o
Dotun Alex Omoboye · Follow app Medium. Consulte a Política de Privacidade e os
Termos de Serviço do app Medium.
5 min read · Dec 4, 2023

Be part of a better internet.


Listen GetShare
20% off membership for a limited time.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Sign up for free

Membership Get 20% off

Read member-only stories


Analyzing financial markets is a crucial aspect of informed decision-making in the
Support writers you read most
world of finance. Python servesas a tool for fetching and visualizing market data,
Earn money for your writing
making it an invaluable asset for financial analysts.
Listen to audio narrations
In this article, we’ll walk through a simple Python script that utilizes the yfinance
Read offline with the Medium app
library to fetch financial market data and matplotlib for plotting.

Requirements
Try for $ 5 $ 4/month
Before we go into the financial aspect of Python, ensure you have the necessary
libraries installed. You can install them using the following:
pip install yfinance matplotlib pandas

Be part of a better internet.


Get 20% off membership for a limited time.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Fetching Financial Market Data


This Python script prompts the user to input stock symbols and a start date. The
script then uses the yfinance library to download historical financial market data
for each symbol.
Membership Get 20% off

Read member-only stories


import yfinance as yf
import matplotlib.pyplot as plt
Support writers you read most
import pandas as pd
from datetime import datetime
Earn money for your writing
# User input
Listen to audio financial
stock_symbols = input("Enter narrations stock symbols separated by
commas (e.g., AAPL, MSFT): ").upper().split(',')
Read offline
start_date = input("Enter withstart
the the Medium app(YYYY-MM-DD): ")
date

# Use the current date as the end date


end_date = datetime.today().strftime('%Y-%m-%d')

# Fetch financial market data for each specified stock symbol


for symbol in stock_symbols:
try:
# Fetch data
stock_data = yf.download(symbol, start=start_date,
end=end_date)

# Calculate 60-day simple moving average (SMA)


stock_data['SMA_60'] =
stock_data['Close'].rolling(window=60).mean()

# Calculate daily percentage change in closing prices


stock_data['Daily_Return'] =
stock_data['Close'].pct_change() * 100

# Plotting
plt.figure(figsize=(14, 10))
Be part of a better internet.
# Closing Price and 60-day SMA
Get 20% off2,membership
plt.subplot(2, 1) for a limited time.
plt.plot(stock_data.index, stock_data['Close'],
label=f'{symbol} Closing Price')
plt.plot(stock_data.index, stock_data['SMA_60'],
label=f'{symbol}Free
60-day SMA', linestyle='--')
plt.title(f'{symbol} Closing Price and 60-day SMA')
plt.xlabel('Date')
Distraction-free reading. No ads.
plt.ylabel('Price (GBP)')
plt.legend()
Organize your knowledge with lists and highlights.

# Opening Price
Tell your story. Find your audience.
plt.subplot(2, 2, 2)
plt.plot(stock_data.index, stock_data['Open'],
label=f'{symbol} Opening Price', color='orange')
plt.title(f'{symbol} Opening Price')
plt.xlabel('Date')
plt.ylabel('Price (GBP)')
plt.legend()

# Volume
Membership
plt.subplot(2, 2, 3) Get 20% off

plt.bar(stock_data.index, stock_data['Volume'],
label=f'{symbol} Volume', color='green')
Read member-only
plt.title(f'{symbol} stories
Volume')
plt.xlabel('Date')
Support writers you read most
plt.ylabel('Volume')
plt.legend()
Earn money for your writing
# Daily Percentage Change
Listen to audio narrations
plt.subplot(2, 2, 4)
plt.plot(stock_data.index, stock_data['Daily_Return'],
Read offline with the Medium app
label=f'{symbol} Daily % Change', color='purple')
plt.title(f'{symbol} Daily Percentage Change')
plt.xlabel('Date')
plt.ylabel('% Change')
plt.legend()

plt.tight_layout()
plt.show()

except Exception as e:
print(f"Error fetching data for {symbol}: {e}")

Be part of a better internet.


Get 20% off membership for a limited time.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

#Output
Enter financial stock symbols separated by commas (e.g., AAPL,
MSFT): AAPL, AMZN, GOOGL, TSLA, COMP, GS, META, MSFT, DJIA

Membership Get 20% off

The stock symbols provided above and their corresponding companies:


Read member-only stories
1. AAPL: Apple Inc.
Support writers you read most
2. AMZN: Amazon.com Inc.
Earn money for your writing

3. GOOGL: Alphabet Inc. (Google)


Listen to audio narrations

4. TSLA: Tesla Inc. Read offline with the Medium app

5. COMP: NASDAQ Composite Index

6. GS: The Goldman Sachs Group Inc.


7. META: Meta Platforms, Inc. (formerly Facebook, Inc.)

8. MSFT: Microsoft Corporation

9. DJIA: Dow Jones Industrial Average

#Output

Enter the start date (YYYY-MM-DD): 2023-01-01

[*********************100%%**********************] 1 of 1 completed

The code generates four charts for each stock symbol entered by the user, These
Be part of aofbetter
charts provide a visual representation various internet.
aspects of the selected stocks, such
as closing and Get 20%
opening off membership
prices, moving averages,for
andadaily
limited time.changes,
percentage
allowing for a quick and intuitive analysis of their historical performance. Let’s
break down each chart:
Free
Opening Price Chart:
Data: This chart displays the opening
Distraction-free prices
reading. of the selected stocks over the
No ads.
specified time period.
Organize your knowledge with lists and highlights.

Lines: The solid line Tell


represents
your story. the
Findactual opening prices of the stock.
your audience.

Title and Labels: The chart has a title indicating that it shows the Opening Prices
for the selected stocks. The x-axis represents the date, and the y-axis represents
the opening price in USD.

Legend: A legend is included to distinguish the lines corresponding to each


stock.
Membership Get 20% off

Closing Price Chart:


Read member-only stories
Data: This chart displays the closing prices of the selected stocks over the
specified time period.
Support writers you read most

Lines: The solid line Earn money for your writing


represents the actual closing prices of the stock.
Listen to audio narrations
Title and Labels: The chart has a title indicating that it shows the Closing Prices
Read
for the selected stocks. offline
The with represents
x-axis the Medium app
the date, and the y-axis represents
the closing price in USD.

Legend: A legend is included to distinguish the lines corresponding to each


stock.
60-Day Simple Moving Average (SMA) Chart:
Data: This chart overlays a 60-day Simple Moving Average (SMA) on top of the
Closing Price chart.

Lines: The solid line represents the closing prices, and the dashed line
represents the 60-day SMA.

Title and Labels: Similar to the Closing Price chart, but with an additional
indication of the SMA.

Legend: The legend distinguishes between Closing Price and 60-day SMA.

Be part
Daily Percentage Change of a better internet.
Chart:
Get 20%
Data: This chart offthe
displays membership for
daily percentage a limited
change time.
in closing prices for the
selected stocks.

Freerepresents the percentage change.


Lines: The solid line

Title and Labels: TheDistraction-free


chart has a title indicating
reading. No ads. that it shows the Daily
Percentage Change in Closing Prices for the selected stocks. The x-axis
Organize your knowledge with lists and highlights.
represents the date, and the y-axis represents the percentage change.
Tell your story. Find your audience.
Legend: A legend is included to distinguish the lines corresponding to each
stock.

Membership Get 20% off


[*********************100%%**********************] 1 of 1 completed

Read member-only stories

Support writers you read most

Earn money for your writing

[*********************100%%**********************]
Listen to audio narrations 1 of 1 completed
#Google
Read offline with the Medium app
[*********************100%%**********************] 1 of 1 completed

[*********************100%%**********************] 1 of 1 completed

Be part of a better internet.


Get 20% off membership for a limited time.
[*********************100%%**********************] 1 of 1 completed

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.


[*********************100%%**********************] 1 of 1 completed
Tell your story. Find your audience.

[*********************100%%**********************] 1 of 1 completed

Membership Get 20% off

Read member-only stories

Support writers you read most


[*********************100%%**********************] 1 of 1 completed
Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Understanding the Code


User Input: The script prompts the user to input financial stock symbols and a start
date.
Data Fetching: It uses yfinance to download historical financial market data for each
symbol.

Data Analysis: The script calculates a 60-day simple moving average (SMA) for each
financial stock.

Data Visualization: It uses matplotlib to plot the closing prices and the 60-day SMA.

This Python script offers a simple yet effective way to analyze and visualize financial
market prices. Whether you are a financial analyst, stock market investor or just an
enthusiast, Python can be a powerful ally in understanding and interpreting
Be
financial data. Feel free to part ofthe
customize a better internet.
script based on your specific financial
analysis needs.Get 20% off membership for a limited time.

github repository link


Free
Happy coding!
Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Follow

Membership Get 20% off


Written by Dotun Alex Omoboye
8 Followers Read member-only stories

You found me ! I am a budding Data Engineer,


Support I write
writers about
you read my learning experience here
most

Earn money for your writing

Listen to audio narrations


More from Dotun Alex Omoboye
Read offline with the Medium app
Be part of a better internet.
Get 20% off membership for a limited time.
Dotun Alex Omoboye

Free
Machine Learning Predictions for the 2023 Cricket World Cup:
Leveraging Python and Historical Match
Distraction-free reading. No ads.
Introduction
Organize your knowledge with lists and highlights.
Oct 5, 2023 2
Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app


Dotun Alex Omoboye

Securing Data Pipelines: Essential Practices for Aspiring Data Engineers


Introduction: As data continues to fuel the modern business landscape, the role of data
engineers has become paramount in building…
Aug 7, 2023 4

Be part of a better internet.


Get 20% off membership for a limited time.

Free

Dotun Alex Omoboye Distraction-free reading. No ads.

Data Engineering Project —your


Organize From Scraping
knowledge toand
with lists Insights:
highlights.Building an
Automated ETL Pipeline and…
Tell your story. Find your audience.
Introduction

Sep 1, 2023 4 2

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Dotun Alex Omoboye


Fighting Fake News with Python!
🔍 Embracing the Fight Against Fake News: Introducing my Latest Python Script 📰💡

Jul 20, 2023

See all from Dotun Alex Omoboye

Be part of a better internet.


Get 20% off membership for a limited time.

Recommended from Medium


Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support
Alexander Nguyen in Level Up Codingwriters you read most

The resume that got aEarn money for your writing


software engineer a $300,000 job at Google.
1-page. Well-formatted. Listen to audio narrations

Jun 1 11K 145


Read offline with the Medium app
Be part of a better internet.
Get 20% off membership for a limited time.
Harshita Katiyar in Coinmonks

Free
FREE Stock APIs
Being a college undergrad, you will find a lot of people expressing their thoughts about how
stock market helped them toDistraction-free reading. No ads.
earn a lot, and…
Organize your knowledge with lists and highlights.
Feb 6 884 8
Tell your story. Find your audience.

Lists

Staff Picks
681 stories · 1114 saves
Membership Get 20% off

Stories to Help You Level-Up at Work


19 stories · 680 saves
Read member-only stories

Self-Improvement
Support101
writers you read most
20 stories · 2244 saves
Earn money for your writing
Productivity 101
Listen to audio narrations
20 stories · 1987 saves

Read offline with the Medium app


Be part of a better internet.
Get 20% off membership for a limited time.
Vishal Rajput in AIGuys

Free
Prompt Engineering Is Dead: DSPy Is New Paradigm For Prompting
DSPy Paradigm: Let’s program — not prompt — LLMs
Distraction-free reading. No ads.

May 29 3.8K 36 Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app


Be part of a better internet.
Get 20% off membership for a limited time.
Alberto Gálvez

Free
Predicting Stock Prices with an LSTM Model in Python

Feb 9 98 2 Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app


Be part of a better internet.
Get 20% off membership for a limited time.
Sugath Mudali

Free
Fundamental Analysis for ranking Stocks with Python API
This article will rank stocks based on their fundamentals and stock details. The approach
builds on the previous articleDistraction-free
"Fundamental reading.
Stock… No ads.

Organize your knowledge with lists and highlights.


Jan 26 269 1
Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app


Henrique Centieiro & Bee Lee in Limitless Investor

52% Returns in 30 Days: Your GPT-4o Quant Trading Bot Strategy


How to Profit in Any Market Condition with GPT-4o’s Mean Regression Strategies
May 21 1.7K 31

See more recommendations

Be part of a better internet.


Get 20% off membership for a limited time.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership Get 20% off

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

You might also like