[PYTHON] Quantopian Tutorial LESSON 8

This is a continuation of Last time.

LESSON 8 Your Portfolio and Plotting Variables

context.portfolio It is a context object that was used like a receiver of global variables so far, but aportfolio object is prepared under it. This object contains various information (property) about the portfolio.

Properties Contents
capital_used Cash consumed by the transaction
cash Cash remaining in the portfolio
pnl Realized P / L and Unrealized P / L
positions All open positions keyed by security ID
portfolio_value Total of cash and open positions
positions_value Total open positions
returns Cumulative P & L for Positions (10% return is 0.1)
starting_cash Initial capital
start_date Start Date and Time (UTC), the date and time when the algorithm was executed for live trading

The code below closes all the positions you own.

for security in context.portfolio.positions:
    order_target_percent(security, 0)

Plotting Variables By using the record () function, you can graph the data you want to record. Up to 5 types of data can be recorded (plot).

The code below executes AAPL longs and SPY shorts by 50% each daily, and records the cash used and the remaining cash using the recode () function at the daily close. [^ 1]

def initialize(context):
    context.aapl = sid(24)
    context.spy = sid(8554)

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())

def rebalance(context, data):
    order_target_percent(context.aapl, 0.50)
    order_target_percent(context.spy, -0.50)

def record_vars(context, data):
    record(capital_used=context.portfolio.capital_used,
           cash=context.portfolio.cash)

image.png

[^ 1]: Changed Original Tutorial Code.

LESSON 7<-->LESSON9

Recommended Posts

Quantopian Tutorial LESSON 10
Quantopian Tutorial LESSON 8
Quantopian Tutorial LESSON 1, 2
Quantopian Tutorial LESSON 6
Quantopian Tutorial LESSON 9
Quantopian Tutorial LESSON 5
Quantopian Tutorial LESSON 3
Quantopian Tutorial LESSON 7
Quantopian Tutorial LESSON 4
Quantopian Tutorial LESSON 11
sqlalchemy tutorial
PyODE Tutorial 2
Python tutorial
PyODE Tutorial 1
PyODE Tutorial 3
TensorFlow tutorial tutorial