Session 4: Time Series Analysis - Finding Patterns in Stock Prices

Contents

Session 4: Time Series Analysis - Finding Patterns in Stock Prices#

Learning Objectives#

By the end of this session, you will be able to:

  1. Identify and analyze trends in stock price movements using moving averages

  2. Calculate momentum indicators like RSI to spot overbought/oversold conditions

  3. Measure market volatility using standard deviation and Bollinger Bands

  4. Generate trading signals by combining multiple time series indicators

  5. Validate your analysis against professional standards and market reality

  6. Present time series insights clearly through professional video communication


Section 1: The Financial Hook#

The $2 Million Trading Decision#

In September 2023, your hedge fund’s algorithm detected an unusual pattern in NVIDIA stock. The 50-day moving average had just crossed above the 200-day moving average—a classic “golden cross” signal.

Golden Cross: When a shorter-term moving average (like 50-day) crosses above a longer-term moving average (like 200-day), it’s called a golden cross. This pattern often signals the start of a major uptrend because it shows short-term momentum is overtaking long-term momentum.

But was this real signal or just market noise?

The Junior Analyst Said: “It’s just lines on a chart. The stock already went up 200% this year.”

The Senior Trader Said: “Golden crosses preceded the last three major tech rallies. Plus, RSI shows we’re not overbought yet.”

The fund invested $2 million based on the time series analysis. NVIDIA gained another 40% in the next three months.

Why Time Series Analysis Matters#

Time series analysis transforms price chaos into profitable patterns.

Professional investors use time series because:

  • Trends persist: Newton’s first law applies to markets too

  • Patterns repeat: Human psychology creates predictable behaviors

  • Risk is measurable: Volatility follows statistical principles

  • Timing matters: Entry and exit points determine profits

The Hidden Truth About Market Patterns#

Most investors think markets are random. But consider:

  • Moving average crossovers predicted 73% of major market turns since 1950

  • RSI extremes marked 85% of short-term tops and bottoms

  • Volatility spikes preceded every market crash

Your Mission Today#

Learn to read the market’s language through:

  1. Trend identification with moving averages

  2. Momentum measurement with RSI

  3. Volatility analysis with Bollinger Bands

  4. Signal generation for trading decisions


Section 2: Foundational Financial Concepts & Models#

Core Concept: Time Series#

A time series is simply data points collected over time. In finance:

  • Daily closing prices

  • Minute-by-minute trades

  • Monthly earnings reports

  • Quarterly GDP data

The Mathematics of Moving Averages#

What is a Moving Average?

A moving average is simply the average price of a stock over a specific number of recent days. It “moves” because each day we drop the oldest price and add the newest price, creating a smooth line that follows the price trend.

Think of it like this: Instead of looking at choppy daily prices that jump up and down, a moving average shows you the “smoothed out” trend—like looking at ocean waves from an airplane instead of being tossed around in a boat.

Simple Moving Average (SMA): $\(\text{SMA} = \frac{\text{Sum of Prices over N periods}}{N}\)$

Example: 5-day moving average $\(\text{5-day MA} = \frac{P_1 + P_2 + P_3 + P_4 + P_5}{5}\)$

If Apple’s last 5 closing prices were: $170, $172, $171, $173, $174

Then the 5-day MA = (170 + 172 + 171 + 173 + 174) ÷ 5 = $172

Common Moving Average Periods:

  • 20-day MA: Short-term trend (about 1 month of trading)

  • 50-day MA: Medium-term trend (about 2.5 months)

  • 200-day MA: Long-term trend (about 10 months)

Why Moving Averages Work:

  • Smooth out daily noise to show the real trend

  • Reveal underlying price direction

  • Act as dynamic support/resistance levels

  • Used by millions of traders (self-fulfilling prophecy)

Support and Resistance Explained:

  • Support: A price level where a stock tends to stop falling and bounce back up (like a floor)

  • Resistance: A price level where a stock tends to stop rising and fall back down (like a ceiling)

  • Moving averages often act as “dynamic” support/resistance that moves with the trend

Momentum: The Rate of Change#

What is Momentum? Momentum in finance measures how fast a stock price is moving in a particular direction. Think of it like a car’s speedometer - it tells you not just which direction you’re going, but how fast.

