日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python画蜡烛致敬烈士_「」matplotlib 股票-用python绘制蜡烛线型k线图是用代码还是绘图工具-TOP金融网...

發布時間:2023/12/10 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python画蜡烛致敬烈士_「」matplotlib 股票-用python绘制蜡烛线型k线图是用代码还是绘图工具-TOP金融网... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

用python繪制蠟燭線型k線圖是用代碼還是繪圖工具

import?matplotlib.pyplot?as?plt

from?matplotlib.dates?import?DateFormatter,?WeekdayLocator,?DayLocator,?MONDAY,YEARLY

from?matplotlib.finance?import?quotes_historical_yahoo_ohlc,?candlestick_ohlc

plt.rcParams['font.sans-serif']?=?['SimHei']

plt.rcParams['axes.unicode_minus']?=?False

ticker?=?'600028'?#?600028?是"中國石化"的股票代碼

ticker?+=?'.ss'???#?.ss?表示上證?.sz表示深證

date1?=?(2015,?8,?1)?#?起始日期,格式:(年,月,日)元組

date2?=?(2016,?1,?1)??#?結束日期,格式:(年,月,日)元組

mondays?=?WeekdayLocator(MONDAY)????????????#?主要刻度

alldays?=?DayLocator()??????????????????????#?次要刻度

#weekFormatter?=?DateFormatter('%b?%d')?????#?如:Jan?12

mondayFormatter?=?DateFormatter('%m-%d-%Y')?#?如:2-29-2015

dayFormatter?=?DateFormatter('%d')??????????#?如:12

quotes?=?quotes_historical_yahoo_ohlc(ticker,?date1,?date2)

if?len(quotes)?==?0:

raise?SystemExit

fig,?ax?=?plt.subplots()

fig.subplots_adjust(bottom=0.2)

ax.xaxis.set_major_locator(mondays)

ax.xaxis.set_minor_locator(alldays)

ax.xaxis.set_major_formatter(mondayFormatter)

#ax.xaxis.set_minor_formatter(dayFormatter)

#plot_day_summary(ax,?quotes,?ticksize=3)

candlestick_ohlc(ax,?quotes,?width=0.6,?colorup='r',?colordown='g')

ax.xaxis_date()

ax.autoscale_view()

plt.setp(plt.gca().get_xticklabels(),?rotation=45,?horizontalalignment='right')

ax.grid(True)

plt.title('中國石化?600028')

plt.show()

如何用python實現Markowitz投資組合優化

0.導入需要的包import pandas as pd

import numpy as np

import statsmodels.api as sm #統計運算

import scipy.stats as scs #科學計算

import matplotlib.pyplot as plt #繪圖

1.選取幾只感興趣的股票

000413 東旭光電,000063 中興通訊,002007 華蘭生物,000001 平安銀行,000002 萬科A

并比較一下數據(2015-01-01至2015-12-31)

In[1]:

stock_set = ['000413.XSHE','000063.XSHE','002007.XSHE','000001.XSHE','000002.XSHE']

noa = len(stock_set)

df = get_price(stock_set, start_date = '2015-01-01', end_date ='2015-12-31', 'daily', ['close'])

data = df['close']

#規范化后時序數據

(data/data.ix[0]*100).plot(figsize = (8,5))

Out[1]:

2.計算不同證券的均值、協方差

每年252個交易日,用每日收益得到年化收益。計算投資資產的協方差是構建資產組合過程的核心部分。運用pandas內置方法生產協方差矩陣。

In [2]:

returns = np.log(data / data.shift(1))

returns.mean()*252

Out[2]:

000413.XSHE 0.184516

000063.XSHE 0.176790

002007.XSHE 0.309077

000001.XSHE -0.102059

000002.XSHE 0.547441

In [3]:

returns.cov()*252

Out[3]:

3.給不同資產隨機分配初始權重

由于A股不允許建立空頭頭寸,所有的權重系數均在0-1之間

In [4]:

weights = np.random.random(noa)

weights /= np.sum(weights)

weights

Out[4]:

array([ 0.37505798, 0.21652754, 0.31590981, 0.06087709, 0.03162758])

4.計算預期組合年化收益、組合方差和組合標準差

In [5]:

np.sum(returns.mean()*weights)*252

Out[5]:

0.21622558669017816

In [6]:

np.dot(weights.T, np.dot(returns.cov()*252,weights))

Out[6]:

0.23595133640121463

In [7]:

np.sqrt(np.dot(weights.T, np.dot(returns.cov()* 252,weights)))

Out[7]:

0.4857482232609962

5.用蒙特卡洛模擬產生大量隨機組合

進行到此,我們最想知道的是給定的一個股票池(證券組合)如何找到風險和收益平衡的位置。

下面通過一次蒙特卡洛模擬,產生大量隨機的權重向量,并記錄隨機組合的預期收益和方差。

In [8]:

port_returns = []

port_variance = []

for p in range(4000):

weights = np.random.random(noa)

weights /=np.sum(weights)

port_returns.append(np.sum(returns.mean()*252*weights))

port_variance.append(np.sqrt(np.dot(weights.T, np.dot(returns.cov()*252, weights))))

port_returns = np.array(port_returns)

port_variance = np.array(port_variance)

#無風險利率設定為4%

risk_free = 0.04

plt.figure(figsize = (8,4))

plt.scatter(port_variance, port_returns, c=(port_returns-risk_free)/port_variance, marker = 'o')

plt.grid(True)

plt.xlabel('excepted volatility')

plt.ylabel('expected return')

plt.colorbar(label = 'Sharpe ratio')

Out[8]:

