# 用Python建立高效的货运和卡车库存组合

• Yamato Holdings (YATRY)
• Knight-Swift Transportation Holdings (KNX)
• BEST (BEST)
• YRC Worldwide (YRCW)
• Schneider National (SNDR)
• Old Dominion Freight Line (ODFL)
• Arc Best (ARCB)
• Werner Enterprises (WERN)

```＃导入相关模块

import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
import statistics as stat
import random as rnd
from matplotlib.ticker import StrMethodFormatter```

```＃指定股价数据收集期间的相关开始和结束日期
start_date = datetime.datetime(2020,4,1)
end_date = datetime.datetime(2020,9,30)```

```＃define函数返回每日收益列表
def returns(df):
prices = df["Close"]
returns = [0 if i == 0 else (prices[i]-prices[i-1])/(prices[i-1]) for i in range(0,len(prices))]
return(returns)```

```＃define函数可以构造具有标准偏差和平均每日收益的数据框
def analyzeStocks(tickersArr,start_date,end_date):
# create empty data frame template
index = ["ticker","return","stdev"]
muArr = []
sigmaArr = []
# loop through all tickers
for i in range(0,len(tickersArr)):
tick = tickersArr[i]
# get stock price data
# calculate average daily return
muArr.append(stat.mean(returns(data)))
# calculate standard deviation
sigmaArr.append(stat.stdev(returns(data)))
# return a data frame
return(pd.DataFrame(np.array([tickersArr, muArr, sigmaArr]),index=index,columns=tickersArr))```

`tickersArr = ["YATRY","KNX","BEST","YRCW","SNDR","ODFL","ARCB","WERN"]`

```base_df = analyzeStocks(tickersArr,start_date,end_date)
base_df
```

```plt.figure(figsize=(15,8))
muArr = [float(i) for i in base_df.iloc[1,]]
sigmaArr = [float(i) for i in base_df.iloc[2,]]
sharpeArr = [muArr[i]/sigmaArr[i] for i in range(0,len(muArr))]
plt.scatter(sigmaArr,muArr,c=sharpeArr,cmap="plasma")
plt.title("Historical avg. returns vs. standard deviations [single stocks]",size=22)
plt.xlabel("Standard deviation",size=14)
plt.ylabel("Avg. daily return",size=14)
```
`Text(0, 0.5, 'Avg. daily return')`

```＃函数用于创建定义数量的投资组合
def portfolioBuilder(n,tickersArr,start_date,end_date):
muArr = []
sigmaArr = []
dailyreturnsArr = []
weightedreturnsArr = []
portfoliodailyreturnsArr = []
＃填充每日收益
for i in range(0,len(tickersArr)):
dailyreturnsArr.append(returns(data))
＃创建n个不同的投资组合
for i in range(0,n):
＃重置每日投资组合列表
portfoliodailyreturnsArr = []
＃创建投资组合权重
weightsArr = [rnd.uniform(0,1) for i in range(0,len(tickersArr))]
nweightsArr = [i/sum(weightsArr) for i in weightsArr]
＃权衡每日收益
for j in range(0,len(dailyreturnsArr[0])):
temp = 0
for k in range(0,len(tickersArr)):
temp = temp + float(dailyreturnsArr[k][j])*float(nweightsArr[k])
portfoliodailyreturnsArr.append(temp)
＃计算并附加每日平均加权投资组合收益
muArr.append(stat.mean(portfoliodailyreturnsArr))
＃计算并附加加权投资组合日收益的标准差
sigmaArr.append(stat.stdev(portfoliodailyreturnsArr))
＃返回所创建投资组合的预期收益和标准差
return([sigmaArr,muArr])```

```portfoliosArr = portfolioBuilder(500000,tickersArr,start_date,end_date)
plt.figure(figsize=(15,8))
muArr = [float(portfoliosArr[1][i]) for i in range(0,len(portfoliosArr[1]))]
sigmaArr = [float(portfoliosArr[0][i]) for i in range(0,len(portfoliosArr[0]))]
sharpeArr = [muArr[i]/sigmaArr[i] for i in range(0,len(muArr))]
plt.scatter(sigmaArr,muArr,c=sharpeArr,cmap="plasma")
plt.title("Historical avg. returns vs. standard deviations [single stocks]",size=22)
plt.colorbar(label="Sharpe ratio")
plt.xlabel("Standard deviation",size=14)
plt.ylabel("Avg. daily returns",size=14)
```
`Text(0, 0.5, 'Avg. daily returns')`