Skip to content

Commit 5017ab6

Browse files
Yaroslav SmirnovYaroslav Smirnov
authored andcommitted
added portfolio stats, scatter plots and optimizers
1 parent b9d4d96 commit 5017ab6

6 files changed

Lines changed: 2982 additions & 1 deletion

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
google-python-exercises/
22
.idea/
33
python-trading/excel/
4+
ptyhon-trading/data/
45
python-trading/oanda_api.py
56
python_fundamentals/prank/

python-trading/data/GLD.csv

Lines changed: 2833 additions & 0 deletions
Large diffs are not rendered by default.

python-trading/histogram.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ def main():
2525
# Plot a histogram
2626
daily_returns.hist(bins=20)
2727

28-
2928
# Get the mean and standard deviation
3029
mean = daily_returns["SPY"].mean()
3130
print "mean: ", mean
@@ -40,6 +39,16 @@ def main():
4039
# Compute Kurtosis
4140
print "kurtosis: ", daily_returns["SPY"].kurtosis()
4241

42+
# Plot double histogram
43+
dates = pd.date_range("2009-01-01", "2012-12-31")
44+
symbols = ["SPY", "XOM"]
45+
df = get_data(symbols, dates)
46+
plot_data(df)
47+
daily_returns = compute_daily_returns(df)
48+
plot_data(daily_returns, title="Daily Returns", ylabel="Daily Returns")
49+
daily_returns["SPY"].hist(bins=20, label="SPY")
50+
daily_returns["XOM"].hist(bins=20, label="XOM")
51+
plt.show()
4352

4453
if __name__ == "__main__":
4554
main()

python-trading/optimizers.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
""" Minimize an objective function using SciPy. """
2+
3+
import pandas as pd
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
import scipy.optimize as spo
7+
8+
def f(x):
9+
# find a min value of x for the function to return the min value of y
10+
# suppose you have the following function:
11+
y = (x - 1.5)**2 + 0.5
12+
print "x = {}, y = {}".format(x, y) # for tracing
13+
return y
14+
15+
def main():
16+
xguess = 2.0 # give some value to start with
17+
min_result = spo.minimize(f, xguess, method="SLSQP", options={ "disp": True })
18+
print "Minina found at: "
19+
print "x = {}, y = {}".format(min_result.x, min_result.fun)
20+
21+
22+
if __name__ == "__main__":
23+
main()

python-trading/portfolio_stats.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
""" Portfolio Statistics """
2+
3+
# Cummulative return
4+
# Sharpe ratio = sqrt(sample_rate, e.g. 12 for months or 252 for trading days) * mean(daily_ret - risk-free-rate) / std(daily_ret - risk-free-rate)
5+
6+
import pandas as pd
7+
import matplotlib.pyplot as plt
8+
import numpy as np
9+
10+
from daily_returns import get_data, plot_data
11+
12+
def compute_daily_returns(df):
13+
daily_returns = df.copy()
14+
daily_returns[1:] = (df[1:] / df[:-1].values) - 1
15+
daily_returns.ix[0, :] = 0
16+
return daily_returns
17+
18+
def main():
19+
20+
# Initial values
21+
start_value = 10000
22+
dates = pd.date_range("2009-01-01", "2015-12-31")
23+
symbols = ["SPY", "XOM", "GLD", "AAPL"]
24+
allocations = [0.4, 0.1, 0.1, 0.4]
25+
26+
# Read data
27+
df = get_data(symbols, dates)
28+
plot_data(df)
29+
30+
# Basic calculations
31+
normalized = df / df.ix[0]
32+
plot_data(normalized, title="Assests Returns", ylabel="Assets Returns")
33+
allocated = normalized * allocations
34+
position_values = allocated * start_value
35+
portfolio_value = position_values.sum(axis=1)
36+
print portfolio_value.tail()
37+
plot_data(portfolio_value, title="Portfolio Value", ylabel="Portfolio Value")
38+
39+
# Compute daily returns
40+
daily_returns = (portfolio_value / portfolio_value.shift(1)) - 1
41+
daily_returns = daily_returns.ix[1:] # Get rid of first row which is just zeros
42+
plot_data(daily_returns, title="Daily Returns", ylabel="Daily Returns")
43+
44+
# Portfolio Statistics
45+
cummularive_return = portfolio_value[-1] / portfolio_value[0] - 1
46+
avg_daily_return = daily_returns.mean()
47+
std_daily_return = daily_returns.std()
48+
sharpe_ratio_daily = np.sqrt(252) * avg_daily_return / std_daily_return
49+
50+
print "PORTFOLIO STATISTICS"
51+
print "Cummulative return: ", round(cummularive_return * 100, 2), "%"
52+
print "Average daily return: ", round(avg_daily_return * 100, 2), "%"
53+
print "Standard deviation of daily returns: ", round(std_daily_return * 100, 2), "%"
54+
print "Sharpe ratio: ", round(sharpe_ratio_daily, 2)
55+
56+
if __name__ == "__main__":
57+
main()

