Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Mastering Python F-String Formatting: A Trader’s Guide

5 min read

F-String, introduced in Python 3.6, stands for “Formatted String Literals.” It’s a way to format strings in Python, allowing for easier and more readable string formatting. F-strings are recognizable by their prefix f before the opening quotation mark of a string. They use curly braces {} to evaluate variables or expressions directly within the string.

Example:

name = "NIFTY"
price = 19500
formatted_string = f"The current index of {name} is {price}."
print(formatted_string)

Output: The current index of NIFTY is 19500.

In this example, the variables name and price are directly inserted into the string using their variable names inside the curly braces.

Why Should Traders Learn F-String Formatting in Python?

Trading involves dealing with a lot of data, including prices, volumes, dates, and percentages. F-strings allow traders to format this data succinctly and clearly in their Python scripts or Jupyter notebooks. For traders who rely on Python for data analysis, report generation, or algorithmic trading, learning f-string formatting is a valuable skill that enhances their coding efficiency.

Traders often need to generate dynamic reports or real-time dashboards. F-strings make it simple to integrate variables and expressions directly within string literals, which is ideal for creating up-to-date content.

1. Basics of F-String Formatting

Snippet 1: Basic f-string syntax.

name = "Bank Nifty"
print(f"The index we are analyzing is {name}.")

Output: The index we are analyzing is Bank Nifty.

Snippet 2: Formatting numbers with commas.

volume = 78456385
print(f"Total traded volume: {volume:,}")

Output: Total traded volume: 78,456,385

2. Formatting Financial Figures

Snippet 3: Formatting currency adjusted to two decimals

price = 350.4
print(f"The closing price was ${price:.2f}")

Output: The closing price was $350.40

Snippet 4: Formatting local currency(INR).

import locale

# Set the locale to Indian English
locale.setlocale(locale.LC_ALL, 'en_IN')

# Your currency amount
amount = 1234567.89

# Format the amount as currency using f-string and locale.currency()
formatted_amount = locale.currency(amount, grouping=True)

print(f"The formatted amount in Indian currency is: {formatted_amount}")

Output: The formatted amount in Indian currency is: ₹ 12,34,567.89

Snippet 5: Using percentage format.

change = 0.0534
print(f"Price change: {change:.2%}")

Output: Price change: 5.34%

NumberFormatOutputdescription
3.1415926{:.2f}3.14Format float 2 decimal places
3.1415926{:+.4f}+3.1416Format float 4 decimal places with sign
-1{:+.2f}-1.00Format float 2 decimal places with sign
2.71828{:.0f}3Format float with no decimal places
4{:02}04Pad number with zeros (left padding, width 2)
4{:x<4d}4xxxPad number with x’s (right padding, width 4)
10{:x>6d}xxxx10Pad number with x’s (left padding, width 6)
5000000{:,}5,000,000Number format with comma separator
0.35{:.2%}35.00%Format percentage
1000000000{:.2e}1.00e+09Exponent notation
11{:11d} 11Right-aligned (default, width 10)
11{:<11d}11Left-aligned (width 10)
11{:^11d} 11Center aligned (width 10)

3. Date and Time in Trading

Snippet 6: Formatting current date

from datetime import datetime
current_time = datetime.now()
print(f"Report generated on {current_time:%Y-%m-%d %H:%M}")

Output: Report generated on 2023-11-15 09:10

Snippet 7: Time delta in reports.

from datetime import timedelta
yesterday = datetime.now() - timedelta(days=1)
print(f"Data from: {yesterday:%Y %B, %d}")

Output: Data from: 2023 November, 14

List of Date & Time Formatting

DirectiveDescriptionExample
%aWeekday, short versionWed
%AWeekday, full versionWednesday
%wWeekday as a number 0-6, 0 is Sunday3
%dDay of month 01-3131
%bMonth name, short versionDec
%BMonth name, full versionDecember
%mMonth as a number 01-1212
%yYear, short version, without century18
%YYear, full version2018
%HHour 00-2317
%IHour 00-1205
%pAM/PMPM
%MMinute 00-5941
%SSecond 00-5908
%fMicrosecond 000000-999999548513
%zUTC offset+0530
%ZTimezoneIST
%jDay number of year 001-366365
%UWeek number of year, Sunday as the first day of week, 00-5352
%WWeek number of year, Monday as the first day of week, 00-5352
%cLocal version of date and timeMon Dec 31 17:41:00 2018
%CCentury20
%xLocal version of date12/31/18
%XLocal version of time17:41:00
%%A % character%

4. Handling Stock Data

Snippet 8: Displaying stock price with color coding.

stock_price_change = -2.45
color = 'red' if stock_price_change < 0 else 'green'
print(f"Change: {stock_price_change} ({color})")

Output: Change: -2.45 (red)

5. Advanced Formatting for Reporting

Snippet 9: Conditional formatting based on performance.

performance = 0.05
status = "Good" if performance > 0.04 else "Average"
print(f"Monthly performance: {performance:.2%} - {status}")

Output: Monthly performance: 5.00% - Good

Snippet 10: Dynamic precision in reporting.

precision = 3
rate = 5.12345
print(f"Interest rate: {rate:.{precision}f}")

Output: Interest rate: 5.123

6. Formatting in Trading Algorithms

Snippet 11: Displaying algorithmic trade decisions.

action = "BUY"
quantity = 500
print(f"Action: {action}, Quantity: {quantity}")

Output: Action: BUY, Quantity: 500

Snippet 12 : Iterating over a list

If you have a list of stock prices and you want to print them out with some additional text, you can iterate over the list using a for loop:

