金融数据分析| tushare包| 双均线策略
1. tushare
Tushare是一个免费、开源的python财经数据接口包。
tushare pro版 https://tushare.pro/document/1
下载安装tushare接口包
get_k_data 获取k线数据 ---->> 全新的免费行情数据接口简介:
import tushare as ts
ts.get_k_data("601318")
df = ts.get_k_data("002230", start = "1988-01-01")
df

date open close high low volume code 0 2008-05-12 2.106 2.262 2.327 2.106 182125.40 002230 1 2008-05-13 2.273 2.489 2.489 2.270 49982.31 002230 2 2008-05-14 2.553 2.534 2.611 2.411 49221.30 002230 3 2008-05-15 2.497 2.538 2.680 2.497 46358.73 002230 ... ... ... ... ... ... ... ... 2766 2020-02-06 38.320 39.300 39.370 37.800 1309916.00 002230 2767 2020-02-07 38.880 38.860 39.800 38.100 1074613.00 002230
练习一:
使用tushare包获取某股票的历史行情数据;
输出该股票所有收盘比开盘上涨3%以上的日期;
输出该股票所有开盘比前日收盘跌幅超过2%的日期;
加入我从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
df = ts.get_k_data("600519",start = "1988-01-01")
df.to_csv("600519.csv")
df = pd.read_csv("600519.csv", index_col = 'date', parse_dates = ['date'])[['open','close','high','low']]
df

open close high low date 2001-08-27 5.392 5.554 5.902 5.132 2001-08-28 5.467 5.759 5.781 5.407 2001-08-29 5.777 5.684 5.781 5.640 ... ... ... ... ... 2020-02-05 1050.000 1049.990 1054.000 1033.030 2020-02-06 1059.430 1071.000 1075.000 1052.020 2020-02-07 1070.010 1076.000 1077.000 1061.020
#输出该股票所有收盘比开盘上涨3%以上的日期
df[(df['close']-df['open'])/df['open'] >= 0.08] #df[(df['close']-df['open'])/df['open'] >= 0.1].index

open close high low
date
2004-03-02 5.463 6.031 6.079 5.463
2005-06-08 11.383 12.555 12.639 11.383
2006-02-10 14.894 16.165 16.310 14.796
2006-05-29 25.024 27.520 27.520 25.024
2006-12-18 49.409 54.051 54.214 49.409
2007-06-11 67.313 73.569 73.569 66.913
2007-10-09 92.221 99.938 101.348 92.221
2007-12-14 125.269 135.970 137.154 124.029
2008-11-14 57.017 62.417 62.417 57.017
2009-03-04 73.123 79.024 79.961 72.756
2015-04-16 177.135 192.185 192.185 176.523
2015-07-09 201.180 219.085 221.182 197.901
④ 假如我从2001-01-01开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?
price_last = df['open'][-1] #最后一天的开盘价
df = df['2001-09':'2017-11'] #剔除首尾无用数据
df_monthly = df.resample('M').first() #每个月的第一个开盘 #mean()平均 sum()
df_yearly = df.resample('A').last()[:-1] #每年的最后一天开盘, 去掉最后一天不符合
cost_money = 0
hold = 0
for year in range(2001, 2018):
cost_money += df_monthly[str(year)]['open'].sum()*100 #花费的钱 = 一年内的开盘价总和 * 100股
hold += len(df_monthly[str(year)]['open']) * 100 #股票的数量
if year != 2017:
cost_money -= df_yearly[str(year)]['open'][0] * hold #每年取第一个月的开盘价 * 股票数量
hold = 0
print(cost_money)
cost_money -= hold * price_last #股票值的钱
print(-cost_money)