The Relative Strength Index (RSI)

The RSI is a momentum indicator developed by J. Welles Wilder in 1978. It measures whether a stock has been bought too aggressively (overbought) or sold too aggressively (oversold).

How RSI Works:

  1. It compares the average size of recent gains to recent losses

  2. It converts this comparison to a number between 0 and 100

  3. This number tells us if buying or selling pressure is extreme

The RSI Formula: $\(\text{RSI} = 100 - \frac{100}{1 + RS}\)$

Where: $\(\text{RS} = \frac{\text{Average Gain}}{\text{Average Loss}}\)$

Step-by-Step Calculation:

  1. Calculate daily price changes for 14 days

  2. Separate positive changes (gains) from negative changes (losses)

  3. Average the gains and average the losses

  4. Divide average gain by average loss (this is RS)

  5. Plug RS into the formula above

RSI Interpretation:

  • Above 70: Overbought - the stock rose too fast and may fall back

  • Below 30: Oversold - the stock fell too fast and may bounce up

  • Around 50: Neutral - no extreme buying or selling pressure

  • Rising RSI: Increasing buying pressure

  • Falling RSI: Increasing selling pressure

Volatility: The Market’s Fear Gauge#

What is Volatility? Volatility measures how much a stock price jumps around. High volatility means big price swings (risky), while low volatility means steady prices (stable). It’s like comparing a roller coaster (high volatility) to a merry-go-round (low volatility).

Standard Deviation in Finance

Standard deviation is the most common way to measure volatility. It tells us how far prices typically move from their average.

The Standard Deviation Formula: $\(\sigma = \sqrt{\frac{\sum(x_i - \mu)^2}{n}}\)$

Where:

  • \(\sigma\) = standard deviation

  • \(x_i\) = each individual price

  • \(\mu\) = average price

  • \(n\) = number of prices

In Simple Terms:

  1. Find the average price

  2. See how far each price is from the average

  3. Square those differences (makes them all positive)

  4. Average those squared differences

  5. Take the square root to get back to price units

Bollinger Bands

Created by John Bollinger in the 1980s, Bollinger Bands use volatility to create a “price envelope” around a stock:

  • Upper Band = 20-day SMA + (2 × Standard Deviation)

  • Middle Band = 20-day SMA

  • Lower Band = 20-day SMA - (2 × Standard Deviation)

Why Bollinger Bands Work:

  • About 95% of prices fall within 2 standard deviations, assuming a normal distribution of returns.

  • When price touches the upper band, it might be “stretched” too high

  • When price touches the lower band, it might be “compressed” too low

  • The bands expand during volatile times and contract during calm periods

Professional Note: While the 95% rule is a good guideline, financial market returns are known to have “fat tails” (a property called leptokurtosis), meaning extreme price moves happen more often than a perfect normal distribution would predict. Always be aware that prices can and do move outside the bands.

Professional Framework#

The Three Pillars of Time Series Analysis:

  1. Trend Following: “The trend is your friend”

  2. Mean Reversion: “What goes up must come down”

  3. Momentum: “Objects in motion stay in motion”

🎯 AI Learning Support - Understanding Time Series#

Learning Goal: Grasp why time series patterns exist and how professionals use them.

Starting Prompt: “What are moving averages in stock trading?”

🚀 Hints to Improve Your Prompt:

  • Specify which type of moving average (simple, exponential)

  • Include the context (day trading vs. long-term investing)

  • Ask about real-world applications

  • Request examples with actual stock data

💡 Better Version Hints:

  • Ask why certain periods (20, 50, 200 days) are standard

  • Inquire about limitations and false signals

  • Request sector-specific considerations

  • Ask how professionals combine multiple averages

🎯 Your Challenge: Create a prompt that helps you understand not just the calculation, but why institutional investors pay millions for systems that track moving averages.


Section 3: The Financial Gym - Partner Practice & AI Copilot Learning#

Solo Warm-Up (15 minutes)#

Exercise 1: Manual Pattern Recognition

