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%
Number | Format | Output | description |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
3.1415926 | {:+.4f} | +3.1416 | Format float 4 decimal places with sign |
-1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
2.71828 | {:.0f} | 3 | Format float with no decimal places |
4 | {:02} | 04 | Pad number with zeros (left padding, width 2) |
4 | {:x<4d} | 4xxx | Pad number with x’s (right padding, width 4) |
10 | {:x>6d} | xxxx10 | Pad number with x’s (left padding, width 6) |
5000000 | {:,} | 5,000,000 | Number format with comma separator |
0.35 | {:.2%} | 35.00% | Format percentage |
1000000000 | {:.2e} | 1.00e+09 | Exponent notation |
11 | {:11d} | 11 | Right-aligned (default, width 10) |
11 | {:<11d} | 11 | Left-aligned (width 10) |
11 | {:^11d} | 11 | Center 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
Directive | Description | Example |
---|---|---|
%a | Weekday, short version | Wed |
%A | Weekday, full version | Wednesday |
%w | Weekday as a number 0-6, 0 is Sunday | 3 |
%d | Day of month 01-31 | 31 |
%b | Month name, short version | Dec |
%B | Month name, full version | December |
%m | Month as a number 01-12 | 12 |
%y | Year, short version, without century | 18 |
%Y | Year, full version | 2018 |
%H | Hour 00-23 | 17 |
%I | Hour 00-12 | 05 |
%p | AM/PM | PM |
%M | Minute 00-59 | 41 |
%S | Second 00-59 | 08 |
%f | Microsecond 000000-999999 | 548513 |
%z | UTC offset | +0530 |
%Z | Timezone | IST |
%j | Day number of year 001-366 | 365 |
%U | Week number of year, Sunday as the first day of week, 00-53 | 52 |
%W | Week number of year, Monday as the first day of week, 00-53 | 52 |
%c | Local version of date and time | Mon Dec 31 17:41:00 2018 |
%C | Century | 20 |
%x | Local version of date | 12/31/18 |
%X | Local version of time | 17: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.