python-trading/scatter_plots.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
""" Scatter plots, Correlations, Beta and Alpha """
2+
3+
# Beta is a slope of the line. The steeper it is, the steeper the growth compared to market (SPY in this context).
4+
# e.g. If market goes 1% up, with Beta 2 the stock would go up 2%.
5+
# Beta shows how REACTIVE stock/asset is compared to the market.
6+
# Alpha is how much higher the line is above central cross. It means how much the stock outperforms the market.
7+
# Higher Alpha - better performance.
8+
9+
import pandas as pd
10+
import matplotlib.pyplot as plt
11+
import numpy as np
12+
13+
from daily_returns import get_data, plot_data
14+
15+
def compute_daily_returns(df):
16+
daily_returns = df.copy()
17+
daily_returns[1:] = (df[1:] / df[:-1].values) - 1
18+
daily_returns.ix[0, :] = 0
19+
return daily_returns
20+
21+
def main():
22+
# Read data
23+
dates = pd.date_range("2009-01-01", "2012-12-31")
24+
symbols = ["SPY", "XOM", "GLD"]
25+
df = get_data(symbols, dates)
26+
plot_data(df)
27+
28+
# Compute daily returns
29+
daily_returns = compute_daily_returns(df)
30+
plot_data(daily_returns, title="Daily Returns", ylabel="Daily Returns")
31+
32+
# Scatter plot SPY vs XOM
33+
daily_returns.plot(kind="scatter", x="SPY", y="XOM")
34+
beta_XOM, alpha_XOM = np.polyfit(daily_returns["SPY"], daily_returns["XOM"], 1)
35+
plt.plot(daily_returns["SPY"], beta_XOM * daily_returns["SPY"] + alpha_XOM, "-", color="r")
36+
print "XOM"
37+
print "Beta XOM: ", beta_XOM
38+
print "Alpha XOM: ", alpha_XOM
39+
print "\n"
40+
plt.show()
41+
42+
# Scatter plot SPY vs GLD
43+
daily_returns.plot(kind="scatter", x="SPY", y="GLD")
44+
beta_GLD, alpha_GLD = np.polyfit(daily_returns["SPY"], daily_returns["GLD"], 1)
45+
plt.plot(daily_returns["SPY"], beta_GLD * daily_returns["SPY"] + alpha_GLD, "-", color="y")
46+
print "GLD"
47+
print "Beta GLD: ", beta_GLD
48+
print "Alpha GLD: ", alpha_GLD
49+
print "\n"
50+
plt.show()
51+
52+
# Calculate correlation coefficient
53+
print daily_returns.corr(method="pearson")
54+
55+
56+
57+
if __name__ == "__main__":
58+
main()

0 commit comments

Comments
 (0)