In this article, we will explore how to analyze stocks using Python and Excel. We will fetch historical data for three popular stocks—Realty Income (O), McDonald’s (MCD), and Johnson & Johnson (JNJ) — calculate returns, factor in dividends, and visualize…
برچسب: Python
-
Automate Stock Analysis with Python and Yfinance: Generate Excel Reports
-
Python – Data Wrangling with Excel and Pandas – Useful code
Data wrangling with Excel and Pandas is actually quite useful tool in the belt of any Excel professional, financial professional, data analyst or a developer. Really, everyonecan benefit from the well defined libraries that ease people’s lifes. These are the libraries used:
import pandas as pd # Main data manipulation
from openpyxl import Workbook # Excel writing
from openpyxl.styles import Font # Excel formatting (bold, colors)
import glob # File path handling
from datetime import datetime
Additionally, a function for making a unique Excel name is used:
def make_unique_name():
timestamp = datetime.now().strftime(‘%Y%m%d_%H%M%S’)
return f‘{timestamp}__report.xlsx’
An example of the video, where Jupyter Notebook is used.
In the YT video below, the following 8 points are discussed:
# Trick 1 – Simple reading of worksheet from Excel workbook
excel_file_name = “financial_data.xlsx”
df = pd.read_excel(excel_file_name,
sheet_name = “Transactions”,
parse_dates = [“Date”],
dtype={“InvoiceID”:str})
# Trick 2 – Combine Reports
income = pd.read_excel(excel_file_name, sheet_name=“Income”)
expenses = pd.read_excel(excel_file_name, sheet_name=“Expenses”)
combined = pd.concat([
income.assign(From_Worksheet=“Income”),
expenses.assign(From_Worksheet=“Expenses”)
])
# Trick 3 – Fix Missing Values
combined[“Amount”] = combined[“Amount”].fillna(combined[“Amount”].mean())
# Trick 4 – Formatting the exported Excel file
with pd.ExcelWriter(new_worksheet, engine=“openpyxl”) as writer:
combined.to_excel(writer, index=False)
workbook = writer.book
worksheet=writer.sheets[“Sheet1”]
for cell in worksheet[“1:1”]:
cell.font = Font(bold=True)
cell.font = Font(color=“FFFF22”)
# Trick 5 – Merging Excel Files
files = glob.glob(“sales12/sales_*.xlsx”)
annual_data = pd.concat([pd.read_excel(f) for f in files])
# Trick 6 – Smart Filtering
web_design_only = annual_data[
(annual_data[“Description”]==“Web Design”
)]
small_transactions = annual_data[
(annual_data[“Amount”] < 200
)]
# Trick 7 – Mergining Tables
df_transactions = pd.read_excel(
excel_file_name,
sheet_name=“Transactions”)
df_customers = pd.read_excel(
excel_file_name,
sheet_name=“Customers”)
merged = pd.merge(
df_transactions,
df_customers,
on = “CustomerID”
)
# Trick 8 – Export Dataframe to Excel
with pd.ExcelWriter(new_worksheet, engine=“openpyxl”) as writer:
merged.to_excel(writer)
The whole code with the Excel files is available in GitHub here.
https://www.youtube.com/watch?v=SXXc4WySZS4
Enjoy it!
-
Python – Monte Carlo Simulation – Useful code
Python can be used for various tasks. One of these is Monte Carlo simulation for future stock analysis. In the video below this is exactly what is happening. 🙂
10K simulations in 30 buckets for KO look like that.
Instead of explaining the video and its code (available also in GitHub), I will concentrate on why it is better to use log returns than simple returns in stock analysis. Which is actually part of the video as well. Below are the 3 main reasons:
1. Time-Additivity
Log returns sum over time, making multi-period calculations effortless. A 10% gain followed by a 10% loss doesn’t cancel out with simple returns—but it nearly does with logs.
2. Symmetry Matters
A +10% and -10% return aren’t true inverses in simple terms. Logs fix this, ensuring consistent math for gains and losses.
3. Better for Modeling
Log returns follow a near-normal distribution, crucial for statistical models like Monte Carlo simulations.
When to Use Simple Returns?
Code Highlights
-
Python – Reading Financial Data From Internet – Useful code
Reading financial data from the internet is sometimes challenging. In this short article with two python snippets, I will show how to read it from Wikipedia and from and from API, delivering in JSON format:
This is how the financial json data from the api looks like.
Reading the data from the API is actually not tough, if you have experience reading JSON, with nested lists. If not, simply try with trial and error and eventually you will succeed:
import numpy as np
import pandas as pd
import yfinance as yf
import requests
from datetime import datetime
def get_nasdaq_tickers_from_api():
headers={
“User-Agent”:“Mozilla/5.0”,
“Accept”:“application/json”
}
url = “https://api.nasdaq.com/api/quote/list-type/nasdaq100”
response = requests.get(url, headers=headers, timeout=10)
tickers = [item[“symbol”] for item in data[“data”][“data”][“rows”]]
return tickers
With the reading from wikipedia, it is actually even easier – the site works flawlessly with pandas, and if you count the tables correctly, you would get what you want:
def get_nasdaq_tickers_from_wikipedia():
wiki_url = “https://en.wikipedia.org/wiki/Nasdaq-100”
tables = pd.read_html(wiki_url)
components_table=tables[4]
tickers=components_table[“Ticker”].tolist()
return tickers
You might want to combine both sources, just in case:
tickers = list(set(get_wiki_tickers() + get_nasdaq_api_tickers()))
The YouTube video for this article is here:
https://www.youtube.com/watch?v=Uj95BgimHa8
The GitHub code is there – GitHubEnjoy it! 🙂
-
Python – Simple Stock Analysis with yfinance – Useful code
Sometimes, the graphs of stocks are useful. Sometimes these are not. In general, do your own research, none of this is financial advice.
And while doing that, if you want to analyze stocks with just a few lines of python, this article might help? This simple yet powerful script helps you spot potential buy and sell opportunities for Apple (AAPL) using two classic technical indicators: moving averages and RSI.
Understanding the Strategy
1. SMA Crossover: The Trend Following Signal
The script first calculates two Simple Moving Averages (SMA):
The crossover strategy is simple:
This works because moving averages smooth out price noise, helping identify the overall trend direction.
2. RSI: The Overbought/Oversold Indicator
The Relative Strength Index (RSI) measures whether a stock is overbought or oversold:
By combining SMA crossovers (trend confirmation) and RSI extremes (timing), we get stronger signals.
This plot is generated with less than 40 lines of python code
The code looks like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
# Get data
ticker = “AAPL”
df = yf.download(ticker, start=“2024-01-01”, end=“2025-01-01”)
sns.set_style(“whitegrid”)
# Moving Averages
df[‘SMA_20’] = df[‘Close’].rolling(20).mean()
df[‘SMA_50’] = df[‘Close’].rolling(50).mean()
# RSI Calculation
delta = df[‘Close’].diff(1)
gain = delta.clip(lower=0)
loss = –delta.clip(upper=0)
rs = gain.rolling(14).mean() / loss.rolling(14).mean()
df[‘RSI’] = 100 – (100 / (1 + rs))
# Signals
df[‘Buy’] = (df[‘SMA_20’] > df[‘SMA_50’]) & (df[‘RSI’] < 30)
df[‘Sell’] = (df[‘SMA_20’] < df[‘SMA_50’]) & (df[‘RSI’] > 70)
# Plot
plt.figure(figsize=(12,6))
plt.plot(df[‘Close’], label=‘Price’)
plt.plot(df[‘SMA_20’], label=’20-day SMA’)
plt.plot(df[‘SMA_50’], label=’50-day SMA’)
plt.scatter(df.index[df[‘Buy’]], df[‘Close’][df[‘Buy’]], color=‘green’, marker=‘^’, label=‘Buy’)
plt.scatter(df.index[df[‘Sell’]], df[‘Close’][df[‘Sell’]], color=‘red’, marker=‘v’, label=‘Sell’)
plt.title(f‘{ticker} Combined Trading Signals (SMA + RSI)’)
plt.legend()
plt.show()
The code above, but in way more details is explained in the YT video below:
-
Calling AWS Bedrock from code. Using Python in a Jupyter notebook | by Thomas Reid
Image by Author Many of you will know that every man and his dog are producing AI products or LLM’s and integrating them with their products. Not surprisingly AWS — the biggest cloud services provider — is also getting in on the act.
What is bedrock?
Its AI offering is called Bedrock and the following blurb from it’s website describes what Bedrock is.
Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) from leading AI companies like AI21 Labs, Anthropic, Cohere, Meta, Stability AI, and Amazon via a single API, along with a broad set of capabilities you need to build generative AI applications, simplifying development while maintaining privacy and security. With Amazon Bedrock’s comprehensive capabilities, you can easily experiment with a variety of top FMs, privately customize them with your data using techniques such as fine-tuning and retrieval augmented generation (RAG), and create managed agents that execute complex business tasks — from booking travel and processing insurance claims to creating ad campaigns and managing inventory — all without writing any code. Since Amazon Bedrock is serverless, you don’t have to manage any infrastructure, and you can securely integrate and deploy generative AI…
-
Write and Test Code Instantly With an Online Python Editor
Write and Test Code Instantly With an Online Python Editor
Source link -
Build a Python Site Connectivity Checker App with PyQt (Step-by-Step)
Build a Python Site Connectivity Checker App with PyQt (Step-by-Step)
Source link -
Build a Python Network Speed Test App with PyQt (Step-by-Step)
Build a Python Network Speed Test App with PyQt (Step-by-Step)
Source link