# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#解决中文显示问题
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# %%
df = pd.read_excel('沪深300成分股收盘价.xlsx')
# %%
stock = df.iloc[:, 1:]
# %%
stock
# %%
# 计算差价
stock = stock.diff()
# %%
stock
# %%
date = df.iloc[:, 0]
# %%
date
# %%
# 设置行索引
stock = stock.set_index(keys=date)
# %%
# 表转置
stock = stock.T
# %%
stock
# %%
stock = stock.iloc[:, 1:]
# %%
stock
# %%
stock_list = []
gain_list = []
for i in list(stock):
var = stock.sort_values(by=i, ascending=False) # 对每1列进行降序排序
gain = list(var[i])
gain_list.append(gain)
var = list(var.index) # 获取行索引
stock_list.append(var)
# %%
# 每周涨幅的降序排名列表
stock_list
# %%
gain_list
# %%
# 将2维列表转换为1维列表
list1 = []
for i in gain_list:
for j in i:
list1.append(j)
# %%
list1
# %%
# 将1维列表按每60个为间隔拆分为2维列表
gain_list = [list1[i:i+60] for i in range(0,len(list1),60)]
# %%
gain_list
# %%
# 将2维列表第1层进行求和
list1 = []
for i in gain_list:
list1.append(sum(i))
# %%
list1
# %%
# 将1维列表按每5个为间隔拆分为2维列表
gain_list = [list1[i:i+5] for i in range(0,len(list1),5)]
# %%
gain_list
# %%
print(len(gain_list))
# %%
# 每个组合每1周的涨幅
list1 = list(zip(*gain_list)) # 将2维列表对应的元素进行打包
gain_list = [list1[i:i+5] for i in range(0,len(list1),5)] # 有误
# %%
gain_list
# %%
list1 = []
for i in gain_list:
for j in i:
for k in j:
list1.append(k)
gain_list = [list1[i:i+369] for i in range(0,len(list1),369)]
# %%
gain_list
# %%
combination1_gain = gain_list[0]
combination2_gain = gain_list[1]
combination3_gain = gain_list[2]
combination4_gain = gain_list[3]
combination5_gain = gain_list[4]
# %%
plt.figure(figsize=(20, 10), dpi=100)
date = list(date)
date = date[1:]
# %%
date
# %%
plt.figure(figsize=(40, 40), dpi=100) # 图像的大小
plt.plot(date, combination1_gain, c='red', label="组合1")
plt.plot(date, combination2_gain, c='green', label="组合2")
plt.plot(date, combination3_gain, c='blue', label="组合3")
plt.plot(date, combination4_gain, c='black', label="组合4")
plt.plot(date, combination5_gain, c='orange', label="组合5")
plt.scatter(date, combination1_gain, c='red')
plt.scatter(date, combination2_gain, c='green')
plt.scatter(date, combination3_gain, c='blue')
plt.scatter(date, combination4_gain, c='black')
plt.scatter(date, combination5_gain, c='orange')
plt.legend(loc='best')
plt.yticks(range(-2500, 2000, 100)) # y轴的范围
plt.grid(True, linestyle='--', alpha=0.5)
plt.xlabel("日期", fontdict={'size': 30})
plt.ylabel("上周涨跌幅", fontdict={'size': 30})
plt.title("五个组合每周持仓的对应因子值(上周涨跌幅)", fontdict={'size': 35})
plt.show()
标签:每行,%%,list,乱码,plt,差值,gain,date,stock
From: https://www.cnblogs.com/tiansz/p/16723571.html