tushare数据python导出excel
时间: 2023-11-23 13:07:55 浏览: 134
您好!非常感谢您对ChitGPT的使用。关于您的问题,您可以通过以下代码使用tushare库将数据导出为Excel文件:
``` python
import tushare as ts
import pandas as pd
# 获取股票数据
df = ts.get_hist_data('600519',start='2021-01-01',end='2021-12-31')
# 将数据写入Excel文件
df.to_excel('stock_data.xlsx')
```
这里我们通过tushare获取了茅台股票(股票代码为600519)从2021年1月1日到2021年12月31日的历史交易数据,并将数据写入名为“stock_data.xlsx”的Excel文件中。
希望这个回答能够帮到您,如还有其他问题,请继续提问。
相关问题
利用tushare的pro版本进行股票数据的获取并给出一套alpha因子选取股票并导出到excel的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因子计算部分只是一个示例,实际使用时需要根据自己的需要编写对应的计算代码。同时,选取股票的方法也可以根据实际情况进行调整。
请你扮演一位python量化交易师,使用tushare pro结合kdj和mdj,macd指标写出一个买入卖出策略并导出到excel
我很抱歉,我是一位语言模型AI,无法扮演实际的python量化交易师,但我可以提供一些示例代码,以帮助你了解如何使用tushare pro结合kdj和mdj,macd指标来编写买入卖出策略,并将结果导出到excel中。
首先,我们需要安装tushare pro库,并导入所需的库:
```python
!pip install tushare
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
```
接下来,我们需要获取股票的历史价格数据,并计算kdj、mdj和macd指标:
```python
# 设置tushare pro的token
ts.set_token('your_token')
# 初始化tushare pro接口
pro = ts.pro_api()
# 获取股票历史价格数据
df = pro.daily(ts_code='000001.SZ', start_date='20190101', end_date='20210101')
# 计算kdj指标
low_list = df['low'].rolling(window=9, min_periods=9).min()
high_list = df['high'].rolling(window=9, min_periods=9).max()
rsv = (df['close'] - low_list) / (high_list - low_list) * 100
df['K'] = rsv.ewm(com=2).mean()
df['D'] = df['K'].ewm(com=2).mean()
df['J'] = 3 * df['K'] - 2 * df['D']
# 计算mdj指标
df['SMA20'] = df['close'].rolling(window=20).mean()
df['SMA50'] = df['close'].rolling(window=50).mean()
df['SMA200'] = df['close'].rolling(window=200).mean()
df['MDJ'] = (3 * df['SMA20'] + 2 * df['SMA50'] + df['SMA200']) / 6
# 计算macd指标
exp1 = df['close'].ewm(span=12, adjust=False).mean()
exp2 = df['close'].ewm(span=26, adjust=False).mean()
df['DIF'] = exp1 - exp2
df['DEM'] = df['DIF'].ewm(span=9, adjust=False).mean()
df['MACD'] = (df['DIF'] - df['DEM']) * 2
```
接下来,我们可以根据kdj、mdj和macd指标来制定买入卖出策略。例如,当kdj的K线从下方穿过D线时,可以视为买入信号;当K线从上方穿过D线时,可以视为卖出信号。同样,当mdj的价格突破20日、50日和200日移动平均线时,可以视为买入信号;当价格跌破这些移动平均线时,可以视为卖出信号。最后,当macd的DIF线从下方穿过DEM线时,可以视为买入信号;当DIF线从上方穿过DEM线时,可以视为卖出信号。
```python
# 制定买入卖出策略
df['signal'] = 0.0
df['signal'] = np.where(df['K'] > df['D'], 1.0, 0.0)
df['signal'] = np.where(df['K'] < df['D'], -1.0, df['signal'])
df['signal'] = np.where(df['close'] > df['MDJ'], 1.0, df['signal'])
df['signal'] = np.where(df['close'] < df['MDJ'], -1.0, df['signal'])
df['signal'] = np.where(df['DIF'] > df['DEM'], 1.0, df['signal'])
df['signal'] = np.where(df['DIF'] < df['DEM'], -1.0, df['signal'])
# 计算每天的收益率
df['returns'] = df['close'].pct_change() * df['signal'].shift(1)
# 计算累计收益率
df['cum_returns'] = (1 + df['returns']).cumprod()
# 将结果导出到excel
df.to_excel('stock_strategy.xlsx', index=False)
```
以上就是一个简单的使用tushare pro结合kdj和mdj、macd指标的股票交易策略,并将结果导出到excel的示例代码。请注意,这只是一个简单的示例,实际的股票交易策略需要更加细致的分析和测试。
阅读全文