[DaMaiXiaomiLearning Quantification] Quantitative Basics of Python Programming (First Lesson for Beginners)

Table of Contents of Series Articles

High frequency head boyfriend

While eating ice cream, Xiaomi asked Damai nonchalantly: "Hi, Brother Damai, what do you want to learn Python for?"
Damai: "Sister Xiaomi, even if you tell me what Brother did, you wouldn't understand." !"
"Don't understand?! How do you know I don't understand if you didn't say anything?" Xiaomi looked at Damai with disdain, curiosity and murderous intent in his eyes.
"Let me tell you, I learned Python to study quantitative trading," Damai said casually, which confused sister Xiaomi.
Then Damai added: "Quantitative trading is to use data calculations to generate trading signals for trading. Do you think trading on a mobile APP is amazing! In fact, we can let computers automatically trade without people watching the market. I don't understand. Right!"
Xiaomi pouted and smiled contemptuously: "You know! You know! You know! I have also studied computers. Who is afraid of anyone? I also want to learn quantitative trading. Isn't it just computer programming? My high-frequency My boyfriend is better than you!"
"Who is the high-frequency head!"
"You don't even know this, but you are still programming, ChatGPT!"
"Uh, uh, uh, that's okay!" Damai was speechless for a moment. Be true to your word.

Preface

Learning time: For beginners to programming, it will take about a week; for veterans with basic programming skills, depending on personal circumstances, it may be OK in an afternoon.
Learning objectives: Master the basic syntax of Python, be able to flexibly use list and dict, and master time conversion and file operations.
Difficulties in learning: functions, modules, lists, dicts, time conversions, etc.

1. What is Python?

Python (British pronunciation: /ˈpaɪθən/; American pronunciation: /ˈpaɪθɑːn/) is a computer programming language founded by Guido van Rossum. Python is a general-purpose programming language designed to make writing code easier for people. It is a high-level programming language, which means that it is more abstract than assembly language and focuses more on problem solving rather than low-level operations.

Python is designed to make code easier to read and understand. It supports multiple programming paradigms, including object-oriented, procedural, and functional programming. Additionally, Python is an interpreted language, which means it can be interpreted line by line at runtime, which makes debugging easier.

Python is widely used in various fields, including web development, data analysis, artificial intelligence, machine learning, network programming, automation scripts, etc. It has a strong community and rich libraries, allowing developers to quickly solve problems and develop efficient applications.

Python's syntax is concise, clear and easy to learn. Its learning curve is relatively flat, allowing beginners to quickly get started writing simple programs. At the same time, Python is also a very powerful programming language that can be used to develop large and complex applications.

2. Python basic syntax

Python is a high-level programming language. Its basic syntax includes data types, variables, operators, expressions, control structures, functions, modules, etc. Here is a brief introduction to these basic syntaxes:

1. Data type:

Python supports a variety of data types, including integers (int), floating point numbers (float), Boolean values ​​(bool), strings (str), lists (list), tuples (tuple), dictionaries (dict), etc.

