type
status
date
slug
summary
tags
category
icon
password
Objective:Lay the groundwork by introducing the stock market basics and getting familiar with handling financial data programmatically.
1.1 What is a Stock Market?
- Definition: A marketplace where buyers and sellers trade shares of public companies.
- Key Terms to Know:
- Stock: A representation of ownership in a company.
- Exchange: A platform where stocks are traded (e.g., NYSE, NASDAQ).
- Ticker Symbol: A unique identifier for a company's stock (e.g., AAPL for Apple).
- Price: Current value of a stock determined by supply and demand.
- Volume: Number of shares traded during a given period.
1.2 Types of Stock Data
- OHLC Data:
- Open: Price at market opening.
- High: Highest price of the stock during the day.
- Low: Lowest price of the stock during the day.
- Close: Price at market close.
- Volume: Total shares traded.
- Time Frames: Intraday, Daily, Weekly, Monthly.
1.3 Setting Up Python Environment
- Install Python and essential libraries:
1.4 Fetching and Handling Stock Data
- Using Yahoo Finance API (via
yfinance):
这里利用vscode的插件
DataWrangler 还能看到数据的分布情况
- Understanding the Output:
- The
dataDataFrame includes columns like Open, High, Low, Close, Volume.
1.5 Visualizing Stock Data
- Plotting Stock Prices:

如果想画常看到的蜡烛图(K线图):

Insights and Explanation
- Why Stock Data Matters:
Understanding stock data is the foundation of quantitative investment. It forms the input for all analysis and strategy development.
- Key Takeaway from Visualization:
A simple price plot provides a visual understanding of trends and fluctuations, which is the first step towards identifying patterns.
Extra Reading and Resources
- The Intelligent Investor by Benjamin Graham (Chapter 1-3).
- Introduction to Stock Markets (Investopedia).
- Official Yahoo Finance API Documentation.
- Python for Finance by Yves Hilpisch (Chapter 2).
课后作业
Homework for Unit 1: Introduction to Stock Markets and Data Handling
To reinforce the concepts and skills learned in Unit 1, here are the homework tasks:
Task 1: Explore Stock Market Basics
- Research and define the following terms:
- Market capitalization
- Dividend yield
- Price-to-Earnings (P/E) ratio
- Write a short paragraph explaining how stock prices are determined by supply and demand.
Task 2: Fetch and Analyze Stock Data
- Use the
yfinancelibrary to fetch daily stock data for any three companies of your choice over the past two years. Example companies: - Technology: Microsoft (MSFT)
- Healthcare: Johnson & Johnson (JNJ)
- Retail: Amazon (AMZN)
- Save the data for each company to a CSV file using the code
Task 3: Visualize Stock Trends
- Plot the closing prices of your chosen stocks on a single graph for comparison. Include:
- A legend indicating which line corresponds to each stock.
- Labels for the X-axis (Date) and Y-axis (Price in USD).
- Customize the plot by:
- Adding a title.
- Displaying a grid for better readability.
- Using different colors or line styles for each stock.
Task 4: Interpret Insights
Answer the following based on your visualizations:
- Which stock showed the most consistent upward trend over the selected period?
- Did any stock experience significant price volatility? What might have caused this (hint: research news or events)?
Task 5: Bonus Challenge (Optional)
- Calculate the daily percentage change for one of the stocks and add it as a new column to the DataFrame. Use the formula: Code example:
- Plot the daily percentage changes over time.
Submission Format
- Submit a Jupyter Notebook or Python script (.py file) with:
- Code implementations for each task.
- Plots and any additional visualizations.
- Written answers to the interpretive questions (Task 4).
Let me know if you need clarifications or additional hints for these tasks!
我自己做的答案:
Task 1: Explore Stock Market Basics
- Research and define the following terms:
- Market capitalization:公司的市值,等于当前股价 乘以 所有股数
- Dividend yield: 股息率,是衡量一家公司派发股息相对于其股价的比例,是投资者评估股票收益的重要指标之一。它用来表示每年从股息中获得的收益与股票价格的比值,公式如下:
- 高股息率通常意味着投资者可以从股息中获得较高的现金回报,但可能也反映公司增长潜力有限(因为它更倾向于派发利润而非再投资)。
- 低股息率可能意味着公司选择将更多利润用于再投资以推动增长,但现金回报较低。
例如,如果某公司股票的当前股价为50元,而每年每股派发股息为2元,那么其股息率为:4%。
意义:
- Price-to-Earnings (P/E) ratio: 市盈率,是衡量股票估值的一个重要指标,它表示投资者为每单位的公司盈利支付的价格。公式为:
- 我们在平时看一个股票中,常常还会有动态PE和静态PE两个指标,而且两个指标往往不相同。静态PE和动态PE的分母都是当前股价。静态PE的分子是过去12个月的每股收益。动态PE是分析师对未来12个月或者下一个财年的盈利预测数据下的预期每股收益。动态PE更适用于成长型公司,投资者希望通过它了解未来的增长空间。静态PE适合评价成熟公司,尤其是稳定盈利的企业,能直观反映当前估值水平。
- EPS的实际意义: 投资者通常会结合EPS和市盈率(P/E)等指标,评估股票是否值得购买。 在比较同行业公司时,EPS是判断盈利能力的一个核心维度,但需要结合公司规模、行业特性等综合分析,避免单纯依赖该指标。
- Write a short paragraph explaining how stock prices are determined by supply and demand.
在股市当中要明白一个道理,当前股价是由边际交易决定的。假设十万个人持有某股票C,该股票今天被100个人交易,这100个人认为这个股值多少钱,这个股今天就会在涨跌幅区间内按照这个价格去波动。然而一百人仅占十万人的千分之一。这就是边际交易决定当前股价。但是,长期来看,股价的走势和金额和筹码的供需程度决定的。当一个公司有很好的预期,业绩也很好时,更多人愿意买入,这个时候市场上卖出的少,买入的多,价格就容易被抬升。反之亦然。所以我们要坚持长期持有,买股票并不是买筹码,而是真正的参与到公司的成长中,获得成长的收益。虽说如此,我们仍然要给我们的买入价格留取足够的安全边际,价格不能太高。但是我们无法保证在买入的节点一定是一个底价,所以要分批建仓,按时间、按幅度动态调整。
记住,股价的波动不是亏损。要有耐心和公司成长
Task 2: Fetch and Analyze Stock Data
- Use the
yfinancelibrary to fetch daily stock data for any three companies of your choice over the past two years. Example companies: - Technology: Microsoft (MSFT)
- Healthcare: Johnson & Johnson (JNJ)
- Retail: Amazon (AMZN)
- Save the data for each company to a CSV file using the code:

