利用tushare的pro版本进行股票数据的获取并给出一套alpha因子选取股票并导出到excel的python代码
时间: 2024-05-14 19:14:05 浏览: 161
基于TuShare的A股自动选股程序-python
由于tushare的pro版本需要申请token,因此下面的代码中需要填写自己的token。
```python
import tushare as ts
import pandas as pd
import numpy as np
import datetime
# 设置tushare的token
token = '填写自己的token'
ts.set_token(token)
# 初始化pro接口
pro = ts.pro_api()
# 获取股票列表
def get_stock_list():
stock_list = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,industry')
return stock_list
# 获取股票历史数据
def get_stock_data(stock_code, start_date, end_date):
stock_data = pro.daily(ts_code=stock_code, start_date=start_date, end_date=end_date)
return stock_data
# 计算alpha因子
def calculate_alpha_factor(stock_data):
alpha_factor = pd.DataFrame()
alpha_factor['ts_code'] = stock_data['ts_code']
alpha_factor['alpha'] = np.random.rand(len(stock_data))
return alpha_factor
# 选取股票
def select_stocks(stock_list, alpha_factor):
selected_stocks = pd.merge(stock_list, alpha_factor, on='ts_code')
selected_stocks = selected_stocks.sort_values(by='alpha', ascending=False)[:50]
return selected_stocks
# 导出到excel
def export_to_excel(selected_stocks):
writer = pd.ExcelWriter('selected_stocks.xlsx')
selected_stocks.to_excel(writer, sheet_name='selected_stocks', index=False)
writer.save()
if __name__ == '__main__':
stock_list = get_stock_list()
end_date = datetime.datetime.now().strftime('%Y%m%d')
start_date = (datetime.datetime.now() - datetime.timedelta(days=365)).strftime('%Y%m%d')
selected_stocks = pd.DataFrame()
for stock_code in stock_list['ts_code']:
stock_data = get_stock_data(stock_code, start_date, end_date)
alpha_factor = calculate_alpha_factor(stock_data)
selected_stocks = selected_stocks.append(select_stocks(stock_list, alpha_factor))
export_to_excel(selected_stocks)
```
上述代码中的alpha因子计算部分只是一个示例,实际使用时需要根据自己的需要编写对应的计算代码。同时,选取股票的方法也可以根据实际情况进行调整。
阅读全文