Introduction
In this tutorial, we'll explore how to analyze stock market data using Python to understand the factors behind Intel's remarkable 490% stock surge. We'll build a practical tool that fetches financial data, performs basic analysis, and visualizes trends. This intermediate-level tutorial assumes you have basic Python knowledge and understand financial concepts like stock prices, returns, and volatility.
Prerequisites
- Python 3.7 or higher installed
- Basic understanding of financial markets and stock analysis
- Installed Python packages: yfinance, pandas, matplotlib, numpy
- Internet connection for data fetching
Step-by-Step Instructions
1. Install Required Python Packages
First, we need to install the necessary libraries for financial data analysis. The yfinance package allows us to fetch stock data directly from Yahoo Finance, while pandas handles data manipulation and matplotlib creates visualizations.
pip install yfinance pandas matplotlib numpy
Why this step: These packages form the foundation of our financial analysis toolkit. yfinance is essential for accessing real stock data, while pandas and matplotlib provide the data handling and visualization capabilities we need.
2. Import Libraries and Set Up Data Fetching
Now we'll create our Python script and import the required modules. We'll also set up our Intel stock symbol for analysis.
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Set up the stock symbol
symbol = 'INTC'
stock = yf.Ticker(symbol)
print(f"Analyzing {symbol} stock data")
Why this step: Importing the libraries is crucial as they provide all the functionality we'll need for data fetching, manipulation, and visualization. The yfinance library is particularly important as it's our gateway to real-time financial data.
3. Fetch Historical Stock Data
We'll retrieve Intel's historical stock data for the past year to analyze the performance that led to the 490% increase.
# Fetch historical data for the past year
hist_data = stock.history(period='1y')
print("Historical data retrieved successfully")
print(hist_data.head())
Why this step: Understanding the raw data is fundamental. The period='1y' parameter ensures we get exactly one year of data, which aligns with the news article's timeframe of the stock's remarkable rise.
4. Calculate Key Performance Metrics
Let's calculate the percentage change and other important metrics to quantify Intel's performance.
# Calculate percentage change
initial_price = hist_data['Close'].iloc[0]
final_price = hist_data['Close'].iloc[-1]
percentage_change = ((final_price - initial_price) / initial_price) * 100
print(f"Initial price: ${initial_price:.2f}")
print(f"Final price: ${final_price:.2f}")
print(f"Percentage change: {percentage_change:.2f}%")
# Calculate daily returns
hist_data['Daily_Return'] = hist_data['Close'].pct_change()
print("\nDaily returns calculated")
Why this step: Calculating percentage change directly shows the dramatic 490% increase mentioned in the article. Daily returns help us understand volatility and risk associated with the stock.
5. Create Visualizations
Visualizing the data helps us understand the stock's performance trajectory. We'll create two plots: one for price movement and one for daily returns.
# Create the first plot - Price movement
plt.figure(figsize=(12, 6))
plt.plot(hist_data.index, hist_data['Close'], label='Intel Stock Price')
plt.title('Intel (INTC) Stock Price Performance - Last 12 Months')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
# Create the second plot - Daily returns
plt.figure(figsize=(12, 6))
plt.plot(hist_data.index, hist_data['Daily_Return'], label='Daily Returns', color='orange')
plt.axhline(y=0, color='black', linestyle='-', alpha=0.5)
plt.title('Intel (INTC) Daily Returns - Last 12 Months')
plt.xlabel('Date')
plt.ylabel('Daily Return')
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Why this step: Visualizations make complex data understandable. The price chart shows the dramatic upward trend, while the returns chart reveals volatility patterns that investors should consider.
6. Analyze Volatility and Risk Metrics
Understanding volatility is crucial for assessing investment risk. Let's calculate standard deviation and other risk measures.
# Calculate volatility (standard deviation of daily returns)
volatility = hist_data['Daily_Return'].std()
annualized_volatility = volatility * np.sqrt(252) # 252 trading days in a year
print(f"Daily Volatility: {volatility:.4f} ({volatility*100:.2f}%)")
print(f"Annualized Volatility: {annualized_volatility:.4f} ({annualized_volatility*100:.2f}%)")
# Calculate Sharpe Ratio (assuming 2% risk-free rate)
risk_free_rate = 0.02
sharpe_ratio = (percentage_change/100 - risk_free_rate) / annualized_volatility
print(f"Sharpe Ratio: {sharpe_ratio:.4f}")
Why this step: Volatility measures risk. The Sharpe ratio helps investors understand the return relative to risk, which is crucial when analyzing a stock with such dramatic price movements.
7. Export Analysis Results
Finally, let's save our analysis to a CSV file for further examination or sharing with others.
# Save the complete dataset with our calculated metrics
hist_data.to_csv('intel_stock_analysis.csv')
print("Analysis saved to intel_stock_analysis.csv")
# Create a summary report
summary = {
'Symbol': symbol,
'Initial_Price': initial_price,
'Final_Price': final_price,
'Percentage_Change': percentage_change,
'Annualized_Volatility': annualized_volatility,
'Sharpe_Ratio': sharpe_ratio
}
summary_df = pd.DataFrame([summary])
summary_df.to_csv('intel_stock_summary.csv', index=False)
print("Summary report saved to intel_stock_summary.csv")
Why this step: Saving our work ensures we can revisit and share our findings. This is particularly important for financial analysis where documenting methodology and results is crucial for decision-making.
Summary
In this tutorial, we've built a practical stock analysis tool that examines Intel's remarkable 490% stock surge over the past year. We've learned how to fetch financial data using yfinance, calculate key performance metrics like percentage change and volatility, create visualizations to understand price trends, and compute risk-adjusted returns using the Sharpe ratio. This hands-on approach gives you the skills to analyze any stock's performance and understand the factors behind market movements, including the complex dynamics behind Intel's impressive turnaround story.
The techniques we've covered are fundamental to financial analysis and can be extended to analyze other stocks or investment opportunities. Remember that while stock performance can be dramatic, understanding risk metrics like volatility and Sharpe ratios is essential for making informed investment decisions.