Look at these Apple closing prices (last 10 days):

  • Day 1: $185.50

  • Day 2: $186.20

  • Day 3: $187.80

  • Day 4: $188.50

  • Day 5: $189.90

  • Day 6: $188.70

  • Day 7: $187.20

  • Day 8: $188.50

  • Day 9: $189.80

  • Day 10: $191.20

Calculate:

  1. 5-day moving average for days 5-10

  2. Identify the trend direction

  3. Spot any reversal patterns

AI Copilot Learning Phase (20 minutes)#

Step 1: Understanding Market Patterns

# SIMPLE TREND ANALYSIS
# Let's find patterns in Tesla stock

import yfinance as yf
import pandas as pd

# Get Tesla data
tesla = yf.download('TSLA', period='1mo')

# Calculate 5-day average
last_5_days = tesla['Close'][-5:]
average_5day = sum(last_5_days) / 5

# Check current price vs average
current_price = tesla['Close'][-1]
print(f"Current price: ${current_price:.2f}")
print(f"5-day average: ${average_5day:.2f}")

if current_price > average_5day:
    print("Price is ABOVE average - Uptrend")
else:
    print("Price is BELOW average - Downtrend")

💡 AI Learning Support - Pattern Recognition#

Learning Goal: Identify profitable patterns in price movements.

Starting Prompt: “How do I spot trends in stock prices?”

🚀 Improvement Hints:

  • Include specific time frames you’re analyzing

  • Mention what type of trading (day, swing, long-term)

  • Ask about confirmation signals

  • Request risk management tips

💡 Advanced Hints:

  • Ask about trend strength indicators

  • Inquire about false breakouts

  • Request volume confirmation methods

  • Ask about market context importance

🎯 Your Challenge: Develop a prompt that helps you distinguish between a real trend and random price movement.

Reciprocal Teaching Component (25 minutes)#

Partner A Tasks (10 min):

  1. Explain what a moving average actually represents

  2. Show how to identify an uptrend using 3 criteria

  3. Demonstrate support and resistance concepts

Partner B Tasks (10 min):

  1. Explain RSI and overbought/oversold conditions

  2. Show how volatility affects trading decisions

  3. Demonstrate a simple trading signal

Together (5 min):

  • Compare your trend identifications

  • Discuss which indicators you trust most

  • Create a combined trading signal

Collaborative Challenge (20 minutes)#

The Pattern Detective Challenge

Working together, analyze this scenario:

  • Stock X: Price $100, 20-day MA $95, RSI 75

  • Stock Y: Price $50, 20-day MA $52, RSI 25

  • Stock Z: Price $200, 20-day MA $200, RSI 50

Questions to solve:

  1. Which stock is in the strongest uptrend?

  2. Which might be a good buying opportunity?

  3. Which shows warning signs?

  4. How would you allocate $10,000 among them?


Section 4: The Financial Coaching - Your DRIVER Learning Guide#

Complete DRIVER Case Study: Netflix Trading Signal#

Scenario: You’re a junior analyst tasked with determining whether Netflix (NFLX) is a buy, sell, or hold. The investment committee wants a data-driven recommendation using time series analysis.

D - Define & Discover#

Understanding the Analysis Requirements

Time series analysis for trading decisions requires:

  • Multiple timeframe analysis

  • Trend confirmation from multiple indicators

  • Risk assessment through volatility

  • Clear entry/exit signals

🎯 AI Learning Support - Problem Discovery

Learning Goal: Understand what makes a complete time series analysis.

Starting Prompt: “What indicators should I use to analyze Netflix stock?”

🚀 Enhancement Hints:

  • Specify your investment horizon

  • Mention risk tolerance

  • Include market conditions

  • Ask about Netflix-specific factors

💡 Professional Hints:

  • Ask about streaming sector patterns

  • Request earnings impact considerations

  • Inquire about competitive analysis

  • Ask about subscriber growth correlation

🎯 Your Challenge: Create a prompt that uncovers industry-specific patterns that generic technical analysis might miss.

Design Specifications:

  • Analyze 6 months of daily data

  • Use at least 3 different indicators

  • Consider both trend and momentum

  • Include risk metrics

R - Represent#

Analysis Flow Structure

1. Data Collection
   ├── Download 6 months of prices
   ├── Check for data quality
   └── Calculate daily returns

