import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
# Load stock data
stock_ticker = '^GSPC'
df = yf.download(stock_ticker)
# List arrays for close price and dates
close_price = df["Adj Close"]
dates = df.index.tolist()
# Returns
daily_returns = close_price.pct_change(fill_method='pad')
monthly_returns = close_price.resample('M').ffill().pct_change(fill_method='pad')
monthly_returns
[*********************100%***********************] 1 of 1 completed
# Use websockets, bs4, or quandl
# Plot stock price over time
plt.figure(figsize=(8, 5), dpi = 100)
plt.plot(close_price) #Can use [-timescale:] to slice plot
plt.xlabel("Year")
plt.ylabel("Price (USD)")
plt.title(stock_ticker + " Stock Price")
plt.grid()
plt.show()
# Plot daily and monthly returns
plt.figure(figsize=(8, 5), dpi = 100)
plt.plot(daily_returns, label = "Daily Returns")
plt.plot(monthly_returns, label = "Monthly Returns")
plt.xlabel("Year")
plt.ylabel("Returns (USD)")
plt.title(stock_ticker + " Daily and Monthly Returns")
plt.grid()
plt.legend()
plt.show()
timescape = 36 #how long we want to simulate in months
# Buy and sell conditions
buy_x = 100
value1 = buy_x / close_price[0]
def monthly_buy(_timescape):
global value1, buy_x, timescape
#print(_timescape)
if _timescape < 0 :
print('You have this many shares: ' + str(value1))
print('Portfolio value:' + str(value1*close_price[30 * (timescape - _timescape)]))
return
elif _timescape == timescape - 1:
print('Starting shares: ' + str(value1))
print('Portfolio value:' + str(value1*close_price[30 * (timescape - _timescape)]))
this_month = close_price[30 * (timescape - _timescape)]
value1 += buy_x / this_month
monthly_buy(_timescape - 1)
monthly_buy(35)
#1. Buy $x on the first date. Buy $x every month thereafter.
# Calculate the portfolio value (which would be my expected returns) on a specified date.
Starting shares: 0.060984161686640864
Portfolio value:103.55476916690812
You have this many shares: 1.778368274288642
Portfolio value:5019.319846832348
taken_out = 0
timescape = 36
_value2 = buy_x / close_price[0] # shares
_limit = (timescape - 30) * 30
_baseP = close_price[0]
_lastb = 0
def strategic_sell():
global taken_out, _limit
global _baseP, _lastb, _value2
for day in range(0, _limit):
if close_price[day] <= close_price[day-1] * .98:
# buy value of buy_x
print("bought +" + str(buy_x/close_price[day]))
_value2 += buy_x / close_price[day]
_lastb = day
_baseP = close_price[day]
'''
if close_price[day] >= (close_price[day-1] * 0.1):
#print("selling, old shares: " + str(_value2))
# sell half value of buy_x
_val = (close_price[day] * _value2) - (50) #substract 50$ from share value in $
_value2 = _val / close_price[day] #convert $ value back to shares
#print("selling, new shares: " + str(_value2))
taken_out += 50
_lastb = day
_baseP = close_price[day]
'''
if day - _lastb >= 30:
#print("bought +" + str(buy_x/close_price[day]))
# buy value of buy_x
_value2 += buy_x / close_price[day]
_lastb = day
_baseP = close_price[day]
print("final portfolio price: " + str(_value2 * close_price[timescape * 30]))
print("final account balance: " + str(taken_out))
print("last traded day " + str(_lastb))
print("last traded price: " + str(_baseP));
strategic_sell()
#2. Buy $x on the first date. Buy $x again if the price drops by 10%.
# Sell 0.5*$x if the price increases by 10%.
# Buy $x if 30 days have surpassed and no buy/sell order has been made.
#DO WE WANNA CONSIDER SELLS???
bought +5.662514205211274
bought +5.868544285633054
bought +5.165289093355255
bought +5.353318970358496
bought +5.316321256736941
final portfolio price: 475.4681252503131
final account balance: 0
last traded day 168
last traded price: 23.030000686645508
close_price[0] / close_price[_limit-1]
plt.plot(range(0, 180), close_price[0:180])
_value2
# My account
account = 0
# To Trade
buy_amount = 100
portfolio_shares = 0
initial_share = buy_amount/close_price[0]
def buy(day):
portfolio_shares += buy_amount/close_price[day]
def sell(day):
account += 0.30*portfolio_shares*close_price[day]
portfolio_shares = 0.70*portfolio_shares*close_price[day]
def strat(stockprices):
for i in range(1,len(stockprices)):
day = i
todays_price = stockprices[i]
if todays_price > 1.1*stockprices[i-1]:
sell(i)
elif todays_price < 0.9*stockprices[i-1]:
buy(i)
print("Account value: " + str(account))
print("Portfolio shares: " + str(portfolio_shares))
print("Portfolio value: " + str(portfolio_shares*stockprices[-1]))
strat(close_price)
SyntaxError: invalid syntax (2897226725.py, line 13)