Text is a string
A string (str) is text. Write it between single or double quotes: both mean the same, so pick one style and keep it. A backslash starts an escape, such as \n for a new line. len() counts the characters. Strings are immutable: you never change one in place, you build a new one.
symbol = "AAPL"
note = 'bid and ask'
print(symbol, len(symbol)) # AAPL 4
print(note) # bid and askIndexing and slicing
Each character has a position, counting from 0. text[0] is the first character and text[-1] the last. A slice text[start:stop] takes the characters from start up to, but not including, stop. Leave one side empty to run to that end.
# Indexing starts at 0; a slice stops before its end index
ticker = "AAPL.US"
print(ticker[0], ticker[-1]) # A S
print(ticker[:4], ticker[5:]) # AAPL USMethods that clean and split text
Methods are functions attached to a value and called with a dot. They return a new string and leave the original alone. strip() removes spaces and newlines around the text, upper() and lower() change the case, replace(old, new) swaps text, and split(",") cuts a line at every comma into a list of pieces. Data feeds are full of lines like this.
# Clean up a raw line from a data feed
raw = " aapl,184.25,200 \n"
parts = raw.strip().split(",")
print(parts) # ['aapl', '184.25', '200']
print(parts[0].upper()) # AAPL
print(float(parts[1])) # 184.25# join is the opposite of split; in tests for a piece of text
print("-".join(["AAPL", "MSFT"])) # AAPL-MSFT
print("AAPL" in "AAPL,MSFT") # Truef-strings put values into text
Put an f before the opening quote and write any expression between { and }: Python evaluates it and inserts the result as text. This replaces gluing pieces together with + and converting numbers by hand. Anything that is a valid expression works inside the braces, even arithmetic.
# f-strings put values straight into text
symbol, bid, ask = "AAPL", 184.25, 184.5
print(f"{symbol} {bid} x {ask}") # AAPL 184.25 x 184.5
print(f"{symbol} spread {ask - bid}") # AAPL spread 0.25Format specifications
After a colon inside the braces, a format specification controls how the value looks. .2f shows two decimals, , adds thousands separators, + always shows the sign, >8 right-aligns in a width of 8, and .1% shows a fraction as a percentage. They combine: +,.2f is a signed amount with separators and two decimals.
# After the colon, a format spec controls the look
price, pnl, quantity = 184.5, 1234.5, 200
print(f"{price:.2f}") # 184.50
print(f"{pnl:+,.2f}") # +1,234.50
print(f"{quantity:>8d}|") # " 200|"
print(f"{0.0123:.1%}") # 1.2%Next up: booleans and comparisons, the True and False values that every decision in a trading rule is built from.
Lab · what's graded
- Write a quote as text with
quote_line25 pts - Show profit and loss with a sign using
signed_pnl25 pts - Clean a ticker symbol with
normalize_symbol25 pts - Read a fill line from a feed with
parse_fill25 pts