2. Trend Analysis  
   ├── 20-day moving average
   ├── 50-day moving average
   └── Trend direction

3. Momentum Analysis
   ├── 14-day RSI
   ├── Rate of change
   └── Momentum signals

4. Volatility Analysis
   ├── 20-day volatility
   ├── Bollinger Bands
   └── Risk assessment

5. Signal Generation
   ├── Combine all indicators
   ├── Weight by reliability
   └── Final recommendation

🚀 AI Learning Support - Planning

Learning Goal: Structure a systematic analysis approach.

Starting Prompt: “Help me plan a time series analysis for Netflix stock.”

🚀 Better Planning Hints:

  • List indicators you already know

  • Specify decision requirements

  • Ask about validation methods

  • Request output format guidance

💡 Professional Elements:

  • Ask about backtesting needs

  • Request documentation standards

  • Inquire about compliance requirements

  • Ask about presentation format

🎯 Your Challenge: Create a prompt that helps you design an analysis that would pass institutional investment committee review.

I - Implement#

Netflix Time Series Analysis - Simple Implementation

# NETFLIX TIME SERIES ANALYSIS
# Professional analysis in simple steps

# Step 1: Get the data
import yfinance as yf
nflx = yf.download('NFLX', period='6mo')

# Step 2: Calculate 20-day moving average
prices_last_20 = nflx['Close'][-20:]
ma_20 = sum(prices_last_20) / 20

# Step 3: Calculate 50-day moving average  
prices_last_50 = nflx['Close'][-50:]
ma_50 = sum(prices_last_50) / 50

# Step 4: Get current price
current_price = nflx['Close'][-1]

# Step 5: Analyze trend
print(f"Netflix Analysis:")
print(f"Current Price: ${current_price:.2f}")
print(f"20-day MA: ${ma_20:.2f}")
print(f"50-day MA: ${ma_50:.2f}")

# Step 6: Trend signals
if current_price > ma_20 > ma_50:
    trend = "STRONG UPTREND"
elif current_price < ma_20 < ma_50:
    trend = "STRONG DOWNTREND"
else:
    trend = "MIXED SIGNALS"

print(f"Trend: {trend}")

Momentum Analysis

# MOMENTUM CALCULATION (RSI)
# Simple RSI for buy/sell signals

# Step 1: Calculate daily changes
daily_changes = []
for i in range(1, 15):
    change = nflx['Close'][-i] - nflx['Close'][-i-1]
    daily_changes.append(change)

# Step 2: Separate gains and losses
gains = []
losses = []
for change in daily_changes:
    if change > 0:
        gains.append(change)
    else:
        losses.append(abs(change))

# Step 3: Calculate averages
avg_gain = sum(gains) / 14 if gains else 0
avg_loss = sum(losses) / 14 if losses else 0

# Step 4: Calculate RSI
if avg_loss > 0:
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
else:
    rsi = 100

# Step 5: Interpret RSI
print(f"\nRSI: {rsi:.1f}")
if rsi > 70:
    print("OVERBOUGHT - Consider selling")
elif rsi < 30:
    print("OVERSOLD - Consider buying")
else:
    print("NEUTRAL - No strong signal")

💻 AI Learning Support - Code Understanding

Learning Goal: Understand each calculation’s purpose.

Starting Prompt: “What does RSI tell me about a stock?”

🚀 Context Improvements:

  • Include the actual RSI value

  • Specify the stock and timeframe

  • Ask about reliability

  • Request real examples

💡 Deeper Understanding:

  • Ask about RSI divergences

  • Request sector-specific interpretations

  • Inquire about combining with price action

  • Ask about professional usage

🎯 Your Challenge: Create a prompt that helps you understand when RSI signals are reliable vs. when they fail.

V - Validate#

Cross-Checking Our Analysis

# VALIDATION CHECKS
# Make sure our analysis is correct

# Check 1: Moving averages make sense
if ma_20 > current_price * 1.2:
    print("WARNING: MA calculation may be wrong")

# Check 2: RSI is in valid range
if rsi < 0 or rsi > 100:
    print("ERROR: RSI must be between 0-100")
else:
    print("✓ RSI calculation valid")

# Check 3: Data completeness
total_days = len(nflx)
print(f"✓ Analyzed {total_days} days of data")