-94.80000000000018 1082.6999999999998 493.4999999999982 -2027.2000000000025 -3889.5000000000055 -38129.100000000006 -110589.8 -70515.90000000001 -96941.2 -116591.6 -123173.59999999998 -116746.5 -78106.39999999998 -121609.49999999996 -143901.09999999998 -212044.10000000003 263700.50000000006 425573.8
2. 双均线策略
练习2 -- 查找历史金叉死叉日期
使用tushare包获取某股票的历史行情数据;
使用pandas包计算改股票历史数据的5日均线和30日均线;
使用matplotlib包可视化历史数据的收盘价和两条均线;
分析输出所有金叉日期和死叉日期;
假设我从2010年1月1日开始,初始资金为100000元,金叉尽量买入,死叉全部卖出,则到今天为止,我的股票收益率如何?
练习二-查找历史金叉死叉日期 均线:对于每一个交易日,都可以计算出前N天的移动平均值,然后把这些移动平均值连起来成为一条线,就叫做N日移动平均线。 移动平均线常用线有5天、10天、30天、60天、120天和240天的指标。 5天和10天的是短线操作的参照指标,称做日均线指标; 30天和60天的是中期均线指标,称做季均线指标; 120天和240天的是长期均线指标,称做年均线指标。 金叉: 短期均线上穿长期均线,买入信号; 死叉: 短期均线下穿长期均线,卖出信号;
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("601318.csv",index_col='date',parse_dates = ['date'])[['open','close','low','high']]
df
##方法一: for循环
df['ma5'] = np.nan
df['ma30'] = np.nan
for i in range(4, len(df)):
df.loc[df.index[i],'ma5'] = df['close'][i-4:i+1].mean()
for i in range(30, len(df)):
df.loc[df.index[i],'ma30'] = df['close'][i-29:i+1].mean()
df
df['ma5'] = df['close'].rolling(5).mean()
df['ma30'] = df['close'].rolling(30).mean()
df
#df = df[:100]
df[['close','ma5','ma30']].plot()
plt.show()
## 方法一:
# golden_cross = []
# death_cross = []
# for i in range(1, len(df)):
# if df['ma5'][i] >= df['ma30'][i] and df['ma5'][i-1] < df['ma30'][i-1]:
# golden_cross.append(df.index[i]) #df.index[i].to_pydatetime() .to_pydatetime()转换成py的datetine
# if df['ma5'][i] <= df['ma30'][i] and df['ma5'][i-1] > df['ma30'][i-1]:
# death_cross.append(df.index[i])
# golden_cross
df = df.dropna()
df = df['2010-01-01':]
#方法二:
sr1 = df['ma5'] < df['ma30']
sr2 = df['ma5'] >= df['ma30']
death_cross = df[sr1 & sr2.shift(1)].index
golden_cross = df[-sr1 | sr2.shift(1)].index
golden_cross
###
first_money = 100000
money = first_money
hold = 0 #持有多少股
sr1 = pd.Series(1, index=golden_cross)
sr2 = pd.Series(0, index=death_cross)
sr = sr1.append(sr2).sort_index()
for i in range(0, len(sr)):
p = df['open'][sr.index[i]]
if sr.iloc[i] == 1:
#金叉
buy = (money // (100 * p))
hold += buy * 100
money -= buy * 100 * p
else:
money += hold + p
hold = 0
p = df['open'][-1]
now_money = hold * p + money
print(now_money - first_money)
----97618.177
双均线策略的JoinQuant实现
import jqdata def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) set_order_cost(OrderCost(open_tax=0, close_tax=0.001,open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') g.security = ['601318.XSHG'] g.p1 = 5 g.p2 = 60 def handle_data(context, data): for stock in g.security: #金叉: 如果5日均线大于10日均线并且不持仓 #死叉: 如果5日均线小于10日均线并且持仓 df = attribute_history(stock, g.p2) ma10 = df['close'].mean() ma5 = df['close'][-5:].mean() if ma10 > ma5 and stock in context.portfolio.positions: #死叉 order_target(stock, 0) if ma10 < ma5 and stock not in context.portfolio.positions: #金叉 order(stock, context.portfolio.available_cash * 0.8) record(ma5 = ma5, ma10 = ma10)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人