Tuesday, 5 November 2019

python finance 7 merge csv

merge all csv files into one that has date and each company's daily closing price

about 500 companies record, skip a few unfounded csv file

save merged csv in joined_closes

import datetime as dt
import pandas as pd
import pandas_datareader.data as web
import bs4 as bs
import pickle
import requests
import os

def compile_data():
    with open('sp500tickers.pickle', 'rb') as f:
        tickers = pickle.load(f)

    main_df = pd.DataFrame()

    for count, ticker in enumerate(tickers):
        try:
            ticker = ticker.strip('\n').split('.')[0]

            df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))
            df.set_index('Date', inplace=True)

            #only interested in closing price, drop the rest, change column header to company name
            df.rename(columns = {'Adj Close': ticker}, inplace=True)
            df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True)

            if main_df.empty:
                main_df = df
            else:
                #concat columns from different csv
                main_df = main_df.join(df, how='outer')

            if count % 10 == 0:
                print(count)
        except:
            print(ticker, ' not found')

    print(main_df.tail())
    main_df.to_csv('sp500_joined_closes.csv')

compile_data()

reference:
https://www.youtube.com/watch?v=j0zW_KXyQJ4&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=7

python finance 6 downloading all s&p 500 historic data

save data in symbol.csv

data contains date, high, low, open, close, volume, adj close

resume downloading from last, if not downloaded in one time

import datetime as dt
import pandas_datareader.data as web
import bs4 as bs
import pickle
import requests
import os

#get all s&p500 symbols, save in pickle
def save_sp500_tickers():
    resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
    soup = bs.BeautifulSoup(resp.text, 'lxml')
    table = soup.find('table', {'class': 'wikitable sortable'})
    tickers = []
    for row in table.findAll('tr')[1:]:
        ticker = row.findAll('td')[0].text
        tickers.append(ticker)

    with open('sp500tickers.pickle', 'wb') as f:
        pickle.dump(tickers, f)

    #print(tickers)
    return tickers

#save_sp500_tickers()

#get historic data from yahoo for all companies in pickle file
def get_data_from_yahoo(reload_sp500=False):
    if reload_sp500:
        tickers = save_sp500_tickers()
    else:
        with open('sp500tickers.pickle','rb') as f:
            tickers = pickle.load(f)

    if not os.path.exists('stock_dfs'):
        os.makedirs('stock_dfs')

    start = dt.datetime(2011, 1, 1)
    end = dt.datetime(2019, 10, 31)

    for ticker in tickers:
        try:
            ticker = ticker.strip('\n').split('.')[0]
            if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
                print('downloading ', ticker)
                df = web.DataReader(ticker, 'yahoo', start, end)
                df.to_csv('stock_dfs/{}.csv'.format(ticker))
            else:
                print('Already have {}'.format(ticker))
        except:
            print(ticker, ' not found')
get_data_from_yahoo()

reference:
https://www.youtube.com/watch?v=baCAFPHb1o4&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=6
https://github.com/pydata/pandas-datareader/issues/614

Sunday, 3 November 2019

python finance 5 beautifulsoup fetch and save data from wiki

wiki s&p 500 companies
goal is to fetch all company symbols from table

ctrl + U to inspect element
ctrl + F find table class = 'wikitable sortable'
skip first  header row 
fetch the first symbol column from tbody


symbols saved in pickle file

import bs4 as bs
import pickle
import requests

def save_sp500_tickers():
    resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
    soup = bs.BeautifulSoup(resp.text, 'lxml')
    table = soup.find('table', {'class': 'wikitable sortable'})
    tickers = []
    #skip table header
    for row in table.findAll('tr')[1:]:
        #save first column of tbody
        ticker = row.findAll('td')[0].text
        tickers.append(ticker)

    with open('sp500tickers.pickle', 'wb') as f:
        pickle.dump(tickers, f)

    print(tickers)
    return tickers

save_sp500_tickers()

reference:
https://www.youtube.com/watch?v=C--57BP79EM&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=5

Saturday, 2 November 2019

python finance 4 candlestick

candlestick sampled every 10 days
top graph: zoomed ohlc (open high low close)
bottom graph: trading volume summed over sample time
#powershell
pip install mpl_finance

---------------------------
#pycharm
#resample data

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
import pandas as pd
import pandas_datareader.data as web

df = pd.read_csv('tsla_csv', parse_dates=True, index_col=0)

#open high low
df_ohlc = df['Adj Close'].resample('10D').ohlc()
df_volume = df['Volume'].resample('10D').sum()
#print(df_ohlc.head())

-----------------------
#log
#every 10 days

        Date       open       high        low      close
0 2011-01-03  26.620001  28.450001  26.620001  26.959999
1 2011-01-13  26.219999  26.219999  22.620001  23.040001
2 2011-01-23  24.490000  24.920000  23.910000  23.910000
3 2011-02-02  23.940001  24.490000  23.070000  23.250000
4 2011-02-12  23.080000  24.730000  22.840000  23.180000

------------------------------
#pycharm
#change date format for plot

df_ohlc.reset_index(inplace=True)

df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)
#print(df_ohlc.head())

---------------------------------
#log

       Date       open       high        low      close
0  734140.0  26.620001  28.450001  26.620001  26.959999
1  734150.0  26.219999  26.219999  22.620001  23.040001
2  734160.0  24.490000  24.920000  23.910000  23.910000
3  734170.0  23.940001  24.490000  23.070000  23.250000
4  734180.0  23.080000  24.730000  22.840000  23.180000

-------------------------------
#pycharm

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
ax1.xaxis_date()

candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g')
ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0)

plt.show()

reference:
https://www.youtube.com/watch?v=19yyasfGLhk&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=4
https://stackoverflow.com/questions/42373104/since-matplotlib-finance-has-been-deprecated-how-can-i-use-the-new-mpl-finance

Thursday, 31 October 2019

python finance 3 rolling average

daily stock price, 100 day rolling average, and trade volume

synchronized zoom on volume and price graphs

df = pd.read_csv('tsla_csv', parse_dates=True, index_col=0)

#100 day rolling average, for the first 100 days, average beginning to current day
df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean()
#df.dropna(inplace=True)
#print(df.head())

#price graph height 5 x volumn graph height, share x axis (date)
ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)

ax1.plot(df.index, df['Adj Close'])
ax1.plot(df.index, df['100ma'])
ax2.bar(df.index, df['Volume'])

plt.show()  

reference:
https://www.youtube.com/watch?v=QAkOnV1-lIg&list=PLQVvvaa0QuDcOdF96TBtRtuQksErCEBYZ&index=3
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.subplot2grid.html

Wednesday, 30 October 2019

Python Programming for Finance 2

Tesla stock 2011-2019


import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web

style.use('ggplot')
#save web data in local csv file for better performance
'''
start = dt.datetime(2011, 1, 1)
end = dt.datetime(2019, 10, 30)

df = web.DataReader('TSLA', 'yahoo', start, end)
df.to_csv('tsla_csv')
'''
df = pd.read_csv('tsla_csv', parse_dates=True, index_col=0)
#print(df.head())
df['Adj Close'].plot()
plt.show()