# Example list of stock prices
stock_prices = [150.5, 200.3, 98.7, 143.6]

# Iterate over the list and print each price
for price in stock_prices:
    print(f"Current stock price: ${price:.2f}")

Output:

Current stock price: $150.50
Current stock price: $200.30
Current stock price: $98.70
Current stock price: $143.60

Snippet 13 : Accessing Specific List Elements

If you want to format and print specific elements from the list, you can access them by their index:

# Example list of currencies
currencies = ["USD", "EUR", "JPY", "INR"]

# Access and print specific elements
print(f"The first currency in the list is {currencies[0]}")
print(f"The fourth currency in the list is {currencies[3]}")

Output:

The first currency in the list is USD
The fourth currency in the list is INR

7. Real-time Data Display

Snippet 14: Read the data from dictionary

stocks = {
    "AAPL": 150.50,
    "MSFT": 295.00,
    "GOOGL": 2820.80
}

# Iterate over the dictionary and use f-string for formatting
for symbol, price in stocks.items():
    print(f"Stock: {symbol}, Price: ${price:.2f}")

Output:

Stock: AAPL, Price: $150.50
Stock: MSFT, Price: $295.00
Stock: GOOGL, Price: $2820.80

Snippet 15 : Read the data from json

First, let’s assume you have a JSON string like this:

[
    {"symbol": "AAPL", "price": 150.50},
    {"symbol": "MSFT", "price": 295.00},
    {"symbol": "GOOGL", "price": 2820.80}
]

Now, let’s write a Python snippet to parse this JSON and use f-strings to format and print this data:

import json

# JSON data as a string
json_data = '''
[
    {"symbol": "AAPL", "price": 150.50},
    {"symbol": "MSFT", "price": 295.00},
    {"symbol": "GOOGL", "price": 2820.80}
]
'''

# Parse the JSON data into a Python list
stocks = json.loads(json_data)

# Iterate over the list and use f-string for formatting
for stock in stocks:
    print(f"Stock: {stock['symbol']}, Price: ${stock['price']:.2f}")

Output:

Stock: AAPL, Price: $150.50
Stock: MSFT, Price: $295.00
Stock: GOOGL, Price: $2820.80

In this snippet:

  • json.loads is used to parse the JSON string into a Python object (in this case, a list of dictionaries).
  • An f-string is used within a loop to format and print out each stock’s symbol and price. The price is formatted to two decimal places.

Snippet 16: Creating a dynamic ticker display.

tickers = ["AAPL", "MSFT", "GOOGL"]
prices = [157, 242, 2732]
for ticker, price in zip(tickers, prices):
    print(f"{ticker:5}: ${price:.2f}")

Output:
AAPL : $157.00
MSFT : $242.00
GOOGL: $2732.00

8. Portfolio Analysis

Snippet 17: Displaying asset allocation.

allocations = {"Stocks": 60, "Bonds": 30, "Cash": 10}
for asset, percentage in allocations.items():
    print(f"{asset:6}: {percentage}%")

Output:

Stocks: 60%
Bonds : 30%
Cash : 10%

Snippet 18 : Stock Pricing in Table Format

stock_data = [
    {"Symbol": "AAPL", "Price": 150.50, "Change": 1.25},
    {"Symbol": "MSFT", "Price": 295.00, "Change": -0.85},
    {"Symbol": "GOOGL", "Price": 2820.80, "Change": 0.55}
]

# Determine column widths
symbol_width = max(len(stock["Symbol"]) for stock in stock_data) + 2
price_width = max(len(f"{stock['Price']:.2f}") for stock in stock_data) + 2
change_width = max(len(f"{stock['Change']:.2f}") for stock in stock_data) + 2

# Print table header
print(f"{'Symbol':<{symbol_width}}{'Price':<{price_width}}{'Change':<{change_width}}")

# Print table rows
for stock in stock_data:
    symbol, price, change = stock["Symbol"], stock["Price"], stock["Change"]
    print(f"{symbol:<{symbol_width}}{price:<{price_width}.2f}{change:<{change_width}.2f}%")

This code will output a table like:

Symbol Price   Change
AAPL   150.50  1.25 %
MSFT   295.00 -0.85 %
GOOGL  2820.80 0.55 %
  • The widths for the ‘Symbol’, ‘Price’, and ‘Change’ columns are calculated based on the longest string that will be printed in each column.
  • The table header is printed first, using the calculated widths to align the column names.
  • Each row of stock data is then printed, formatting the ‘Price’ and ‘Change’ to two decimal places.
  • The < in the f-string format specification aligns the text to the left, ensuring a neatly aligned table.

This approach dynamically adjusts to the data, creating a well-formatted and readable stock market data table.

Rajandran R Creator of OpenAlgo - OpenSource Algo Trading framework for Indian Traders. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Building Algo Platforms, Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in

Integrating Tradingview Lightweight Charts with Yahoo Finance Data –…

Hey traders! If you’re looking for a way to visualize your stock data dynamically and interactively, you’re in for a treat. Today, we’ll explore...
Rajandran R
2 min read

Setting Up a Full-Stack Development Environment for Algorithmic Trading…

Creating an efficient development environment for algorithmic trading requires a blend of modern tools and technologies. This guide will walk you through setting up...
Rajandran R
5 min read

How to Use OpenAI’s Whisper API for Speech-to-Text Conversion…

With the rapid growth of artificial intelligence technology, converting spoken language into text has become an incredibly useful skill. OpenAI's Whisper API is a...
Rajandran R
3 min read

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More