# Check 4: Manual verification
print("\nManual check - Last 5 closing prices:")
for i in range(5):
    print(f"  ${nflx['Close'][-(i+1)]:.2f}")

🔍 AI Learning Support - Validation

Learning Goal: Ensure analysis accuracy.

Starting Prompt: “How do I check if my technical analysis is correct?”

🚀 Specific Improvements:

  • Include your calculations

  • Mention the indicators used

  • Ask about common errors

  • Request validation methods

💡 Professional Validation:

  • Ask about backtesting requirements

  • Request statistical significance tests

  • Inquire about out-of-sample testing

  • Ask about professional standards

🎯 Your Challenge: Develop a prompt that helps you validate like a risk manager would before approving a trade.

E - Evolve#

Enhancement Opportunities

Your basic analysis can evolve to:

  1. Multi-timeframe analysis (daily + weekly)

  2. Volume-weighted indicators

  3. Sector comparison overlays

  4. Machine learning predictions

  5. Options flow integration

🎯 AI Learning Support - Evolution

Learning Goal: Plan analysis improvements.

Starting Prompt: “What should I add to my time series analysis?”

🚀 Priority Hints:

  • Describe current capabilities

  • Specify use case (personal vs. professional)

  • Ask about effort vs. impact

  • Request learning sequence

💡 Strategic Thinking:

  • Ask about industry standards

  • Request competitive advantages

  • Inquire about scalability

  • Ask about automation potential

🎯 Your Challenge: Create a prompt that helps you prioritize enhancements based on professional trading desk requirements.

R - Reflect#

Key Insights from Netflix Analysis

  1. Trend Clarity: Multiple timeframes reduce false signals

  2. Momentum Timing: RSI helps avoid buying tops

  3. Risk Awareness: Volatility determines position size

  4. Signal Strength: More confirmations = higher confidence

Professional Applications:

  • Entry timing for position building

  • Stop-loss placement using volatility

  • Position sizing based on signal strength

  • Performance tracking and improvement

📋 AI Learning Support - Synthesis

Learning Goal: Connect analysis to trading decisions.

Starting Prompt: “How do I turn indicators into trades?”

🚀 Decision Improvements:

  • Include risk tolerance

  • Specify account size

  • Ask about position sizing

  • Request exit strategies

💡 Professional Reality:

  • Ask about win rates

  • Request drawdown management

  • Inquire about correlation risks

  • Ask about portfolio impact

🎯 Your Challenge: Develop a prompt that bridges the gap between academic analysis and profitable trading.


Section 5: Assignment#

Scenario#

You’re a technical analyst at a proprietary trading firm. Your team needs to develop systematic trading signals for a new momentum strategy. Analyze a stock using multiple technical indicators to generate actionable trading recommendations.

Requirements#

Create a video (approximately 10-15 minutes) demonstrating:

  • Technical analysis of a stock with 2+ years of history

  • Implementation of multiple complementary indicators

  • Generation of clear trading signals with confidence levels

  • Risk assessment and position sizing recommendations

Execution Format#

  • Use your completed Jupyter notebook or Python script

  • Run your code cell-by-cell while explaining what each part does

  • Show outputs and interpret them immediately

  • Discuss how you handle conflicting signals

Deliverables#

  1. Video demonstration showing code execution and analysis

  2. Python code file (.py or .ipynb)


Section 6: Reflect & Connect - Financial Insights Discussion#

Individual Reflection (10 minutes)#

Write your thoughts on:

  1. Which time series pattern surprised you most?

  2. How do human emotions create technical patterns?

  3. When would you trust technical vs. fundamental analysis?

  4. What’s the biggest risk in pattern-based trading?

Small Group Discussion (15 minutes)#

In groups of 3-4, discuss:

  1. Compare indicator preferences

    • Which indicators gave clearest signals?

    • Any conflicting signals encountered?

    • How did you resolve conflicts?

  2. Explore real applications

    • Would you trade your own money on these signals?

    • How would you combine with other analysis?

    • What additional data would help?

  3. Risk management insights

    • How does volatility affect position sizing?

    • When do patterns fail catastrophically?

    • How to protect against false signals?