6.投資組合優化1——sharpe最大

建立statistics函數來記錄重要的投資組合統計數據(收益,方差和夏普比)

通過對約束最優問題的求解,得到最優解。其中約束是權重總和為1。

In [9]:

def statistics(weights):

weights = np.array(weights)

port_returns = np.sum(returns.mean()*weights)*252

port_variance = np.sqrt(np.dot(weights.T, np.dot(returns.cov()*252,weights)))

return np.array([port_returns, port_variance, port_returns/port_variance])

#最優化投資組合的推導是一個約束最優化問題

import scipy.optimize as sco

#最小化夏普指數的負值

def min_sharpe(weights):

return -statistics(weights)[2]

#約束是所有參數(權重)的總和為1。這可以用minimize函數的約定表達如下

cons = ({'type':'eq', 'fun':lambda x: np.sum(x)-1})

#我們還將參數值(權重)限制在0和1之間。這些值以多個元組組成的一個元組形式提供給最小化函數

bnds = tuple((0,1) for x in range(noa))

#優化函數調用中忽略的唯一輸入是起始參數列表(對權重的初始猜測)。我們簡單的使用平均分布。

opts = sco.minimize(min_sharpe, noa*[1./noa,], method = 'SLSQP', bounds = bnds, constraints = cons)

opts

Out[9]:

status: 0

success: True

njev: 4

nfev: 28

fun: -1.1623048291871221

x: array([ -3.60840218e-16, 2.24626781e-16, 1.63619563e-01, -2.27085639e-16, 8.36380437e-01])

message: 'Optimization terminated successfully.'

jac: array([ 1.81575805e-01, 5.40387481e-01, 8.18073750e-05, 1.03137662e+00, -1.60038471e-05, 0.00000000e+00])

nit: 4

得到的最優組合權重向量為:

In [10]:

opts['x'].round(3)

Out[10]:

array([-0. , 0. , 0.164, -0. , 0.836])

sharpe最大的組合3個統計數據分別為:

In [11]:

#預期收益率、預期波動率、最優夏普指數

statistics(opts['x']).round(3)

Out[11]:

array([ 0.508, 0.437, 1.162])

7.投資組合優化2——方差最小

接下來,我們通過方差最小來選出最優投資組合。

In [12]:

#但是我們定義一個函數對 方差進行最小化

def min_variance(weights):

return statistics(weights)[1]

optv = sco.minimize(min_variance, noa*[1./noa,],method = 'SLSQP', bounds = bnds, constraints = cons)

optv

Out[12]:

status: 0

success: True

njev: 7

nfev: 50

fun: 0.38542969450547221

x: array([ 1.14787640e-01, 3.28089742e-17, 2.09584008e-01, 3.53487044e-01, 3.22141307e-01])

message: 'Optimization terminated successfully.'

jac: array([ 0.3851725 , 0.43591119, 0.3861807 , 0.3849672 , 0.38553924, 0. ])

nit: 7

方差最小的最優組合權重向量及組合的統計數據分別為:

In [13]:

optv['x'].round(3)

Out[13]:

array([ 0.115, 0. , 0.21 , 0.353, 0.322])

In [14]:

#得到的預期收益率、波動率和夏普指數

statistics(optv['x']).round(3)

Out[14]:

array([ 0.226, 0.385, 0.587])

8.組合的有效前沿

有效前沿有既定的目標收益率下方差最小的投資組合構成。

在最優化時采用兩個約束,1.給定目標收益率,2.投資組合權重和為1。

In [15]:

def min_variance(weights):

return statistics(weights)[1]

#在不同目標收益率水平(target_returns)循環時,最小化的一個約束條件會變化。

target_returns = np.linspace(0.0,0.5,50)

target_variance = []

for tar in target_returns:

cons = ({'type':'eq','fun':lambda x:statistics(x)[0]-tar},{'type':'eq','fun':lambda x:np.sum(x)-1})

res = sco.minimize(min_variance, noa*[1./noa,],method = 'SLSQP', bounds = bnds, constraints = cons)

target_variance.append(res['fun'])

target_variance = np.array(target_variance)

下面是最優化結果的展示。

叉號:構成的曲線是有效前沿(目標收益率下最優的投資組合)

紅星:sharpe最大的投資組合

黃星:方差最小的投資組合

In [16]:

plt.figure(figsize = (8,4))

#圓圈:蒙特卡洛隨機產生的組合分布

plt.scatter(port_variance, port_returns, c = port_returns/port_variance,marker = 'o')

#叉號:有效前沿

plt.scatter(target_variance,target_returns, c = target_returns/target_variance, marker = 'x')

#紅星:標記最高sharpe組合

plt.plot(statistics(opts['x'])[1], statistics(opts['x'])[0], 'r*', markersize = 15.0)

#黃星:標記最小方差組合

plt.plot(statistics(optv['x'])[1], statistics(optv['x'])[0], 'y*', markersize = 15.0)

plt.grid(True)

plt.xlabel('expected volatility')

plt.ylabel('expected return')

plt.colorbar(label = 'Sharpe ratio')

【本文標題和網址】matplotlib 股票-用python繪制蠟燭線型k線圖是用代碼還是繪圖工具:http://www.jjta.cn/pzzx/201144.html

聲明本站分享的文章旨在促進信息交流,不以盈利為目的,本文觀點與本站立場無關,不承擔任何責任。如有傷害到您的利益,請聯系站長刪除!

總結

以上是生活随笔為你收集整理的python画蜡烛致敬烈士_「」matplotlib 股票-用python绘制蜡烛线型k线图是用代码还是绘图工具-TOP金融网...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。