[Python] 2 Create a risk-return map for your asset portfolio

Twitter introduced the risk-return map of the portfolio that combines SPXL and TMF.

Save the code to create the graph here.

Obtain the TMF, SPXL, VTI csv files from the following site in advance (the period is MAX). (Actually, I should just apply the code to get ...)

TMF: https://www.nasdaq.com/market-activity/funds-and-etfs/tmf/historical SPXL: https://www.nasdaq.com/market-activity/funds-and-etfs/spxl/historical VTI: https://www.nasdaq.com/market-activity/funds-and-etfs/vti/historical

Save the files with the file names "TMF.csv", "SPXL.csv", and "VTI.csv", respectively.

1. Load the library.


#Invite frends to the party...
import numpy as np
import pandas as pd
from datetime import datetime
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

2. A function that combines csv files into one DataFrame


def make_df(etfs):
    df = pd.DataFrame()
    for etf in etfs:
        csvfile = etf +'.csv'
        csv_data = pd.read_csv(csvfile)
        csv_data.Date = pd.to_datetime(csv_data.Date)
        csv_data = csv_data.set_index('Date')
        csv_data= csv_data.rename(columns={' Close/Last': etf})
        df[etf] = csv_data[etf]
        df = df.sort_index().dropna()
    return df

3. A function that adds a diversified portfolio index to a DataFrame


def make_port_df(df):
    #Return calculation
    rtn = (df /  df.shift(1) -1).fillna(0)

    #Create portfolio data for each ratio
    for w in [9, 8, 7, 6, 5, 4, 3, 2, 1]:
        rtn['SPXL'+str(w)+' : TMF'+str(10-w)] =rtn['SPXL']*(w/10) + rtn['TMF']*(1-w/10)
    
    rtn += 1
    df = rtn.cumprod()
    
    return df 

4. A function that creates a risk-return map


def rr_map(df):
    #Monthly return calculation
    dfm = df.resample('M').ffill()
    m_rtn = (dfm /  dfm.shift(1) -1).dropna()

    #Risk calculation
    std = (m_rtn.std())*(12**0.5)
    
    #Annual return calculation
    cum = m_rtn+1
    a_rtn = (cum.product())**(12/len(m_rtn))-1
    
    #Risk-return map creation
    plt.figure(figsize=(6, 6))
    for asset in list(a_rtn.index):
        plt.scatter(x = std[asset], y = a_rtn[asset],label = asset)
    plt.xlabel('Risk')
    plt.ylabel('Return')
    plt.xlim(0,std.max()*1.1)
    plt.ylim(0,a_rtn.max()*1.1)
    plt.legend(loc = 'best')
    plt.title('Risk Return Map')
    
    plt.savefig('rr_map.png',bbox_inches="tight")

4. Execute the above function


etfs = ['SPXL','TMF','VTI']
df = make_df(etfs)
df = make_port_df(df)
rr_map(df)

↓ This graph is displayed. rr_map.png

5. Summary

Having about half of the SPXL and half of the TMF is likely to result in a portfolio with better risk-return characteristics than VTI (investment at your own risk).

6. Next issue

-[] Diversified portfolio of multiple assets

Recommended Posts

[Python] 2 Create a risk-return map for your asset portfolio
Create a model for your Django schedule
Create a python environment on your Mac
Let's create a virtual environment for Python
Create a LINE BOT with Minette for Python
Create a web map using Python and GDAL
Create a Python module
Create a Python environment
Create your own Big Data in Python for validation
Create a Layer for AWS Lambda Python with Docker
Create a Wox plugin (Python)
Create a function in Python
Create a dictionary in Python
Create a python numpy array
Create a directory with python
What is a python map?
Create a child account for connect with Stripe in Python
[Python] Create a date and time list for a specified period
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create a Python script for Wake on LAN (NAT traversal Wake on LAN [5])
Create a virtual environment for python on mac [Very easy]
Build a python environment on CentOS 7.7 for your home server
[Python] Create a screen for HTTP status code 403/404/500 with Django
Create a Python environment for professionals in VS Code on Windows
Create a Python execution environment for Windows with VScode + Remote WSL
Create a python GUI using tkinter
Create a DI Container in Python
Create a Python environment on Mac (2017/4)
Create a striped illusion with gamma correction for Python3 and openCV3
Create a color picker for the color wheel with Python + Qt (PySide)
Create a virtual environment with Python!
Create a binary file in Python
Try docker: Create your own container image for your Python web app
Create a python environment on centos
Create a Python general-purpose decorator framework
Python vba to create a date string for creating a file name
Create a CGH for branching a laser in Python (laser and SLM required)
Create a Kubernetes Operator in Python
5 Ways to Create a Python Chatbot
Create a random string in Python
Create a USB boot Ubuntu with a Python environment for data analysis
Prepare a Python virtual environment for your project with venv with VS Code
Create a shortcut to run a Python file in VScode on your terminal
Create a Python development environment locally at the fastest speed (for beginners)
Create a survival prediction model for Kaggle Titanic passengers without using Python
[Python / Tkinter] Search for Pandas DataFrame → Create a simple search form to display
Create a Python function decorator with Class
Create your own Linux commands in Python
Create a new Python numerical calculation project
Create wordcloud from your tweet with python3
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
Create a simple GUI app in Python
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a JSON object mapper in Python
Map rent information on a map with python
[Python] Create a Batch environment using AWS-CDK
[Mac] Building a virtual environment for Python
[Python] [LINE Bot] Create a parrot return LINE Bot
Make Qt for Python app a desktop app