Task 3: Visualize Stock Trends
- Plot the closing prices of your chosen stocks on a single graph for comparison. Include:
- A legend indicating which line corresponds to each stock.
- Labels for the X-axis (Date) and Y-axis (Price in USD).
- Adding a title.
- Displaying a grid for better readability.
- Using different colors or line styles for each stock.
Customize the plot by:

Task 4: Interpret Insights
Answer the following based on your visualizations:
- Which stock showed the most consistent upward trend over the selected period?
According to the calculation
we have
Ticker
AAPL 123.768456
GOOG 89.378853
MSFT 235.711731
Name: 2023-01-03 00:00:00, dtype: float64
Ticker
AAPL 250.419998
GOOG 190.440002
MSFT 421.500000
Name: 2024-12-31 00:00:00, dtype: float64
Ticker
AAPL 2.023294
GOOG 2.130705
MSFT 1.788201
dtype: float64
which indicates the AAPL showed the most consistent upward trend over the selected period.
- Did any stock experience significant price volatility? What might have caused this (hint: research news or events)?
It seems Microsoft experienced the fast down 2024-07 — 2024-08,
消息面上,微软股价走低的背景,是其新近发布的财报。
北京时间7月31日凌晨,微软发布了截至6月30日的2024财年第四财季财报。财报显示,微软第四财季总营收为647亿美元,同比增长15%,好于预期为643.9亿美元;净利润为220.36亿美元,同比增长10%,每股收益2.95美元,略高于预期的2.93美元。
尽管总体上看,微软业绩表现稳健,新一季度总营收和利润增长都略微超预期,但同比营收增速明显放缓。这也是市场对微软财报不买单的原因之一。
与此同时,出人意料的是,微软智能云(含Azure业务)的季度营收不及预期,为285.2亿美元,同比增长19%,低于分析师预期286.8亿美元。本季度,Azure和其他云服务的收入增长了29%,低于平均预期的30.6%。相比上季度降低了2个百分点。市场对Azure云服务业绩的担忧也直接体现在股价上:盘后交易中,微软股价急剧震荡,一度最多下跌8.52%至386.875美元。
尽管Azure的云服务增长正在放缓,但微软管理层预计,2025财年的资本支出将增加。这也意味着,对于微软而言,AI基础设施支出的投资回报率仍是一个未解之谜。
Task 5: Bonus Challenge (Optional)
- Calculate the daily percentage change for one of the stocks and add it as a new column to the DataFrame. Use the formula:

这里如果用普通的
matplotlib 来画图:
但我们如果想用
plotly来做交互式的可视化,代码如下
下节课预告
For Unit 2, we will expand on calculating basic indicators (like moving averages) and delve deeper into preprocessing stock data.
- Author:Yixin Huang
- URL:https://yixinhuang.cn/article/184d1582-2d17-8012-a157-cf85094cd29d
- Copyright:All articles in this blog, except for special statements, adopt BY-NC-SA agreement. Please indicate the source!