Integer (int): Represents an integer value with no size limit. For example: 10, -20, 0, etc.
Float: represents a numerical value with a decimal point, including positive and negative numbers. For example: 3.14, -2.56, 0.0, etc.
Boolean value (bool): represents a logical value, with only two values, True and False.
String (str): Represents text data, which can be enclosed in single quotes (') or double quotes ("). For example: "Hello, world!", 'python', etc. List (list): Represents ordered
elements Sets can be enclosed in square brackets ([]) and separated by commas. For example: [1, 2, 3, 'a', 'b', 'c'], etc. Tuple:
with Lists are similar, representing an ordered collection of elements, but tuples are immutable, that is, the elements in them cannot be modified. Tuples are enclosed in parentheses (()), and the elements are separated by commas. For example: (1, 2 , 3, 'a', 'b', 'c'), etc.
Dictionary (dict): Represents a collection of key-value pairs, enclosed in curly brackets ({}), and separated by colons, each Key-value pairs are separated by commas. For example: {'name': 'Alice', 'age': 20}, etc.

后面我们会重点介绍list和dict的使用,这两个在量化交易中会频繁使用,需要重点介绍。

2. Variables:

A variable in Python is a container for storing data and can store various types of data. Variables are referenced using variable names, which must begin with a letter or underscore and cannot begin with a number. Variables can store any type of data after they are declared.

In Python, the way to declare a variable is very simple. You only need to use the variable name (the variable name is equivalent to a reference to the variable) and the assignment operator (=) to assign a value to the variable. For example:

x = 10   # 声明一个整数类型的变量x,并赋值为10
y = 3.14   # 声明一个浮点数类型的变量y,并赋值为3.14
z = "hello"   # 声明一个字符串类型的变量z,并赋值为"hello"

In Python, variable names are case-sensitive, so x and X are two different variables. Additionally, Python has a dynamic type system, which means the type of a variable can change at any time. For example:

x = 10   # 声明一个整数类型的变量x,并赋值为10
print(x)   # 输出10

x = "hello"   # 将变量x的类型改为字符串,并赋值为"hello"
print(x)   # 输出"hello"

In Python, you can also access the value of a variable using its name. For example:

x = 10
print(x)   # 输出10

print(y)   # 如果y未被声明,则会报错
z = "hello"
print(z)   # 输出"hello"

The above is a brief introduction and examples of Python variables. I hope it will be helpful to you.

3. Operator:

Python supports a variety of operators, including arithmetic operators (such as +, -, *, /, etc.), comparison operators (such as ==, !=, <, >, etc.), logical operators (such as and, or, not etc.) and bitwise operators (such as &, |, ^, ~, etc.). There are many commonly used operators in Python. The following is a brief introduction and examples of these operators:

  1. Arithmetic operators:
    +: addition, for example 2 + 3 = 5.
    -: Subtraction, for example 5 - 3 = 2.
    *: Multiplication, for example 2 * 3 = 6.
    /: Division, for example 6/3 = 2.
    %: Take the remainder, for example 7 % 2 = 1.
    **: Power, for example 2 ** 3 = 8.
  2. Comparison operators:
    ==: equals, for example 2 == 3 (False).
    !=: Not equal, for example 2 != 3 (True).
    <: Less than, for example, 2 < 3 (True).
    =>: Greater than, for example, 2 > 3 (False).
    <=: Less than or equal to, for example, 2 <= 3 (True).
    >=: greater than or equal to, for example, 2 >= 3 (False).
  3. Logical operators:
    and: logical AND, such as True and False (False).
    or: logical OR, such as True or False (True).
    not: logical negation, such as not True (False).
  4. Bit operators:
    &: Bitwise AND, such as 10 & 13 (10).
    |: Bitwise OR, such as 10 | 13 (13).
    ^: Bitwise XOR, for example 10^13(7).
    ~: Bitwise negation, such as ~10 (-11).
  5. Assignment operator:
    =: Assign a value, such as x = 10.
    +=: Addition and assignment, for example, x += 5 is equivalent to x = x + 5.
    -=: Subtraction and assignment, for example, x -= 5 is equivalent to x = x - 5.
    *=: Multiply and assign, for example, x *= 5 is equivalent to x = x * 5.
    /=: Division and assignment, for example, x /= 5 is equivalent to x = x / 5.
    %=: Take the remainder and assign a value. For example, x %= 5 is equivalent to x = x % 5.
    **=: Expand and assign a value. For example, x **= 5 is equivalent to x = x ** 5.
  6. Other operators:
    in: Member operator, used to determine whether a value is in a sequence, such as 'a' in ['a', 'b', 'c'] (True).
    not in: Member operator, used to determine whether a value is not in the sequence, such as 'd' not in ['a', 'b', 'c'] (True).
    is: Identity operator, used to determine whether two references point to the same object, such as a = [1, 2, 3]; b = a; print(a is b) (True).
    is not: Identity operator, used to determine whether two references do not point to the same object, such as a = [1, 2, 3]; b = a[:]; print(a is not b) (True).

4. Expression:

An expression is a grammatical structure composed of operands and operators that can be used to calculate and represent numerical values. There are many commonly used expressions in Python. The following is a brief introduction and examples of these expressions:

  1. Arithmetic expression:
    absolute value expression: abs(-2) -> 2.
    Rounding (rounding down) expression: int(3.14) -> 3.
    Rounding (rounding up) expression: ceil(3.14) -> 4.
    Rounding expression: round(3.14) -> 3.
    Get the remainder expression: divmod(10, 3) -> (3, 1).
  2. Relational expression:
    Not equal to expression: 2 != 3 (True).
    Greater than expression: 3 > 2 (True).
    Less than expression: 2 < 3 (True).
    Greater than or equal expression: 3 >= 2 (True).
    Less than or equal to expression: 2 <= 3 (True).
  3. Logical expression:
    and: logical AND, such as True and False (False).
    or: logical OR, such as True or False (True).
    not: logical negation, such as not True (False).
  4. Bitwise expression:
    bitwise AND expression: 10 & 13(10).
    Bitwise OR expression: 10|13(13).
    Bitwise XOR expression: 10^13(7).
    Bitwise negation expression: ~10 (-11).
  5. Assignment expression:
    x += y is equivalent to x = x + y.
    x -= y is equivalent to x = x - y.
    x *= y is equivalent to x = x * y.
    x /= y is equivalent to x = x / y.
    x %= y is equivalent to x = x % y.
    x **= y is equivalent to x = x **y.
  6. Other common expressions:
    in/not in: member operator, used to determine whether a value is in a sequence.
    is/is not: Identity operator, used to determine whether two references point to the same object.
  7. Ternary operator (conditional expression):
    For example, the operation of a > b > c is to first compare a and b to obtain a Boolean value, and then compare this Boolean value with c. For example, when a > b > c is True, the actual The operation process is equivalent to a > b and b > c.

5. Control structure:

Python supports a variety of control structures, including conditional statements (if), loop statements (for, while), jump statements (break, continue), etc. There are many commonly used control structures in Python. The following is a brief introduction and examples of these control structures:

  1. if statement:
    Example 1: If x is greater than 0, output "x is a positive number".
x = 10
if x > 0:
    print("x是正数")

Example 2: If x is equal to 0, output "x is zero", otherwise output "x is not zero".

x = 0
if x == 0:
    print("x是零")
else:
    print("x不是零")
  1. elif statement:
    Example 1: If x is greater than 0, output "x is a positive number", otherwise if x is equal to 0, output "x is zero".
x = 10
if x > 0:
    print("x是正数")
elif x == 0:
    print("x是零")
  1. else statement:
    Example 1: If x is greater than 0, output "x is a positive number", otherwise output "x is not a positive number".
x = -10
if x > 0:
    print("x是正数")
else:
    print("x不是正数")
  1. while statement:
    Example 1: When x is less than 10, output the value of x, and then add 1 to x.
x = 0
while x < 10:
    print(x)
    x += 1
  1. for statement:
    Example 1: Print all elements in the list.
my_list = [1, 2, 3, 4, 5]
for element in my_list:
    print(element)
  1. break statement:
    Example 1: When x equals 5, break out of the loop.
x = 0
while True:
    print(x)
    if x == 5:
        break
    x += 1
  1. continue statement:
    Example 1: When x is an odd number, skip this loop.
x = 0
while True:
    if x % 2 == 0:
        print(x)
    else:
        continue
    if x == 5:
        break
    x += 1
  1. The pass statement
    pass is an empty statement to maintain the integrity of the program structure. pass does not do anything and is generally used as a placeholder statement.
x = 10
if x > 0:
    print("x是正数")
elif x == 0:
    print("x是零")
else:
	pass

6. Function:

A function is a reusable block of code that can be used to implement a specific function. Functions can accept parameters and return values. The introduction and examples of commonly used functions in Python are as follows:

Introduction and examples of commonly used built-in functions in Python:

  1. len(): Calculate the length of the sequence, for example, len('hello') outputs 5.
  2. max(): Returns the maximum value in the sequence, for example, max([1, 2, 3, 4, 5]) outputs 5.
  3. min(): Returns the minimum value in the sequence, for example, min([1, 2, 3, 4, 5]) outputs 1.
  4. sum(): Find the sum of all elements in the sequence, for example, sum([1, 2, 3, 4, 5]) outputs 15.
  5. sorted(): Sorts the sequence and returns the sorted sequence. For example, sorted([5, 3, 1, 4, 2]) outputs [1, 2, 3, 4, 5].
  6. reversed(): Returns the reverse sequence (reverse order) of the sequence, for example list(reversed([1, 2, 3, 4, 5])) outputs [5, 4, 3, 2, 1].
  7. map(): applies the function to each element of the sequence and returns a new sequence, for example list(map(lambda x: x*2, [1, 2, 3, 4, 5])) outputs [2, 4, 6, 8, 10].
  8. filter(): Filter the elements in the sequence according to conditions and return a new sequence, for example list(filter(lambda x: x%2==0, [1, 2, 3, 4, 5])) output [2, 4].
  9. zip(): Pack multiple sequences into a list of tuples, for example list(zip([1, 2], [3, 4])) outputs [(1, 3), (2, 4)].
  10. range(): Generates an integer sequence, for example, range(1, 6) outputs [1, 2, 3, 4, 5].

These functions are all built-in functions of Python and can be used to process data types such as sequences, sets, and dictionaries. In actual development, we can also define functions ourselves to achieve specific functions.

A custom function in Python is a function written by the user, which can be used to encapsulate specific code logic for reuse in other places.

Introduction and examples of Python custom functions

Here is an example of a simple Python custom function:

def square(num):
    """
    计算给定数字的平方
    :param num: 数字
    :return: 数字的平方
    """
    result = num ** 2
    return result

In this example, we define a squarefunction called which takes one argument numand returns the square of that number. The definition of a function begins with a keyword def, followed by the function name and parameter list. In the function body, we write the code logic for calculating the square. Finally, we use returna statement to return the result of the calculation.

To call this function and calculate the square of a number, you would use the following code:

my_num = 5
squared_num = square(my_num)
print(squared_num)  # 输出25

In this example, we 5assign the number to a variable my_numand then call squarethe function passing it in my_numas an argument. The function returns the result of the calculation, which we assign to a variable squared_numand printoutput the result using a statement.

In addition to the above examples, you can also customize various types of functions according to actual needs, such as functions that accept multiple parameters, functions that return multiple values, functions with default parameters, functions with variable parameters, and so on. Custom functions can greatly improve the reusability and maintainability of code, making the program more modular and efficient.

7. Module:

A module is a collection of Python code that can contain functions, classes, variables, etc. Modules can be imported through the import statement and use the code within them.

Introduction and classification of Python modules

Python module (Module) is the basic unit of Python code, used to organize and encapsulate specific functions or related code. Modules can contain Python objects such as variables, functions, and classes for use in other Python programs.

The creation of a module usually exists in the form of a .py file, which contains the code of the module. By organizing functionality and code into different modules, you can improve code reusability, maintainability, and testability.

Here are some examples of Python modules:

  1. Standard library modules: Python provides a wealth of standard library modules, which cover many aspects such as file processing, network programming, database access, and graphical interface development. For example, the os module provides functions related to the operating system, and the math module provides functions related to mathematical calculations.
  2. Custom modules: Users can create custom modules as needed and encapsulate related functions and variables in them. Custom modules can be part of a larger project or standalone, reusable pieces of code. For example, you can create a file called my_module.py that contains some custom functions and classes.
  3. Third-party modules: In addition to the standard library, there are a large number of third-party modules available that cover a variety of different areas. You can use the functions, classes, or tools in these modules by installing them and importing them into your Python program. For example, numpy is a third-party module for scientific computing that provides efficient mathematical calculation functions.
  4. Importing a module: To use a module, you need to import it using the import statement in your Python program. After importing a module, you can access objects such as variables, functions, and classes in it. For example:
import math
print(math.pi)  # 输出3.141592653589793

The above code imports the math module and prints the pi variable in it.

In short, modules are an important part of Python code, used to encapsulate specific functions or related code and can be reused in different Python programs.

Application examples of Python modules

  1. File operations: Use the os module to easily perform file and directory operations, such as obtaining file information, reading file contents, creating directories, etc.
import os

# 获取文件信息
stat_info = os.stat('example.txt')
print(stat_info.st_size)  # 输出文件大小

# 读取文件内容
with open('example.txt', 'r') as file:
    content = file.read()
print(content)
  1. Network programming: Use the socket module to program network communications, such as creating TCP connections, sending data, etc.
import socket

# 创建TCP连接
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8000))

