Building a Live Nepalese Stock Portfolio Tracker in Python with yfinance and Rich

Building a Live Nepalese Stock Portfolio Tracker in Python with yfinance and Rich

Introduction

As we covered in Building Effective Command Line Interface Tools with Argparse and Click in Python, creating command-line tools can greatly simplify complex tasks, such as tracking stock portfolios. In recent years, there has been a surge in interest in building custom portfolio trackers, as seen in projects like python_portfolio_tracker on GitHub. Following the trend of using Python for financial analysis, as discussed in Analyzing IPO Trends in Nepal with Python: A Step-by-Step Guide, this post will guide you through building a live Nepalese stock portfolio tracker using yfinance and Rich.

Setting Up the Environment

To start, ensure you have Python installed on your system. It's also beneficial to have a basic understanding of Python, as covered in Python : Getting Started the Right Way and Python Basics for Beginners: Numbers, Strings & Lists. For this project, you'll need to install the yfinance and Rich libraries. You can install them using pip:

pip install yfinance rich

These libraries will allow you to fetch live stock data and display it in a visually appealing manner in the terminal.

Understanding yfinance and Rich

yfinance is a Python package to download historical market data from Yahoo! finance. It's particularly useful for fetching real-time and historical stock prices, which is essential for building a live portfolio tracker. Rich, on the other hand, is a Python library for rich text and beautiful formatting in the terminal. It can be used to create user-friendly interfaces for command-line tools, making it perfect for displaying portfolio data in an easy-to-understand format.

Building the Portfolio Tracker

To build the tracker, you'll first need to define a function that fetches the current stock prices using yfinance. Then, you can use Rich to display these prices in a formatted table. Here's an example of how you might implement this:


from rich import print
from rich.table import Table
import yfinance as yf

def fetch_stock_price(ticker):
    stock = yf.Ticker(ticker)
    data = stock.history(period="1d")
    if not data.empty:
        return data['Close'][-1]
    else:
        return None

def display_portfolio(stocks):
    table = Table(title="Stock Portfolio")
    table.add_column("Stock", style="cyan")
    table.add_column("Price", justify="right", style="magenta")
    
    for stock in stocks:
        price = fetch_stock_price(stock)
        if price is not None:
            table.add_row(stock, str(price))
    
    print(table)

# Example usage
stocks = ["NEPSE", "NABIL", "SCB"]  # Replace with your stocks
display_portfolio(stocks)

This example demonstrates how to fetch the current price of a stock and display it in a table. You can customize the `fetch_stock_price` function to handle different types of stock data and the `display_portfolio` function to display more detailed information about each stock.

Handling Real-Time Updates

To make the portfolio tracker live, you can use a loop to continuously update the stock prices. However, be cautious not to overload the Yahoo! finance server with too many requests, as this can lead to your IP being temporarily banned. Implementing a delay between requests or using more advanced techniques like async/await, as discussed in Mastering Async/Await with asyncio in Modern Python: A Comprehensive Guide, can help manage this issue.

Conclusion

Building a live Nepalese stock portfolio tracker with yfinance and Rich is a practical project that combines financial analysis with Python programming. By following the steps outlined in this post and referencing previous guides like Mastering Command Line Interface Tools with Argparse and Click in Python for more complex command-line tools, you can create a powerful tool for monitoring your stock portfolio. Remember to consider recent trends in stock market analysis, such as the use of Unleashing the Power of Dimensionality Reduction for advanced data analysis, to further enhance your project.

Post a Comment

Hi! How can we help you? Send us a message and we'll get back to you.