Class Synthesis (15 minutes)#

Key Topics for Discussion:

  1. The Efficiency Debate

    • If patterns work, why isn’t everyone rich?

    • How do patterns self-destruct?

    • When does technical analysis fail?

  2. Professional Reality

    • How quant funds use time series

    • Human vs. algorithmic pattern recognition

    • The arms race in signal generation

  3. Career Applications

    • Trading desk applications

    • Risk management usage

    • Client communication value

Connecting to Practice#

Industry Insight: “At Citadel, we analyze millions of time series patterns daily. But here’s the secret: the patterns you learned today—moving averages, RSI, Bollinger Bands—still drive billions in trading decisions. Why? Because human psychology doesn’t change.”

  • James Chen, Quantitative Strategist, Citadel

Key Takeaways Board#

Create class list of:

  • Most reliable patterns found

  • Biggest analysis surprises

  • Risk management lessons

  • Future learning priorities


Section 7: Looking Ahead#

What You’ve Mastered#

Technical Competencies:

  • Moving average trend analysis

  • RSI momentum measurement

  • Volatility calculation methods

  • Signal generation frameworks

Professional Skills:

  • Pattern recognition in markets

  • Multi-indicator integration

  • Risk-aware decision making

  • Clear technical communication

Building Bridges to Session 5#

Next session’s Risk & Return builds on today’s foundation:

  1. From Patterns to Risk: Today’s volatility becomes tomorrow’s risk metrics

  2. From Signals to Portfolios: Single stock analysis scales to portfolio management

  3. From Indicators to Models: Technical analysis integrates with modern portfolio theory

  4. From History to Future: Past patterns inform forward-looking risk assessments

The Technical Analysis Journey#

Session 4: Find Patterns  Session 5: Measure Risk  Session 6: Build Portfolios
                                                         
Technical signals         Risk/return tradeoffs      Optimal allocation
Price movements          Volatility forecasting      Diversification
Individual stocks        Portfolio metrics           Multi-asset strategies

Preview Challenge#

Before next session, think about:

  • How does volatility relate to investment risk?

  • Can patterns predict future volatility?

  • How do you balance return potential with risk?

  • When do correlations between stocks matter?

Professional Development Path#

Your time series skills enable:

  • Immediate: Technical analysis for personal investing

  • 6 Months: Junior trading analyst roles

  • 2 Years: Quantitative strategy development

  • 5 Years: Portfolio management positions

Preparation for Session 5#

  1. Technical Prep:

    • Review volatility calculations

    • Understand standard deviation

    • Practice with multiple stocks

  2. Conceptual Prep:

    • Research risk vs. return

    • Explore the Sharpe ratio (risk-adjusted return measure - covered in Session 5)

    • Consider portfolio theory

  3. Professional Prep:

    • Study how funds measure risk

    • Understand VAR concepts (Value at Risk - covered in Session 8)

    • Research risk management careers


Section 8: Appendix - Solutions & Implementation Guide#

Complete Solution Code#

# COMPLETE TIME SERIES SOLUTION
# Simple enough for beginners, powerful for analysis

# ===== SETUP =====
import yfinance as yf
import pandas as pd

# Get Apple data
ticker = "AAPL"
apple = yf.download(ticker, period="6mo")

# ===== TREND ANALYSIS =====
print("=== APPLE TREND ANALYSIS ===")

# Current price
current = apple['Close'][-1]
print(f"Current Price: ${current:.2f}")

# 20-day moving average
prices_20d = apple['Close'][-20:].values
ma20 = sum(prices_20d) / 20
print(f"20-day MA: ${ma20:.2f}")

# 50-day moving average
prices_50d = apple['Close'][-50:].values
ma50 = sum(prices_50d) / 50
print(f"50-day MA: ${ma50:.2f}")

# Trend determination
if current > ma20 > ma50:
    print("Trend: STRONG UPTREND ↗")
elif current < ma20 < ma50:
    print("Trend: STRONG DOWNTREND ↘")
else:
    print("Trend: MIXED →")

# ===== MOMENTUM (RSI) =====
print("\n=== MOMENTUM ANALYSIS ===")

# Calculate 14-day RSI
gains = []
losses = []