# 发送数据
message = 'Hello, server!'
client_socket.send(message.encode())

# 接收数据
response = client_socket.recv(1024).decode()
print(response)

# 关闭连接
client_socket.close()
  1. Database access: Use the sqlite3 module to easily operate SQLite databases, such as creating database connections, executing SQL queries, etc.
import sqlite3

# 创建数据库连接
conn = sqlite3.connect('example.db')
cursor = conn.cursor()

# 创建表
cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INT)''')

# 插入数据
cursor.execute("INSERT INTO users VALUES (1, 'Alice', 25)")
cursor.execute("INSERT INTO users VALUES (2, 'Bob', 30)")

# 查询数据
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
print(result)

# 关闭连接
conn.close()
  1. Graphical interface development: Use the tkinter module to create GUI applications, such as creating windows, adding controls, handling events, etc.
import tkinter as tk

# 创建窗口
window = tk.Tk()
window.title('Example App')
window.geometry('300x200')

# 添加标签控件
label = tk.Label(text='Hello, World!')
label.pack()

# 处理按钮点击事件
def button_clicked():
    label.config(text='Button clicked!')
    label.pack()
    print('Button clicked!')
    
button = tk.Button(text='Click Me!', command=button_clicked)
button.pack()

# 进入主循环
window.mainloop()

Examples of reference methods for Python modules

To reference functions or variables in a Python module, you need to use the import statement or the from...import... statement. The following are examples of citation methods:

  1. Import the entire module:
import math

This allows you to use functions from the math module, for example:

result = math.sqrt(16)  # 调用math模块的sqrt函数
print(result)           # 输出4.0
  1. Import some functions or variables in the module:
from math import sqrt, ceil

This allows you to use the sqrt and ceil functions directly without referencing them by module name, for example:

result1 = sqrt(16)      # 调用math模块的sqrt函数
result2 = ceil(3.14)    # 调用math模块的ceil函数
print(result1)          # 输出4.0
print(result2)          # 输出4.0
  1. Import one module within another module:
import module1
from module2 import function1, function2

This way you can use all functions and variables in module1, as well as function1 and function2 functions in module2.

3. Introduction to the usage of list

The list in Python is a very commonly used data structure. It is an ordered collection that can store any type of data. Below we will introduce some basic methods of using Python lists.

Create list

Creating a list is very simple, just use square brackets [] and enclose the elements, separated by commas.

my_list = [1, 2, 3, 'a', 'b', 'c']

Access list elements

To access elements in a list, you can use indexing. The index starts from 0 and indicates the position of the element in the list.

print(my_list[0])  # 输出:1
print(my_list[3])  # 输出:'a'

Modify list elements

To modify an element in a list, you can assign it directly.

my_list[0] = 100
print(my_list)  # 输出:[100, 2, 3, 'a', 'b', 'c']

Add element to list

To add elements to the list, you can use append()the method.

my_list.append(4)
print(my_list)  # 输出:[100, 2, 3, 'a', 'b', 'c', 4]

Remove element from list

To remove an element from a list, you can use remove()the method, which removes the first matching element. If you want to delete an element at a specified position, you can use delthe statement.

my_list.remove(100)  # 删除元素100
print(my_list)  # 输出:[2, 3, 'a', 'b', 'c', 4]

del my_list[0]  # 删除位置0的元素
print(my_list)  # 输出:[3, 'a', 'b', 'c', 4]

list slicing

List slicing refers to selecting a subset of elements from a list. The syntax is list[start:end]where startis the index at which the slice starts (inclusive) and endis the index at which the slice ends (exclusively). Note that the slices are from left to right.

my_list = [0, 1, 2, 3, 4, 5]
print(my_list[1:4])  # 输出:[1, 2, 3]

Loop through the list

You can use fora loop to iterate through all elements in a list.

my_list = [0, 1, 2, 3, 4, 5]
for element in my_list:
    print(element)

List length

You can use len()the function to get the length of a list.

my_list = [0, 1, 2, 3, 4, 5]
print(len(my_list))  # 输出:6

4. Introduction to the usage of dict

The dictionary (dict) in Python is a very commonly used data structure. It is an unordered collection of key-value pairs, and the corresponding values ​​can be accessed through the keys. Below we will introduce some basic methods of using Python dictionaries.

Create dictionary

Creating a dictionary is very simple, just use curly brackets {} and separate key-value pairs with colon:, and separate key-value pairs with commas,.

my_dict = {
    
    'name': 'Alice', 'age': 25, 'gender': 'female'}

Access dictionary elements

To access elements in a dictionary, you use keys to index them. If the key does not exist in the dictionary, a KeyError exception is thrown. To avoid exceptions, you can use get()the method to get the value of the specified key, or return a default value if the key does not exist.

print(my_dict['name'])  # 输出:'Alice'
print(my_dict.get('age'))  # 输出:25
print(my_dict.get('address', 'unknown'))  # 输出:'unknown',因为'address'键不存在

Modify dictionary elements

To modify an element in a dictionary, you can assign it directly. If the key does not exist, a new key-value pair is created.

my_dict['age'] = 26
print(my_dict)  # 输出:{'name': 'Alice', 'age': 26, 'gender': 'female'}

Add dictionary elements

To add an element to a dictionary, you can assign it directly. If the key does not exist, a new key-value pair is created.

my_dict['address'] = '123 Main St.'
print(my_dict)  # 输出:{'name': 'Alice', 'age': 26, 'gender': 'female', 'address': '123 Main St.'}

Delete dictionary element

To delete elements from a dictionary, you can use delthe statement. If you want to delete the entire dictionary, you can use delthe statement or pop()method.

del my_dict['age']  # 删除键为'age'的元素
print(my_dict)  # 输出:{'name': 'Alice', 'gender': 'female', 'address': '123 Main St.'}

my_dict.pop('address')  # 删除键为'address'的元素,并返回其值
print(my_dict)  # 输出:{'name': 'Alice', 'gender': 'female'}

dictionary comprehension

Dictionary comprehensions are a quick way to create a dictionary by converting the elements of a list or tuple into dictionary key-value pairs. Its syntax is {key_expression for item in iterable}.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
gender = ['female', 'male', 'male']
my_dict = {
    
    name: age + gender[i] for i, name in enumerate(names)}
print(my_dict)  # 输出:{'Alice': '25female', 'Bob': '30male', 'Charlie': '35male'}

5. Mutual conversion of list and dict

  1. Convert list to dict

Converts a list containing key-value pairs into a dictionary, where each element in the list is a tuple containing two elements, the key and the value.

my_list = [('apple', 2), ('banana', 3), ('orange', 4)]
my_dict = dict(my_list)
print(my_dict)  # 输出:{'apple': 2, 'banana': 3, 'orange': 4}
  1. Convert dict to list

Converts a dictionary into a list containing a single element, where each element is a tuple containing the key and value from the dictionary.

my_dict = {
    
    'apple': 2, 'banana': 3, 'orange': 4}
my_list = list(my_dict.items())
print(my_list)  # 输出:[('apple', 2), ('banana', 3), ('orange', 4)]

6. Date, time and conversion to string time

In Python, we often need to deal with dates and times, as well as convert dates and times to timestamps or get date and times from timestamps. The following is a tutorial on how to convert dates, times, and timestamps to and from in Python.

Import related modules

First, we need to import Python's datetime module, which contains many classes and methods for processing dates and times.

import datetime

Get current date and time

To get the current date and time, we can use the now() function from the datetime module.

current_datetime = datetime.datetime.now()
print(current_datetime)

Format date and time into string

If you want to format the date and time into a specific string format, you can use the strftime() method. Here are some commonly used formatting options:

  • %Y: four-digit year
  • %m: two-digit month
  • %d: two-digit date
  • %H: hour (24-hour format)
  • %M: minutes
  • %S: seconds
  • %f: microseconds

For example, to format the current date and time into the format "Year-Month-Day Hour:Minute:Second", you can do the following:

current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)

Parse string into date and time

If you have a string representing a date and time, and the string's format matches the format string of the strptime() method, you can parse the string into a date and time object. Here are some examples:

string_datetime = "2023-07-06 15:30:00"
parsed_datetime = datetime.datetime.strptime(string_datetime, "%Y-%m-%d %H:%M:%S")
print(parsed_datetime)

Convert date and time to timestamp

We can convert it to a timestamp using the timestamp() method of the datetime object. The timestamp is the number of seconds since midnight (UTC) on January 1, 1970.

current_datetime = datetime.datetime.now()
timestamp = current_datetime.timestamp()
print(timestamp)

Convert timestamp to date and time

To get date and time from timestamp we can use fromtimestamp() function from datetime module.

timestamp = 1695483600  # 这是一个示例时间戳
parsed_datetime = datetime.datetime.fromtimestamp(timestamp)
print(parsed_datetime)

The above are the basic operations for converting dates, times, and timestamps in Python.

6. File reading and writing

In Python, file reading and writing is a common operation. The following is a brief introduction to basic file reading and writing methods, covering different scenarios and operations.

open a file

In Python, use open()functions to open files. This function requires passing the file path and mode as parameters. The modes can be the following:

  • 'r': Read-only mode, opens the file for reading.
  • 'w': Write mode, opens the file for writing. If the file already exists, it will be cleared. If the file does not exist, a new file will be created.
  • 'a': Append mode, opens the file to append content at the end. If the file does not exist, a new file will be created.
  • 'x': Create mode, create a new file. If the file already exists, an error will be returned.

Example:

file = open('example.txt', 'r')  # 打开一个名为'example.txt'的文件用于读取

read file

There are several ways to read file contents. Here are a few common methods:

  • read(): Read the entire contents of the file at once.
  • readline(): Read the contents of the file one line at a time.
  • readlines(): Read the entire contents of the file at once and store it line by line as a list.

Example:

file = open('example.txt', 'r')  # 打开一个名为'example.txt'的文件用于读取
content = file.read()  # 读取文件的全部内容
print(content)  # 打印文件的全部内容
file.close()  # 关闭文件

write file

To write to a file, you can use write()the method. It should be noted that when opening a file in write mode, if the file already exists, its contents will be cleared. If you want to append content instead of overwriting the original content, use append mode.

Example:

file = open('example.txt', 'w')  # 打开一个名为'example.txt'的文件用于写入
file.write('Hello, world!')  # 将字符串'Hello, world!'写入文件
file.close()  # 关闭文件

Append content to file

To append content to a file, open the file in append mode and write()write the content using the method.

Example:

file = open('example.txt', 'a')  # 打开一个名为'example.txt'的文件用于追加
file.write('\nHello again, world!')  # 在文件的末尾追加字符串'\nHello again, world!'
file.close()  # 关闭文件

close file

After using the file, you should close it promptly. This frees up system resources and ensures file integrity and consistency. To close the file you can use close()the method.

Example:

file = open('example.txt', 'r')  # 打开一个名为'example.txt'的文件用于读取
content = file.read()  # 读取文件的全部内容
print(content)  # 打印文件的全部内容
file.close()  # 关闭文件

Use the with statement to manipulate files

To ensure that a file is closed properly after use, withstatements can be used to manipulate the file. This will automatically close the file without having to manually call close()the method.

Example:

with open('example.txt', 'r') as file:  # 使用with语句打开文件并赋值给变量file,无需手动关闭文件
    content = file.read()  # 读取文件的全部内容
    print(content)  # 打印文件的全部内容

Summarize

Although the content of this article is a bit long, we only need to know what this expression means. If we don’t know it or forgot to look it up, that’s it. Due to the limited space, Python still has a lot of application skills and knowledge. If you want to learn more, readers can search in depth on their own.

Here, the basic knowledge of Python required for quantitative trading is demonstrated and examples are provided to facilitate follow-up learning of quantification. Quantification does not require much Python knowledge. It requires more data processing through list, dict, and pandas, combined with logical control statements, to generate trading signals, and call API to complete the order operation.

After mastering the knowledge in this article, you must be able to handle basic Python code reading and writing. Later, we will combine different quantitative frameworks to learn quantitative trading.

Guess you like

Origin blog.csdn.net/popboy29/article/details/132462311