current position：Home>Talk about quantifying investment using Python
Talk about quantifying investment using Python
2022-01-30 12:07:54 【ReganYue】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Talk about using Python Getting started quantifying investment
Quantitative trading uses computer technology （ This article mainly refers to the use of Python） Help investors analyze a large amount of data to formulate investment strategies , This belongs to the cross field of Finance and computer .
This article is used to guide the use of Python Beginners who carry out quantitative transactions get started , Limited to my limited level , Let's take it easy ~
0x01 Extract the data
To extract stock data , We need to use Quandl Of API, This platform has a lot of economic and financial data .
First we need to install Python 3 and virtualenv, And pass
virtualenv --python=/usr/bin/python3 <name of env> Copy code
Creating a virtual environment .
And then use
source <env_name>/bin/activate Copy code
Activate the virtual environment .
Reuse pip install jupyter-notebook：
pip install jupyter-notebook Copy code
And then install it
numpy package .
Last run jupyter-notebook.
Extract the data
Let's import the required package first .
import pandas as pd import quandl as q Copy code
here pandas It can help us with data operation and drawing .
Then we call Quandl API.
q.ApiConfig.api_key = "<API key>” msft_data = q.get("EOD/MSFT", start_date="2010-01-01", end_date="2019-01-01") msft_data.head() Copy code
In this code , We first set the required api_key. You need to go to the official website to get .
And then call get Method to get Microsoft from 2010 year 1 month 1 The day is coming 2019 year 1 month 1 The stock price on the day .
Then there is the front view of the acquired dataset 5 That's ok .
0x02 Analyze the data
Let's first understand the data composition of the dataset , This can be done through info Method view .
As shown in the figure above , We can see that these data contain stock price information .
Such as the opening price and closing price of the stock 、 Adjusted opening and closing prices , This adjustment is to distribute dividends 、 Stock splits and other actions are taken into account , It also includes the trading volume and the highest and lowest prices of the day .
We can also go through describe Method to analyze the maximum value of the data set 、 minimum value 、 Average and other data .
We can also continue to process these data .
For example, take another sample . Adjust the time interval to monthly 、 Quarterly or annually .
0x04 Calculate financial returns
Let's next calculate the financial return .
We're going to use pct_change() Method .
import numpy as np daily_close = msft_data[['Adj_Close']] daily_return = daily_close.pct_change() daily_return.fillna(0, inplace=True) print(daily_return) Copy code
We use the adjusted closing price to calculate the return from the start time to each time . Multiply this value 100 You get a percentage return .
We can also calculate the rate of return with a time interval of months ：
mdata = msft_data.resample('M').apply(lambda x: x[-1]) monthly_return = mdata.pct_change() monthly_return.fillna(0, inplace=True) print(monthly_return) Copy code
Some codes refer to ：www.codementor.io/blog/quanti…
author[ReganYue],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
guess what you like
Base64 encryption and decryption in Python
Chapter 2: Fundamentals of python-2 variable
Python garbage collection summary
Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
Python draws a spinning windmill with turtle
Deep understanding of Python features
A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
Python opencv Canny edge detection knowledge supplement
Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
Python: faker extension package
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
- Python string method tutorial - how to use the find() and replace() functions on Python strings
- Python computer network basics
- Python crawler series: crawling global airport information
- Python crawler series: crawling global port information
- How to calculate unique values using pandas groupby
- Application of built-in distribution of Monte Carlo simulation SciPy with Python
- Gradient lifting method and its implementation in Python
- Pandas: how to group and calculate by index
- Can you create an empty pandas data frame and fill it in?
- Python basic exercises teaching! can't? (practice makes perfect)