Exploring Python Basics and Stock Analysis with Yahoo Finance

In this blog post, we will introduce some Python basics, including variable types, control flow statements, and importing libraries. After that, we will dive into stock analysis using the Yahoo Finance library to retrieve stock data, calculate returns, and visualize the results. Let’s begin by looking at some basic Python operations and python for stock analysis.

Printing and Variable Types

				
					print("Hello, World!")
print(type("Hello, World!"))
myFirstString = "Hello, World!"
print(myFirstString)

				
			

The print function allows us to display text in the console, and the type function returns the data type of the given variable. In this case, we’re working with a string.

Multiplying Two Integers

				
					Integers are a variable type in Python and most other programming languages. Here we will declare them and then add them together.
stockPrice = 15
numberOfShares = 10
print('The amount of money I have in these stocks is: ' + str(stockPrice*numberOfShares))

				
			

We declare two integer variables, stockPrice and numberOfShares, and multiply them together to calculate the total amount of money we have in these stocks.

Running a For Loop

				
					values = [1,2,3,4,5,6,7,8,9,10]

print(type(values))

for i in values:
    print(i)

				
			

A for loop is a control flow statement that iterates over a sequence of values and executes a block of code for each value in the sequence. In this example, we iterate over a list of integers and print each value.

Executing an If Statement

				
					a = 8
b = 10

if a > b:
    print("a is greater than b")
elif b > a:
    print("b is greater than a")

for i in values:
    if i > 5:
        print(i)

				
			

An if statement is a control flow statement that allows us to execute a block of code if a particular condition is true, and skip that block of code if the condition is false. In this example, we compare two integer variables and print a message based on their relationship. We also use a for loop and an if statement to print values greater than 5 from a list of integers.

Importing Libraries

				
					import yfinance as yf
import pandas as pd
from pandas_datareader import data as pdr
import datetime as dt
import numpy as np

				
			

In Python, libraries are collections of pre-written code that extend the language’s functionality. We need to import them into our code to use their functions, classes, and other features. In this example, we import the necessary libraries for stock analysis, including yfinance, pandas, pandas_datareader, datetime, and numpy.

Declaring the Date Range for Our Stock Returns

				
					endDate = dt.datetime.now()

startDate = endDate - dt.timedelta(days = 365*5)
endDate, startDate

				
			

Here, we use Python’s datetime module to define a date range for our stock analysis. We declare the current date as the endDate, and the startDate as five years before the current date.

Creating a List of Stocks

				
					stocks = ['MSFT', 'SPY', 'QQQ']

				
			

We create a list of stock symbols that we are interested in analyzing. This list can be modified to include any stock symbols available on Yahoo Finance.

Downloading Stock Data from Yahoo Finance

				
					df = yf.download(stocks, start = startDate, end = endDate)
				
			
				
					
Using the `yfinance` library, we download the historical stock data for our selected stocks within the specified date range.

**Exploring the Dataframe**

```python
df.head()

				
			

The head function allows us to take a peek at the first few rows of the dataframe containing our downloaded stock data.

Selecting Adjusted Close Prices

				
					adj_close_prices = df['Adj Close']
adj_close_prices.head()

				
			

We extract the adjusted close prices from the dataframe and store them in a new variable called adj_close_prices.

Calculating Daily Returns

				
					# To calculate the daily returns, we can use the pct_change() function from pandas
log_returns = np.log(adj_close_prices/adj_close_prices.shift(1))
log_returns.head()

				
			

We calculate the daily log returns of the stocks using the pct_change() function from the pandas library and the natural logarithm function from the numpy library.

Calculating Cumulative Returns

				
					cumulative_log_returns = log_returns.cumsum()

				
			

We compute the cumulative log returns by summing up the daily log returns using the cumsum() function from pandas.

Plotting Cumulative Returns

				
					# We'll use the same plot() function from pandas to visualize the cumulative returns of the stocks

cumulative_log_returns.plot(title="Cumulative Returns", figsize=(10, 6))

				
			

Finally, we visualize the cumulative returns of our selected stocks using the plot() function from pandas. This provides us with a clear picture of how the stocks have performed over the specified date range.

In this blog post, we have covered some Python basics and demonstrated how to analyze stocks using the Yahoo Finance library. This process can be easily adapted to analyze different stocks, timeframes, or even other financial instruments.

Conclusion

In this tutorial, we explored the basics of Python, including variable types, control flow statements, and importing libraries. We then demonstrated how to use the Yahoo Finance library to perform stock analysis, starting from retrieving stock data to calculating daily and cumulative returns, and finally visualizing the results.

This tutorial provides a solid foundation for anyone interested in learning Python programming and applying it to finance. The techniques demonstrated can be easily adapted to analyze different stocks, timeframes, or even other financial instruments. As you progress in your journey with Python and finance, you can explore more advanced topics such as machine learning, portfolio optimization, and algorithmic trading to further enhance your skills and knowledge. Happy coding!

Hire me for your next Project

I can assist you with your financial modeling and quantitative finance projects, leveraging my expertise and experience in the field.

Contact Me

Feel free to reach out to discuss your freelance project needs, and let’s collaborate on bringing your vision to life!