python 量化选股
时间: 2023-12-07 12:39:03 浏览: 121
量化选股是指利用数学和统计学方法,通过对股票历史数据的分析和挖掘,筛选出符合一定条件的股票,以达到投资收益最大化的目的。以下是Python进行量化选股的一些方法和步骤:
1.从蜂鸟数据获取沪深A股的历史数据。
2.使用pandas库读取历史数据,并进行数据清洗和预处理。
3.自定义函数实现选股逻辑,例如MM模型。
4.使用多进程计算,大幅减少筛选的时间。
5.使用matplotlib库进行可视化分析,以便更好地理解和分析数据。
以下是一个简单的Python量化选股的例子:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tushare as ts
import multiprocessing as mp
# 从蜂鸟数据获取沪深A股的历史数据
pro = ts.pro_api()
df = pro.daily(ts_code='000001.SZ', start_date='20100101', end_date='20210101')
# 数据清洗和预处理
df = df.sort_values('trade_date')
df.index = pd.to_datetime(df.trade_date)
df = df[['open', 'high', 'low', 'close', 'vol']]
df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
# 自定义函数实现选股逻辑
def MM_strategy(df):
df['MA5'] = df['Close'].rolling(5).mean()
df['MA20'] = df['Close'].rolling(20).mean()
df['MA60'] = df['Close'].rolling(60).mean()
df['MA120'] = df['Close'].rolling(120).mean()
df['MA250'] = df['Close'].rolling(250).mean()
df['MA5_20'] = df['MA5'] - df['MA20']
df['MA20_60'] = df['MA20'] - df['MA60']
df['MA60_120'] = df['MA60'] - df['MA120']
df['MA120_250'] = df['MA120'] - df['MA250']
df['MA5_20_signal'] = np.where(df['MA5_20'] > 0, 1, -1)
df['MA20_60_signal'] = np.where(df['MA20_60'] > 0, 1, -1)
df['MA60_120_signal'] = np.where(df['MA60_120'] > 0, 1, -1)
df['MA120_250_signal'] = np.where(df['MA120_250'] > 0, 1, -1)
df['signal'] = df['MA5_20_signal'] + df['MA20_60_signal'] + df['MA60_120_signal'] + df['MA120_250_signal']
df['signal'] = np.where(df['signal'] >= 3, 1, 0)
return df
# 使用多进程计算,大幅减少筛选的时间
processors = mp.cpu_count()
df_chunks = np.array_split(df, processors, axis=0)
pool = mp.Pool(processors)
df = pd.concat(pool.map(MM_strategy, df_chunks))
pool.close()
pool.join()
# 可视化分析
df['Close'].plot(figsize=(10, 6))
plt.title('000001.SZ')
plt.show()
```
阅读全文