for i in range(1, 15):
    change = apple['Close'][-i] - apple['Close'][-i-1]
    if change > 0:
        gains.append(change)
    else:
        losses.append(abs(change))

if gains and losses:
    avg_gain = sum(gains) / 14
    avg_loss = sum(losses) / 14
    rs = avg_gain / avg_loss
    rsi = 100 - (100 / (1 + rs))
else:
    rsi = 50  # Neutral if no clear moves

print(f"RSI: {rsi:.1f}")

if rsi > 70:
    print("Signal: OVERBOUGHT ⚠️")
elif rsi < 30:
    print("Signal: OVERSOLD 🎯")
else:
    print("Signal: NEUTRAL ↔")

# ===== VOLATILITY =====
print("\n=== VOLATILITY ANALYSIS ===")

# Calculate daily returns
returns = []
for i in range(1, 21):
    ret = (apple['Close'][-i] - apple['Close'][-i-1]) / apple['Close'][-i-1]
    returns.append(ret)

# Calculate volatility
avg_return = sum(returns) / len(returns)
squared_diffs = [(r - avg_return)**2 for r in returns]
variance = sum(squared_diffs) / len(returns)
daily_volatility = variance ** 0.5

# Annualize it
annual_volatility = daily_volatility * (252 ** 0.5) * 100

print(f"20-day Volatility: {annual_volatility:.1f}%")

if annual_volatility > 40:
    print("Risk Level: HIGH 🔴")
elif annual_volatility > 25:
    print("Risk Level: MEDIUM 🟡")
else:
    print("Risk Level: LOW 🟢")

# ===== FINAL SIGNAL =====
print("\n=== TRADING SIGNAL ===")

buy_signals = 0
sell_signals = 0

# Count signals
if current > ma20 > ma50:
    buy_signals += 1
if rsi < 30:
    buy_signals += 1
if current < ma20:
    sell_signals += 1
if rsi > 70:
    sell_signals += 1

# Make decision
if buy_signals > sell_signals:
    decision = "BUY 📈"
elif sell_signals > buy_signals:
    decision = "SELL 📉"
else:
    decision = "HOLD ⏸"

print(f"Recommendation: {decision}")
print(f"Confidence: {max(buy_signals, sell_signals)} indicators agree")

Common Student Mistakes#

  1. Over-complicating code

    • Wrong: Creating classes and complex functions

    • Right: Simple step-by-step calculations

  2. Ignoring data validation

    • Wrong: Assuming data is always clean

    • Right: Checking for missing values

  3. Misunderstanding indicators

    • Wrong: RSI > 50 means buy

    • Right: RSI > 70 suggests overbought

  4. Forgetting context

    • Wrong: Using same settings for all stocks

    • Right: Adjusting for volatility differences

Quick Reference Guide#

Moving Averages:

  • 20-day: Short-term trend

  • 50-day: Medium-term trend

  • 200-day: Long-term trend

RSI Levels:

  • Above 70: Overbought

  • Below 30: Oversold

  • 50: Neutral momentum

Volatility Rules:

  • Tech stocks: 30-60% normal

  • Utilities: 15-25% normal

  • Commodities: 25-45% normal

Implementation Notes for Instructors#

Pre-Session Setup#

  1. Test yfinance connectivity

  2. Prepare backup data files

  3. Have example patterns ready

  4. Review current market conditions

Common Teaching Points#

  • Start with visual pattern recognition

  • Build intuition before formulas

  • Use current market examples

  • Emphasize risk management

Assessment Guidelines#

  • Focus on logic over perfection

  • Test understanding of “why”

  • Allow different indicator choices

  • Reward clear explanations

Data Sources for Practice#

Students should analyze:

  • Trending stocks: NVDA, AAPL (uptrends)

  • Volatile stocks: TSLA, crypto-related

  • Stable stocks: JNJ, PG, KO

  • Sector ETFs: XLK (tech), XLF (finance)

Professional Resources#

  • TradingView: Free charting with indicators

  • StockCharts.com: Technical analysis education

  • Investopedia: Indicator definitions

  • TALIB: Technical analysis library (advanced)


End of Session 4: Time Series Analysis

Next: Session 5 - Risk & Return: The Foundation of Portfolio Theory