基础
使得可显示出多个结果
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = 'all'
常用包
import pandas as pd
import numpy as np
from math import log, sqrt, exp
from datetime import date
import datetime
打开文件
data1 = pd.read_csv()
data1.head(
提取出列名
name_list = np.array(data.columns)[[1,2,3]]
改列名
df.columns = ['A','B']
df.rename(columns={'a':'A'})
转DataFrame
pd.DataFrame(list1)
设置种子数
np.random.seed(123)
随机数
np.random.uniform(0, 1, dim)
np.random.normal(mu, sigma, dim)
列表推导式
[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式] ]
RandomPortfolios.columns = [ticker + "_weight" for ticker in ticker_list]
定义方法
def Xxx(参数):
"""
Parameters
各个参数的描述
"""
表达式
按需看是否有return
创建零矩阵
zeros(shape, dtype=float, order='C')
np.zeros([simul, dim, N])
数据合并
data11 = pd.merge(data1.iloc[:,0:2],data2.iloc[:,0:2],on="日期",how = "inner")
data11.head(
合并后改名
dict1 = {"日期":"Date","收盘_x":"600276","收盘_y":"600900","收盘":"601318"}
data = data.rename(columns = dict1 )
保存数据
data.to_csv('good_data.csv',index=False,header=True)
画图
最基本的2个库
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
import seaborn as sns
其他库
import scipy.stats
from scipy import stats
热力图
correlation_matrix = stock_return.corr()
sns.heatmap(correlation_matrix,
annot=True,
cmap="YlGnBu",
linewidths=0.3,
annot_kws={"size": 8})
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.savefig("./image/corr.jpg", dpi=300, bbox_inches = 'tight')
plt.show()
cov_mat = stock_return.cov()
散点图 RandomPortfolios是DataFrame,‘Volatility’, 'Returns’是其字段,做x,y轴,每组(x,y)做一个点。
RandomPortfolios.plot('Volatility', 'Returns', kind='scatter', alpha=0.3)
plt.show()
多了一个Sharpe字段
plt.scatter(RandomPortfolios.Volatility, RandomPortfolios.Returns, c=RandomPortfolios.Sharpe)
plt.colorbar(label='Sharpe Ratio')
plt.ylabel('Return')
plt.xlabel("Volatility")
突出某个点,比如找某字段中最大的索引值,idxmax()
max_index = RandomPortfolios.Sharpe.idxmax()
RandomPortfolios.plot('Volatility', 'Returns', kind='scatter', alpha=0.3)
x = RandomPortfolios.loc[max_index,'Volatility']
y = RandomPortfolios.loc[max_index,'Returns']
plt.scatter(x, y, color='red')
plt.savefig("./image/Markowitz-Sharpe.jpg", dpi=300, bbox_inches = 'tight')
plt.show()
突出某个位置
plt.axvline(x=np.array(q_bs).mean(), linewidth=4, color='r')
保存图片,放在show() 前
plt.savefig("./image/corr.jpg", dpi=300, bbox_inches = 'tight')
|