2. Variables, data types and operators
Level 2: Python from Scratch for Finance
In Python, creating a variable is as simple as assigning it a value with the = sign: there is no need to declare its type beforehand, because Python is a dynamically typed language — the type is inferred automatically from the value you assign.
price = 182.52
ticker = "AAPL"
in_portfolio = TrueVariable names can use letters, numbers and underscores, but they must start with a letter, and by convention they are written in lowercase. There is a handful of reserved words in the language — class, import, return, lambda, among others — that you cannot use as variable names, because Python needs them for its own syntax.
Even though you do not declare it explicitly, every variable has a type, and you can check it with the type() function:
type(price) # <class 'float'>
type(ticker) # <class 'str'>
type(in_portfolio) # <class 'bool'>The fundamental types you will use constantly in quantitative finance are four: int for whole numbers (for example, the number of shares you buy), float for decimal numbers (price, return), bool for true/false (is the position open?), and str for text (the ticker, the name of the strategy).
An important detail: if you reassign a variable with a value of another type, Python does not complain — it simply changes the variable's type on the fly.
x = 10 # x is an int
x = 10.5 # now x is a float, with no error at allThis is convenient, but it is also a source of subtle bugs: if your function expects a number of shares (int) and you mistakenly pass it a float such as 10.5, Python will not warn you, and buying 'half a share' may make no sense depending on the broker you work with.
To convert explicitly between types you use casting: int(), float(), str(), bool().
price_text = "182.52"
price_number = float(price_text) # 182.52, now it really is a number you can compute with
shares = 10.9
whole_shares = int(shares) # 10 - int() truncates, it does not roundWatch out for that last detail: int() does not round to the nearest integer, it truncates the decimal part. int(10.9) gives 10, not 11. If you really need to round, the correct function is round().
The arithmetic operators in Python are the ones you expect — +, -, *, / — plus two that tend to surprise people coming from other languages: // is integer division (it gives you the quotient without decimals) and ** is exponentiation (not ^, which in Python means something else).
capital = 10000
share_price = 182.52
shares_i_can_buy = capital // share_price # integer division: how many whole shares I can afford
compound_return = 1.08 ** 5 # ** is exponentiation: 1.4693, the multiplier on capital after 5 years at 8% per yearThe comparison operators (>, <, >=, <=, ==, !=) always return a boolean, and they are the basis of any entry or exit rule in a strategy: current_price > moving_average is, quite literally, the core of a trading signal.