├── Chapter07 ├── c7_print_ff3factor.py ├── c7_56_merge_ffMonthly_GDPquarterly.py ├── c7_23_ffMonthly5.py ├── c7_24_read_ffcMonthly.py ├── c7_26_read_ffMonthly5.py ├── c7_simple_ff3_IBM.py ├── c7_02_critical_F_value.py ├── c7_41_generate_usGDPquarterly.py ├── c7_30_merge_not_good.py ├── c7_55_merge_how_4types.py ├── c7_88_generate_ffMonthly.py ├── c7_11_dot_diff_and_dot_shift_functions.py ├── c7_100_generate_ffMonthly_txt.py ├── c7_25_generate_ffcMonthly_pkl.py ├── c7_14_sharpe_ratio_using_yanMonthly.py ├── c7_102_generate_ffMonthly5.py ├── c7_06_3factors_IBMno_meaning.py ├── c7_39_LPSD.py ├── c7_04_3factors_model.py ├── c7_03_random_OLS.py ├── c7_01_3factor_model.py ├── c7_40_generate_usCPImonthly.py ├── c7_16_sharpe_ratio_YahooData.py ├── c7_24_generate_ffmonMonthly.py ├── c7_101_generate_ffcMonthly.py ├── c7_32_merge_02_different_names.py ├── c7_33_merge_03_left_index.py ├── c7_34_merge_by_two_variables.py ├── c7_31_merge_01.py ├── c7_32_merge_02_stock.py ├── c7_07_generate_ffMonthly.py ├── c7_23_generate_ffMonthly5.py ├── c7_12_Dimson1979_sp500_lag_lead.py └── c7_41_generate_ibmMonthly_pkl.py ├── Chapter08 ├── c8_46_print_indexMonthly_CRSP.py ├── c8_55_rolling_max_decapitted_.py ├── c8_06_noLonger_working.py ├── c8_09_pandas_interpolate.py ├── c8_99_04_generate_indexMonthly_pickle.py ├── c8_99_08_generate_tradingDays.py ├── c8_09_foreigh_exchange_not_working.py ├── c8_33_read_TORQcq.py ├── c8_13_get_current_quote.py ├── c8_45_read_crspInfo.py ├── c8_08_gen_quote_yahoo_good.py ├── c8_25_interplate.py ├── c8_32_print_TORQct.py ├── c8_05_print_obs_from_Google.py ├── c8_07_pandas_read_csv_function.py ├── c8_10_ochl_still_working.py ├── c8_04_retrieve_daily_from_Yahoo.py ├── c8_05_print_GDPquarterly_ffMonthly.py ├── c8_08_generate_GDP_pickle_using_pandas_datareader_GDP.py ├── c8_24_second_way_to_calculate_returns.py ├── c8_44_generate_bysinessCyclePkl.py ├── c8_01_first_one.py ├── c8_11_normality_test_random_from_uniform.py ├── c8_17_ttest_mean_point5.py ├── c8_22_table2_get_year_month_day_from_a_date_var.py ├── c8_07_pandas_datareader_GDP.py ├── c8_05_print_obs_from_Google2.py ├── c8_05_yahoo_stock_splits_dividends_data_notWorking.py ├── c8_10_normality_test_random_from_normal_distribution.py ├── c8_14_mean_std_skew_kurt.py ├── c8_44_relative_spread_TORQcq.py ├── c8_06_get_daily_data_from_Google.py ├── c8_99_01_generate_ffDaily_txt.py ├── c8_02_get_date_varible_using_pandasDataFrame.py ├── c8_20_Durbin_Watson_test.py ├── c8_35_pandas_OLS.py ├── c8_18_ttest_IBM_2013.py ├── c8_26_test_daily_mean_is_zero.py ├── c8_27_test_equal_variances.py ├── c8_12_normality_test_for_IBM.py ├── c8_19_Roll_spread.py ├── c8_18_merge_ff_daily_return.py ├── c8_31_get_high_frequency_data_google.py ├── c8_44_Amihud_IBM_WMT.py ├── c8_15_merge_ffMonthly_GDP.py ├── c8_28_52_week_high.py ├── c8_16_4moments_forSP500.py ├── c8_36_Fama_Mecbeth_regression.py ├── c8_55_merge_business_GDP.py ├── c8_03_daily_to_monthly.py ├── c8_21_use_tempfile.py ├── c8_99_03_generate_crspInfo_pickle.py ├── c8_generate_critical_F_values_Table.py └── c8_34_Durbin_Watson_test_CAPM_IBM_residual.py ├── Chapter05 ├── p4f.cpython-35.pyc └── spreadBasedOnCreditRating.pkl ├── Chapter09 ├── c9_99_04_generate_sp500monthly_pkl.py ├── c9_99_05_generate_ff49_industries.py ├── c9_99_03_generate_sp500add_pkl.py ├── c9_46_print_ff49industries.py ├── c9_55_read_stockMonthly.py ├── c9_55_end_Of_chapter_problem_update_yanMonthly.py ├── c9_01_optimize.py ├── c9_06_find_weight_2stock_portfolio.p ├── c9_032_matrix_multiplication.py ├── c9_02_graph_y_x.py ├── c9_13_get_IBM_from_yanMonthly.py ├── c9_10_impact_of_correlation_2_stock.py ├── c9_03_graph_another_pair_y_x.py ├── c9_04_solution_x1_x2_for_quatradic_form.py ├── c9_08_generate_2setCorrelated_randomNumbers.py ├── c9_99_01_generate_stockMonthly_pkl.py ├── c9_02_matrix.py ├── c9_03_optimization.py ├── c9_22_LPSD_f.py ├── c9_14_get_IBM_ret_from_yanMonthly.py ├── c9_07_find_minimum_expentional_function.py ├── c9_06_solution_2stock_negative_perfect_corr.py ├── c9_44_equal_weighted_vs_value_weighted.py ├── c9_12_get_ret_matrix_from_yanMonthly.py └── c9_77_Modigliani_m2_performance_measure.py ├── Chapter02 ├── c2_03_pandas_02 ├── c2_06_generate_pickle.py ├── c2_02_pandas_1.py ├── c2_08_example_pandas.py ├── c2_05_example_statsmodel_OLS.py ├── c2_09_bsCall.py ├── c2_07_statsmodels_OLS.py ├── c2_04_interplate.py └── c2_99_interplate_not_working.py ├── Chapter06 ├── c6_25_mention_canopy.py ├── c6_05_read_excel.py ├── c6_07_read_csv_file.py ├── c6_03_04_read_pickle.py ├── c6_17_yanMonthly.py ├── c6_06_input_excel_02.py ├── c6_23_lag.py ├── c6_20_save_simple_pickle.py ├── c6_27_get_beta_good.py ├── c6_21_yanMonthly_unique_securities.py ├── c6_31_read_from_a_binary_file.py ├── c6_09_save_price_data_from_Google.py ├── c6_18_lag_and_forward.py ├── c6_03_random_OLS.py ├── c6_22_sp500_return_lag_lead.py ├── c6_28_ols_example.py ├── c6_19_lag_once.py ├── c6_13_save_Excel_file.py ├── c6_12_save_a_binary_file.py ├── c6_30_suggested_read_pickle_not_working.py ├── c6_29_save_text_file.py ├── c6_10_save_price_data_from_Yahoo.py ├── c6_11_save_csv_file.py ├── c6_14_save_Excel_file_index_false.py ├── c6_02_random_OLS.py ├── c6_01_learn_OLS.py ├── c6_24_bible.py ├── c6_26_beta_good.py ├── c6_16_string_manipulation2.py └── c6_15_string_manipulation.py ├── Chapter04 ├── c4_04_dir_fin.py ├── c4_01_dir_pandas_data.py ├── c4_02_dir_pandas_data.py ├── c4_23_read_csv_local_file.py ├── c4_06_read_local_csv_file.py ├── c4_05_get_data.py ├── c4_15_get_data_google_01.py ├── c4_03_get_data_google.py ├── c4_12_get_ffMonthly.py ├── c4_17_print_png_image.py ├── c4_07_first_one.py ├── c4_14_download_one_jpg_image.py ├── c4_08_get_data_5lines.py ├── c4_09_get_return_only.py ├── c4_16_ttest_2stocks.py ├── c4_11_daily_ret_to_annual.py ├── c4_18_federal_fund_rate.py ├── c4_10_from_daily_ret_to_monthly_ret.py ├── c4_19_appendixA.py └── c4_13_generate_ffMonthly_txt2.py ├── Chapter01 ├── c1_01_assign_value.py ├── c1_09_while_loop.py ├── c1_11_import_math_print_dir.py ├── c1_12_read_csv_file.py ├── c1_24_read_infile.py ├── c1_02_import_math_module.py ├── c1_22_data_output.py ├── c1_15_if_condition.py ├── c1_14_read_pickle_data.py ├── c1_03_def_fv_funtion.py ├── c1_04_def_pv_funtion.py ├── c1_06_if_else.py ├── c1_25_string_replacement.py ├── c1_13_read_remote_data.py ├── c1_16_logic_and_logic_or.py ├── c1_07_NPV_function.py ├── c1_08_NPV_Excel.py ├── c1_19_flatten_function.py ├── c1_20_matrix_dot_product.py ├── c1_17_to_letter_grade.py ├── c1_21_read_ffMonthly_data.py ├── c1_23_read_stock_data_and_save_it.py ├── c1_10_while_loop_2IRRs.py ├── c1_05_pv_f_with_help_comments.py └── c1_18_many_useful_commands.py ├── Chapter10 ├── c10_05_payoff_function_call.py ├── c10_01.py ├── c10_40_data_case.py ├── c10_28_standard_normal_dist.py ├── c10_09_standard_normal_dis_graph.py ├── c10_14_bsCall.py ├── c10_02_foreign_exchange_futures.py ├── c10_04_payoff_call_graph.py ├── c10_03_exchange_futures.py ├── c10_43_EW_port.py ├── c10_10_target_beta_portfolio_hedging.py ├── c10_32_implied_vol_EuropeanCall.py ├── c10_34_binary_search.py ├── c10_21_CRR_01.py ├── c10_35_put_call_ratio.py ├── c10_31_plot_call_vs_one_input.py ├── c10_08_arbitrage_argument_exchange_futures.py ├── c10_25_binomialEuropeanCallFunction.py ├── c10_42_binomialCallEuropean.py ├── c10_06_profit_loss_for_call.py ├── c10_13_fig.py ├── c10_29_fig_good.py ├── c10_33_implied_vol_EuropeanPut_min.py ├── c10_11_area_under_normal_dist.py ├── c10_30_figure_end_of_chapter_problem.py ├── c10_27_end_of_chapter_question.py ├── c10_22_binomial_graph.py ├── c10_26_binomialAmericanCall.py ├── c10_38_greeks.py ├── c10_23_binomial_2steps.py └── c10_19_graph_sigma_call.py ├── Chapter12 ├── c12_01_10random_numbers.py ├── c12_06_random_number_with_seed.py ├── c12_08_uniform_dist.py ├── c12_07_normal_dist.py ├── c12_21_use_permutation_function.py ├── c12_09_roll_a_dice.py ├── c12_88_simpy_02.py ├── c12_35_simpy_02.py ├── c12_10_simulate_pi.py ├── c12_03_graph_standard_normal_dist.py ├── c12_33_generateSobol_pkl.py ├── c12_32_scatter_sobol.py ├── c12_12_radnomly_choose_m_from_n_stocks.py ├── c12_27_random_numbers_from_three_distributions.py ├── c12_04_histogram.py ├── c12_11_poison_dist.py ├── c12_20_boots_f_function.py ├── c12_31_scatter_random_numbers.py ├── c12_16_VaR_based_on_formula.py ├── c12_13_use_yanMonthly.py └── c12_05_lognormal_graphs.py ├── Chapter13 ├── c13_01.py ├── c13_05_print_bondSpread2014.py ├── c13_99_03_geneerate5year.py ├── c13_03_print_moodyAAAyield.py ├── c13_99_03_generateBondSpread2014.py ├── c13_02_print1year_credit_migration.py ├── c13_99_04_generate_moodyAAAyield.py ├── c13_09_get_PriceYahoo_not_working.py ├── c13_99_get_finStatement_not_working.py ├── c13_99_02_1yearCreditRatingMigrationMarrix.py ├── c13_06_norm_ppf.py ├── c13_04_print5year_credit_migrationMatrix.py ├── c13_20_graph_term_structure.py └── c13_07_BIS_interest_simulation.py ├── Chapter11 ├── c11_24_01_generate_ff5VWindustry_49.py ├── c11_04_show_z_negative.py ├── c11_13_sort_nparray.py ├── c11_21_ES_z_value_normal_distribution.py ├── c11_02_normal_distribution.py ├── c11_01_normal_density_function.py ├── c11_12_normal_random.py ├── c11_18_sort_pandas.py ├── c11_03_standard_normal_dis.py ├── c11_10_normality_test.py ├── c11_09_normaility_test_msft.py ├── c11_20_VaR_for_5industry_portfolo_ff.py ├── c11_11_normality_test_for_sp500.py ├── c11_14_VaR_500shares_WMT.py └── c11_07_VaR_500shares_IBM_tomorrow.py ├── Chapter14 ├── c14_22_crudeOilPrice.py ├── c14_10_correlated_random_numbers.py ├── c14_01_callandPut.py ├── c14_18_down_and_in_put.py └── c14_24_cholesky.py ├── .gitattributes ├── Chapter15 ├── c15_03_4moments.py ├── c15_01_vol_IBM.py ├── c15_02_normalityTests.py ├── c15_11_sp500cluster.py ├── c15_04_sp500_4moments.py ├── c15_10_volatility_smile_put.py ├── c15_09_volatility_smile_call.py ├── c15_05_generate_ffDaily_pkl.py ├── c15_12_ARCH_1.py ├── c15_06_LSPD.py └── c15_13_GARCH.py ├── Chapter03 ├── c3_04_appendix_E_more.py ├── c3_01_write_your_own_financial_calculator.py ├── c3_03_IRRs_funciton.py └── c3_02_myPV_based_on_scipy.py └── .gitignore /Chapter07/c7_print_ff3factor.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 3 | print(x.head()) 4 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter08/c8_46_print_indexMonthly_CRSP.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_pickle("c:/temp/indexMonthly.pkl") 3 | print(x.head()) 4 | -------------------------------------------------------------------------------- /Chapter05/p4f.cpython-35.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-for-Finance-Second-Edition/HEAD/Chapter05/p4f.cpython-35.pyc -------------------------------------------------------------------------------- /Chapter08/c8_55_rolling_max_decapitted_.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x=sp.arange(1,1000) 4 | 5 | y=pd.rolling_max(x,5) 6 | -------------------------------------------------------------------------------- /Chapter05/spreadBasedOnCreditRating.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PacktPublishing/Python-for-Finance-Second-Edition/HEAD/Chapter05/spreadBasedOnCreditRating.pkl -------------------------------------------------------------------------------- /Chapter09/c9_99_04_generate_sp500monthly_pkl.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_pickle("c:/temp/sp500monthly.pkl") 3 | print(x.head()) 4 | print(x.tail()) 5 | 6 | -------------------------------------------------------------------------------- /Chapter08/c8_06_noLonger_working.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | url='http://chart.yahoo.com/table.csv?s=IBM' 3 | x=pd.read_csv(url,index_col=0,parse_dates=True) 4 | print(x.head()) 5 | -------------------------------------------------------------------------------- /Chapter08/c8_09_pandas_interpolate.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | nn=np.nan 4 | x=pd.Series([0.29,0.57,nn,1.34,nn,nn,nn,nn,2.7]) 5 | y=x.interpolate() 6 | print(y) 7 | -------------------------------------------------------------------------------- /Chapter02/c2_03_pandas_02: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Fri Nov 18 12:42:27 2016 4 | 5 | @author: yany 6 | """ 7 | 8 | import pandas as pd 9 | df = pd.DataFrame(np.random.randn(10, 4)) -------------------------------------------------------------------------------- /Chapter07/c7_56_merge_ffMonthly_GDPquarterly.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | GDP=pd.read_pickle("c:/temp/usGDPquarterly.pkl") 3 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 4 | print(GDP.head()) 5 | print(ff.head()) 6 | 7 | -------------------------------------------------------------------------------- /Chapter08/c8_99_04_generate_indexMonthly_pickle.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | x=pd.read_csv("c:/temp/indexMonthly2.csv") 3 | 4 | x.columns=(['DATE','VWRETD', 'VWRETX', 'EWRETD', 'EWRETX','SP500RET','SP500INDEX','TOTALVAL','TOTALN','USEDVAL', 'USEDN']) 5 | x.to_pickle("c:/temp/indexMonthly.pkl") 6 | -------------------------------------------------------------------------------- /Chapter08/c8_99_08_generate_tradingDays.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | x=pd.read_table("c:/temp/tradingDaysMonthly.txt") 4 | 5 | x.to_pickle("c:/temp/tradingDaysMonthly.pkl") 6 | 7 | 8 | a=pd.read_table("c:/temp/tradingDaysDaily.txt") 9 | 10 | a.to_pickle("c:/temp/tradingDaysDaily.pkl") -------------------------------------------------------------------------------- /Chapter09/c9_99_05_generate_ff49_industries.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x=pd.read_csv("c:/temp/49_industry_portfolios.csv",skiprows=11,index_col=0) 4 | #x=pd.read_csv("c:/temp/49_industry_portfolios.csv",skiprows=11) 5 | x.to_pickle("c:/temp/ff49industries.pkl") 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Chapter06/c6_25_mention_canopy.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_25.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | print(sp.sqrt(2)) -------------------------------------------------------------------------------- /Chapter04/c4_04_dir_fin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_03_dir_fin.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import matplotlib.finance as fin 12 | print(dir(fin)) 13 | -------------------------------------------------------------------------------- /Chapter08/c8_09_foreigh_exchange_not_working.py: -------------------------------------------------------------------------------- 1 | from pandas_datareader.oanda import get_oanda_currency_historical_rates 2 | start, end = "2016-01-01", "2016-06-01" 3 | quote_currency = "USD" 4 | base_currency = ["EUR", "GBP", "JPY"] 5 | df_rates = get_oanda_currency_historical_rates(start, end,quote_currency=quote_currency,base_currency=base_currency) 6 | print(df_rates) 7 | 8 | 9 | -------------------------------------------------------------------------------- /Chapter01/c1_01_assign_value.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_01_assign_value.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | pv=100 13 | fv=pv*(1+0.1)**20 14 | 15 | print(fv) -------------------------------------------------------------------------------- /Chapter01/c1_09_while_loop.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_09_while_loop.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | i=1 13 | while(i<10): 14 | print(i) 15 | i+=1 -------------------------------------------------------------------------------- /Chapter06/c6_05_read_excel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_05_read_Excel.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_excel("c:/temp/Book1.xlsx") 13 | print(x) 14 | -------------------------------------------------------------------------------- /Chapter07/c7_23_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_23_ffMonthly5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | ff=pd.read_pickle('c:/temp/ffMonthly5.pkl') 13 | 14 | -------------------------------------------------------------------------------- /Chapter09/c9_99_03_generate_sp500add_pkl.py: -------------------------------------------------------------------------------- 1 | """DATE,START,END 2 | 10006,19570301,19840718 3 | 10030,19570301,19690108 4 | 10049,19251231,19321001 5 | """ 6 | 7 | import pandas as pd 8 | x=pd.read_csv("c:/temp/sp500add.csv") 9 | x.columns=['PERMNO','DATEADDED','DAYDELETED'] 10 | print(x.head()) 11 | print(x.tail()) 12 | 13 | x.to_pickle("c:/temp/sp500add.pkl") 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter01/c1_11_import_math_print_dir.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_11_import_math_print_dir.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import math 12 | x=dir(math) 13 | print(x) -------------------------------------------------------------------------------- /Chapter01/c1_12_read_csv_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_12_read_csv_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/ibm.csv") -------------------------------------------------------------------------------- /Chapter01/c1_24_read_infile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_24_read_infile.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | infile=open("c:/temp/dell.txt","r") 12 | x=infile.read() 13 | -------------------------------------------------------------------------------- /Chapter06/c6_07_read_csv_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_07_read_csv_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | f=pd.read_csv("c:\\temp\\ibm.csv") 13 | print(f[1:3]) -------------------------------------------------------------------------------- /Chapter10/c10_05_payoff_function_call.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_05_payoff_function_call.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | def payoff_call(sT,x): 12 | return (sT-x+abs(sT-x))/2 13 | -------------------------------------------------------------------------------- /Chapter01/c1_02_import_math_module.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_02_import_math_module.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import math 13 | x=math.sqrt(3) 14 | print(x) -------------------------------------------------------------------------------- /Chapter12/c12_01_10random_numbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_01_randard.standard_normal.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | x=sp.random.standard_normal(size=10) 13 | print(x) -------------------------------------------------------------------------------- /Chapter06/c6_03_04_read_pickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_04_read_pickle.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/yanMonthly.pkl ") 13 | print(x[0:10]) 14 | -------------------------------------------------------------------------------- /Chapter01/c1_22_data_output.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_22_data_output.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | f=open("c:/temp/out.txt","w") 12 | x="This is great" 13 | f.write(x) 14 | f.close() -------------------------------------------------------------------------------- /Chapter04/c4_01_dir_pandas_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_01_dir_pandas.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as pddata 13 | print(help(pddata) ) 14 | -------------------------------------------------------------------------------- /Chapter08/c8_33_read_TORQcq.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c8_33_print_TORQcq.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | cq=pd.read_pickle("c:/temp/TORQcq.pkl") 14 | print(cq.head() ) 15 | -------------------------------------------------------------------------------- /Chapter01/c1_15_if_condition.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_15_if_condition.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | r=-0.05 13 | 14 | if(r<0): 15 | print("interest rate is less than zero") -------------------------------------------------------------------------------- /Chapter06/c6_17_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_17_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 13 | print(df[0:10]) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter08/c8_13_get_current_quote.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_13_get_current_quote.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | ticker='AMZN' 13 | print(web.get_quote_yahoo(ticker)) -------------------------------------------------------------------------------- /Chapter10/c10_01.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_01.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as ps 12 | pv=100 13 | APR=0.08 14 | rate=APR/2.0 15 | n=2 16 | nper=n*2 17 | fv=ps.fv(rate,nper,0,pv) 18 | print(fv) -------------------------------------------------------------------------------- /Chapter10/c10_40_data_case.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_40_datacase.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/businessCycle.pkl") 13 | print(x.head()) 14 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter13/c13_01.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c13_01_3creditRatigs.py 4 | Book : Python for Finance 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 2/27/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_csv("c:/temp/equivalent3creditRatings.csv") 14 | print(x) 15 | -------------------------------------------------------------------------------- /Chapter08/c8_45_read_crspInfo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_45_crspInfo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/crspInfo.pkl") 13 | print(x.head(3)) 14 | print(x.tail(2)) 15 | -------------------------------------------------------------------------------- /Chapter11/c11_24_01_generate_ff5VWindustry_49.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | #x=pd.read_csv("c:/temp/ff49VWindustryMonthly.csv",skiprows=11,index_col=0) 4 | #x.to_pickle("c:/temp/ff49VWindustryMonthly.pkl") 5 | 6 | x=pd.read_csv("c:/temp/ff5VWindustryMonthly.csv",skiprows=11,index_col=0) 7 | x2=x/100.0 8 | x2.columns = [x.upper() for x in x2.columns] 9 | x2.to_pickle("c:/temp/ff5VWindustryMonthly.pkl") -------------------------------------------------------------------------------- /Chapter04/c4_02_dir_pandas_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_02_dir_pandas_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as pddata 13 | print(help(pddata.DataReader) ) 14 | -------------------------------------------------------------------------------- /Chapter07/c7_24_read_ffcMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_24_read_ffMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import pandas as pd 13 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(x.head()) 15 | print(x.tail()) -------------------------------------------------------------------------------- /Chapter08/c8_08_gen_quote_yahoo_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_08_get_quote_yahoo_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | ticker='AMZN' 13 | print(web.get_quote_yahoo (ticker)) 14 | -------------------------------------------------------------------------------- /Chapter09/c9_46_print_ff49industries.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_461_print_ff49industries.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/ff49industries.pkl") 13 | print(x.head(2)) 14 | -------------------------------------------------------------------------------- /Chapter11/c11_04_show_z_negative.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_04_show_z_genative.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy.stats import norm 12 | confidence_level=0.99 13 | z=norm.ppf(1-confidence_level) 14 | print(z) 15 | -------------------------------------------------------------------------------- /Chapter01/c1_14_read_pickle_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_14_read_pickle_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(x.head()) -------------------------------------------------------------------------------- /Chapter04/c4_23_read_csv_local_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_23_read_csv_local_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_csv("c:/temp/ibm.csv") 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter06/c6_06_input_excel_02.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_07_input_Excel.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | infile=pd.ExcelFile("c:/temp/Book1.xlsx") 12 | x=infile.parse('Sheet1',header=None) 13 | print(x) 14 | -------------------------------------------------------------------------------- /Chapter07/c7_26_read_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_26_read_ffMonthly5.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/ffMonthly5.pkl") 13 | print(x.head()) 14 | print(x.tail()) 15 | -------------------------------------------------------------------------------- /Chapter01/c1_03_def_fv_funtion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_03_def_fv_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def fv_f(pv,r,n): 13 | return pv*(1+r)**n 14 | # 15 | fv=fv_f(100,0.1,2) 16 | print(fv) -------------------------------------------------------------------------------- /Chapter01/c1_04_def_pv_funtion.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_04_def_pv_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def pv_f(pv,r,n): 13 | return pv/(1+r)**n 14 | # 15 | pv=pv_f(100,0.1,2) 16 | print(pv) -------------------------------------------------------------------------------- /Chapter01/c1_06_if_else.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_06_if_else.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | cashFlows=np.array([-100,50,40,30]) 14 | for cash in cashFlows: 15 | print(cash) -------------------------------------------------------------------------------- /Chapter04/c4_06_read_local_csv_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_06_read_local_csv_file.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | x=pd.read_csv("c:/temp/ibm.csv") 14 | print(x.head()) 15 | -------------------------------------------------------------------------------- /Chapter07/c7_simple_ff3_IBM.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | import statsmodels.api as ms 4 | 5 | a=pd.read_pickle("c:/temp/ibmMonthly.pkl") 6 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 7 | df=pd.merge(a,ff,left_index=True,right_index=True) 8 | 9 | 10 | y=final['RET'] 11 | x=final[['MKT_RF','SMB','HML']] 12 | x=sm.add_constant(x) 13 | results=sm.OLS(y,x).fit() 14 | print(results.summary()) 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter08/c8_25_interplate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_25_interplate.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | nn=np.nan 14 | x=pd.Series([1,2,nn,nn,6]) 15 | print(x.interpolate()) 16 | 17 | -------------------------------------------------------------------------------- /Chapter09/c9_55_read_stockMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_55_read_stockMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/stockMonthly.pkl") 13 | print(x.head()) 14 | print(x.tail()) 15 | -------------------------------------------------------------------------------- /Chapter14/c14_22_crudeOilPrice.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c14_22_crudeOilPrice.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/cruideOilPriceDaily.pkl") 13 | print(x.head()) 14 | print(x.tail()) 15 | -------------------------------------------------------------------------------- /Chapter11/c11_13_sort_nparray.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_13_sor_nparray.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | a = np.array([[1,-4],[9,10]]) 13 | b=np.sort(a) 14 | 15 | print("a=",a) 16 | print("b=",b) -------------------------------------------------------------------------------- /Chapter12/c12_06_random_number_with_seed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_06_randard_numbers_with_seed.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | sp.random.seed(12345) 13 | x=sp.random.normal(0,1,20) 14 | print x[0:5] 15 | -------------------------------------------------------------------------------- /Chapter12/c12_08_uniform_dist.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_08_uniform_dist.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | sp.random.seed(123345) 14 | x=sp.random.uniform(low=1,high=100,size=10) 15 | print(x[0:5]) 16 | -------------------------------------------------------------------------------- /Chapter01/c1_25_string_replacement.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_26_string_replacement.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import re 12 | x="abc" 13 | print("x=",x) 14 | y=re.sub("a","9",x) 15 | print("y=",y) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter04/c4_05_get_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_05_get_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | df = getData.DataReader("IBM", 'google') 14 | print(df.head()) 15 | -------------------------------------------------------------------------------- /Chapter04/c4_15_get_data_google_01.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_15_get_data_google.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | aapl =getData.DataReader("AAPL", "google") 14 | 15 | -------------------------------------------------------------------------------- /Chapter06/c6_23_lag.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_24_lag.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x=sp.arange(1,5,0.5) 14 | y=pd.DataFrame(x,columns=['Ret']) 15 | y['Lag']=y.shift(1) 16 | print(y) 17 | -------------------------------------------------------------------------------- /Chapter04/c4_03_get_data_google.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_03_get_stock_data_google.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import pandas_datareader.data as getData 12 | df = getData.get_data_google("IBM") 13 | print(df.head()) 14 | -------------------------------------------------------------------------------- /Chapter04/c4_12_get_ffMonthly.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_12_get_ffMonthly.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas_datareader.data as getData 13 | ff =getData.DataReader("F-F_Research_Data_Factors", "famafrench") 14 | -------------------------------------------------------------------------------- /Chapter13/c13_05_print_bondSpread2014.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_05_print_bondSpread2014.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/bondSpread2014.p") 13 | print(x.head()) 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter01/c1_13_read_remote_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_13_read_remote_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | url='http://canisius.edu/~yany/data/ibm.csv' 14 | x=pd.read_csv(url) 15 | print(x.head()) -------------------------------------------------------------------------------- /Chapter10/c10_28_standard_normal_dist.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_28_standard_normal_dist.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | from scipy import exp,sqrt,stats,arange 12 | # 13 | x = arange(-3,3,0.1) 14 | y=stats.norm.pdf(x) 15 | plot(x,y) 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /Chapter08/c8_32_print_TORQct.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_32_print_TORQct.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import pandas as pd 13 | # 14 | x=pd.read_pickle("c:/temp/TORQct.pkl") 15 | print(x.head()) 16 | print(x.tail()) 17 | print(sp.shape(x)) -------------------------------------------------------------------------------- /Chapter13/c13_99_03_geneerate5year.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_99_03_generate5year.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/migration5year.csv",index_col=0) 13 | y=x/100 14 | print(y) 15 | y.to_pickle("c:/temp/migration5year.pkl") 16 | -------------------------------------------------------------------------------- /Chapter07/c7_02_critical_F_value.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_02_critical_F_value.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy.stats 11 | alpha=0.05 12 | dfNumerator=3 13 | dfDenominator=1 14 | 15 | f=scipy.stats.f.ppf(q=1-alpha, dfn=dfNumerator, dfd=dfDenominator) 16 | print(f) -------------------------------------------------------------------------------- /Chapter07/c7_41_generate_usGDPquarterly.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import scipy as sp 3 | x=pd.read_csv("c:/temp/GDP_Yan.csv",skiprows=10) 4 | n=len(x) 5 | ddate=[] 6 | a=[] 7 | k=1 8 | for i in sp.arange(n): 9 | y=sp.array(x[i:(i+1)]) 10 | ddate.append( pd.to_datetime(y[0,0]).date()) 11 | a.append(y[0,1]) 12 | #print(y) 13 | 14 | GDP=pd.DataFrame(a,columns=['AdjustedGDPannualBillion'],index=ddate) 15 | GDP.to_pickle("c:/temp/usGDPquarterly.pkl") 16 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_obs_from_Google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_obs_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as getData 12 | import re 13 | ticker='msft' 14 | p = getData.DataReader(ticker, "google") 15 | print(p.head()) 16 | -------------------------------------------------------------------------------- /Chapter12/c12_07_normal_dist.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_07_normal_dist.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | sp.random.seed(12345) 14 | mean=0.05 15 | std=0.1 16 | n=50 17 | x=sp.random.normal(mean,std,n) 18 | print(x[0:5]) 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter13/c13_03_print_moodyAAAyield.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_03_print_moodyAAAyield.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle("c:/temp/moodyAAAyield.p") 13 | print(x.head()) 14 | print(x.tail()) 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter01/c1_16_logic_and_logic_or.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_16_logic_and_logic_or.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | a=9 12 | b=-8 13 | 14 | if(a>0 and b>0): 15 | print("both positive") 16 | if(a>0 or b>0): 17 | print("at least one is positive") -------------------------------------------------------------------------------- /Chapter07/c7_30_merge_not_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_30_merge_not_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.DataFrame([[40,50],[0.2,0.3]],rows=['A','B']) 13 | y=pd.DataFrame([[30,22],[0.1,-0.25]],rows=['C','B']) 14 | z=pd.merge(x,y) 15 | 16 | -------------------------------------------------------------------------------- /Chapter11/c11_21_ES_z_value_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_21_ES_z_value_normal_distribution.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | sp.random.seed(12345) 13 | n=5000000 14 | ret=sp.random.normal(0,1,n) 15 | print(ret[0:5] ) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter06/c6_20_save_simple_pickle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_20_save_simple_pickle.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | np.random.seed(1234) 14 | a = pd.DataFrame(np.random.randn(6,5)) 15 | a.to_pickle('c:/temp/a.pickle') 16 | 17 | -------------------------------------------------------------------------------- /Chapter08/c8_07_pandas_read_csv_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_07_pandas_read+csv_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | url='http://canisius.edu/~yany/data/ibm.csv' 13 | x=pd.read_csv(url,index_col=0,parse_dates=True) 14 | print(x.head()) 15 | -------------------------------------------------------------------------------- /Chapter02/c2_06_generate_pickle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_06_generate_pickle.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import pandas as pd 14 | np.random.seed(123) 15 | df=pd.Series(np.random.randn(100)) 16 | df.to_pickle('c:/temp/test.pkl') -------------------------------------------------------------------------------- /Chapter10/c10_09_standard_normal_dis_graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_09_standard_normal_dist_graph.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | x = sp.arange(-3,3,0.1) 14 | y=sp.stats.norm.pdf(x) 15 | plt.plot(x,y) 16 | plt.show() 17 | -------------------------------------------------------------------------------- /Chapter12/c12_21_use_permutation_function.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_21_use_permulation_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | 13 | import numpy as np 14 | x=range(1,11) 15 | print(x) 16 | for i in range(5): 17 | y=np.random.permutation(x) 18 | # 19 | print(y) 20 | -------------------------------------------------------------------------------- /Chapter02/c2_02_pandas_1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c2_02_pandas_1.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import pandas as pd 13 | import numpy as np 14 | 15 | np.random.seed(123) 16 | df = pd.DataFrame(np.random.randn(10, 4)) 17 | pieces = [df[:3], df[3:7], df[7:]] 18 | -------------------------------------------------------------------------------- /Chapter08/c8_10_ochl_still_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_10_ochl_still_working.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | x = getData("IBM",(2016,1,1),(2016,1,21),asobject=True, adjusted=True) 14 | print(x[0:4]) 15 | -------------------------------------------------------------------------------- /Chapter13/c13_99_03_generateBondSpread2014.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_99_03_generateBondSpread2014.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/bondSpread2014.csv") 13 | x.to_pickle("c:/temp/bondSpread2014.p") 14 | print(x.head()) 15 | print(x.tail()) 16 | 17 | -------------------------------------------------------------------------------- /Chapter01/c1_07_NPV_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_07_NPV_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def npv_f(rate, cashflows): 13 | total = 0.0 14 | for i in range(0,len(cashflows)): 15 | total += cashflows[i] / (1 + rate)**i 16 | return total -------------------------------------------------------------------------------- /Chapter09/c9_55_end_Of_chapter_problem_update_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_55_end_of_chapter_problem_update_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_pickle('c:/temp/yanMonthly.pkl') 13 | print(x.head(2)) 14 | print(x.tail(3)) 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Chapter13/c13_02_print1year_credit_migration.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_02_print1year_credit_migration.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import pandas as pd 13 | x=pd.read_pickle("c:/temp/creditRating1yearMigrationMatrix.pkl") 14 | print(x.head(1)) 15 | print(x.tail(1)) 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter13/c13_99_04_generate_moodyAAAyield.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_99_04_generate_moodyAAAyield.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | x=pd.read_csv("c:/temp/AAA.csv",index_col=0) 13 | y=x/100 14 | print(y.head()) 15 | print(y.tail()) 16 | y.to_pickle("c:/temp/moodyAAAyield.p") 17 | -------------------------------------------------------------------------------- /Chapter02/c2_08_example_pandas.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_08_example_pandas.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | dates=pd.date_range('20160101',periods=5) 14 | np.random.seed(12345) 15 | x=pd.DataFrame(np.random.rand(5,2),index=dates,columns=('A','B')) 16 | -------------------------------------------------------------------------------- /Chapter01/c1_08_NPV_Excel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_08_NPV_Excel.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def npv_Excel(rate, cashflows): 13 | total = 0.0 14 | for i, cashflow in enumerate(cashflows): 15 | total += cashflow / (1 + rate)**(i+1) 16 | return total -------------------------------------------------------------------------------- /Chapter01/c1_19_flatten_function.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_19_flatten_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | # 13 | x=np.array([[1,2],[5,6],[7,9]]) # a 3 by 2 array 14 | print(x) 15 | y=x.flatten() 16 | print(y) 17 | x2=np.reshape(y,[2,3]) 18 | print(x2) -------------------------------------------------------------------------------- /Chapter08/c8_04_retrieve_daily_from_Yahoo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_04_retrieve_daily_from_Yahoo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | x = getData("IBM",(2016,1,1),(2016,1,21),asobject=True, adjusted=True) 13 | print(x[0:4]) 14 | 15 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_GDPquarterly_ffMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_GDPquarterly_ffMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | GDP=pd.read_pickle("c:/temp/usGDPquarterly.pkl") 13 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 14 | print(GDP.head()) 15 | print(ff.head()) 16 | -------------------------------------------------------------------------------- /Chapter08/c8_08_generate_GDP_pickle_using_pandas_datareader_GDP.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader.data as web 2 | import datetime 3 | begdate = datetime.datetime(1900, 1, 1) 4 | enddate = datetime.datetime(2017, 1, 27) 5 | 6 | x= web.DataReader("GDP", "fred", begdate,enddate) 7 | print(x.head(2)) 8 | print(x.tail(3)) 9 | 10 | x.to_pickle("c:/temp/usGDPquarterly2.pkl") 11 | 12 | 13 | 14 | 15 | import pandas as pd 16 | a=pd.read_pickle("c:/temp/usGDPquarterly2.pkl") 17 | print(a.head()) 18 | print(a.tail()) -------------------------------------------------------------------------------- /Chapter09/c9_01_optimize.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_01_optimize.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy.optimize import minimize 12 | def myFunction(x): 13 | return (3.2+5*x**2) 14 | 15 | x0=100 16 | res = minimize(myFunction,x0,method='nelder-mead',options={'xtol':1e-8,'disp': True}) 17 | 18 | -------------------------------------------------------------------------------- /Chapter13/c13_09_get_PriceYahoo_not_working.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c13_09_getIpriceYahoo.py 4 | Book : Python for Finance 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 2/27/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from yahoo_finance import Share 13 | yahoo = Share('YHOO') 14 | print(yahoo.get_open()) 15 | print(yahoo.get_price()) 16 | print(yahoo.get_trade_datetime()) 17 | -------------------------------------------------------------------------------- /Chapter04/c4_17_print_png_image.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_17_print_png_image.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | from PIL import Image 12 | img = Image.open('c:/temp/fun.png') 13 | img.show() 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter06/c6_27_get_beta_good.py: -------------------------------------------------------------------------------- 1 | from scipy import stats 2 | from matplotlib.finance import quotes_historical_yahoo_ochl as aa 3 | # 4 | def dailyReturn(ticker,begdate,enddate): 5 | p = aa(ticker, begdate,enddate,asobject=True,adjusted=True) 6 | return p.aclose[1:]/p.aclose[:-1]-1 7 | # 8 | begdate=(2012,1,1) 9 | enddate=(2017,1,9) 10 | retIBM=dailyReturn("wmt",begdate,enddate) 11 | retMkt=dailyReturn("^GSPC",begdate,enddate) 12 | outputs=stats.linregress(retMkt,retIBM) 13 | print(outputs) 14 | -------------------------------------------------------------------------------- /Chapter06/c6_21_yanMonthly_unique_securities.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_21_yanMonthly_unique_securities.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 14 | unique=np.unique(df.index) 15 | print(len(unique)) 16 | print(unique) 17 | 18 | -------------------------------------------------------------------------------- /Chapter08/c8_24_second_way_to_calculate_returns.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_24_second_way_to_calculate_return.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | p=[1,1.1,0.9,1.05] 14 | a=pd.DataFrame({'Price':p}) 15 | a['Ret']=a['Price'].diff()/a['Price'].shift(1) 16 | print(a) 17 | -------------------------------------------------------------------------------- /Chapter09/c9_06_find_weight_2stock_portfolio.p: -------------------------------------------------------------------------------- 1 | import scipy as sp 2 | 3 | var1=0.016 4 | var2=0.027 5 | 6 | sigma1=sp.sqrt(var1) 7 | sigma2=sp.sqrt(var2) 8 | rho=-1 9 | n=1000 10 | portVar=10 # assign a big number 11 | tiny=1.0/n 12 | 13 | for i in sp.arange(n): 14 | w1=i*tiny 15 | w2=1-w1 16 | var=w1**2*var1 +w2**2*var2**2+2*w1*w2*rho*sigma1*sigma2 17 | if(var0: 20 | squared=sp.sqrt(inside) 21 | print("x1=",(b+squared)/(2*a)) 22 | print("x2=",(b-squared)/(2*a)) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter12/c12_88_simpy_02.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_88_simpy_02.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import simpy 13 | def clock(env, name, tick): 14 | while True: 15 | print(name, env.now) 16 | yield env.timeout(tick) 17 | 18 | env = simpy.Environment() 19 | env.process(clock(env, 'fast', 0.5)) 20 | env.process(clock(env, 'slow', 1)) 21 | env.run(until=2) 22 | -------------------------------------------------------------------------------- /Chapter09/c9_08_generate_2setCorrelated_randomNumbers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_08_generate_2set_correlated_randomNumbers.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | sp.random.seed(123) 14 | n=1000 15 | rho=0.3 16 | 17 | x1=sp.random.normal(size=n) 18 | x2=sp.random.normal(size=n) 19 | 20 | y1=x1 21 | y2=rho*x1+sp.sqrt(1-rho**2)*x2 22 | print(sp.corrcoef(y1,y2)) 23 | 24 | -------------------------------------------------------------------------------- /Chapter10/c10_14_bsCall.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_14_call_put.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import log,exp,sqrt,stats 13 | def bs_call(S,X,T,r,sigma): 14 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 15 | d2 = d1-sigma*sqrt(T) 16 | return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2) 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter12/c12_35_simpy_02.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_35_simpy_02.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | 13 | import simpy 14 | def clock(env, name, tick): 15 | while True: 16 | print(name, env.now) 17 | yield env.timeout(tick) 18 | 19 | env = simpy.Environment() 20 | env.process(clock(env, 'fast', 0.5)) 21 | env.process(clock(env, 'slow', 1)) 22 | env.run(until=2) 23 | -------------------------------------------------------------------------------- /Chapter08/c8_05_print_obs_from_Google2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_06_print_obs_from_Google2.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | import datetime 13 | ticker='MSFT' 14 | begdate = datetime.datetime(2012, 1, 2) 15 | enddate = datetime.datetime(2017, 1, 10) 16 | a = web.DataReader(ticker, 'google',begdate,enddate) 17 | print(a.head(3)) 18 | print(a.tail(2)) 19 | -------------------------------------------------------------------------------- /Chapter12/c12_10_simulate_pi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_10_simulate_pi.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | n=100000 13 | x=sp.random.uniform(low=0,high=1,size=n) 14 | y=sp.random.uniform(low=0,high=1,size=n) 15 | dist=sp.sqrt(x**2+y**2) 16 | in_circle=dist[dist<=1] 17 | our_pi=len(in_circle)*4./n 18 | print ('pi=',our_pi) 19 | print('error (%)=', (our_pi-sp.pi)/sp.pi) 20 | -------------------------------------------------------------------------------- /Chapter06/c6_30_suggested_read_pickle_not_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_30_suggested_read_pickle_not_working.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import cStringIO 13 | import urllib2 14 | loc="http://canisius.edu/~yany/python/yanMonthly.pkl" 15 | x=pd.read_pickle(cStringIO.StringIO(urllib2.urlopen(loc).read())) 16 | 17 | 18 | y=cStringIO.StringIO(urllib2.urlopen(loc).read()) -------------------------------------------------------------------------------- /Chapter08/c8_05_yahoo_stock_splits_dividends_data_notWorking.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_05_print_obs_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | 13 | import pandas_datareader.data as web 14 | import datetime 15 | ticker='WMT' 16 | begdate = datetime.datetime(2010, 1, 1) 17 | enddate= datetime.datetime(2015, 5, 9) 18 | x=web.DataReader(ticker,'yahoo-actions',begdate,enddate) 19 | print(x.head()) -------------------------------------------------------------------------------- /Chapter08/c8_10_normality_test_random_from_normal_distribution.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_10_normality_test_from_normal.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | import scipy as sp 13 | 14 | sp.random.seed(12345) 15 | mean=0.1 16 | std=0.2 17 | n=5000 18 | 19 | ret=sp.random.normal(loc=0,scale=std,size=n) 20 | 21 | print 'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | -------------------------------------------------------------------------------- /Chapter08/c8_14_mean_std_skew_kurt.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_14_mean_std_skew_kurt.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats,random 12 | import numpy as np 13 | np.random.seed(12345) 14 | ret = random.normal(0,1,500000) 15 | 16 | print('mean =', np.mean(ret)) 17 | print('std =',np.std(ret)) 18 | print('skewness=',stats.skew(ret)) 19 | print('kurtosis=',stats.kurtosis(ret)) 20 | -------------------------------------------------------------------------------- /Chapter08/c8_44_relative_spread_TORQcq.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_44_relative_spread_TORQcq.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import pandas as pd 13 | import scipy as sp 14 | cq=pd.read_pickle('c:/temp/TORQcq.pkl') 15 | x=cq[cq.index=='MO'] 16 | spread=sp.mean(x.ofr-x.bid) 17 | rel_spread=sp.mean(2*(x.ofr-x.bid)/(x.ofr+x.bid)) 18 | print(round(spread,5) ) 19 | print(round(rel_spread,5) ) 20 | -------------------------------------------------------------------------------- /Chapter13/c13_20_graph_term_structure.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c13_20_graph_term_structure.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 2/27/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import matplotlib.pyplot as plt 12 | time=[3./12.,6./12.,2.,3.,5.,10.,30.] 13 | rate=[0.49,0.51,1.18,1.46,1.89,2.40,3.0] 14 | plt.title("Term Structure of Interest Rate ") 15 | plt.xlabel("Time (in years) ") 16 | plt.ylabel("Risk-free rate (%)") 17 | plt.plot(time,rate) 18 | plt.show() 19 | -------------------------------------------------------------------------------- /Chapter04/c4_09_get_return_only.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_09_get_return_only.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | ticker='IBM' 14 | begdate=(2015,1,1) 15 | enddate=(2015,11,9) 16 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 17 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[:1] 18 | -------------------------------------------------------------------------------- /Chapter06/c6_29_save_text_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_29_save_text_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import re 13 | ticker='msft' 14 | f=open("c:/temp/msft.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f.write(str(p)) 19 | f.close() 20 | -------------------------------------------------------------------------------- /Chapter11/c11_12_normal_random.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_12_normal_random.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | from scipy import stats,random 13 | # 14 | np.random.seed(12345) 15 | n=5000000 16 | 17 | ret = random.normal(0,1,n) 18 | print('mean =', np.mean(ret)) 19 | print('std =',np.std(ret)) 20 | print('skewness=',stats.skew(ret)) 21 | print('kurtosis=',stats.kurtosis(ret)) 22 | -------------------------------------------------------------------------------- /Chapter09/c9_99_01_generate_stockMonthly_pkl.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_99_01_generate_stockMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | 13 | x=pd.read_csv("c:/temp/stockMonthly2.csv") 14 | #y=pd.DataFrame(x) 15 | x.columns=['PERMNO','DATE','RETURN','VOLUME','PRICE','SHARESOUTSTNDING'] 16 | #print(y.head()) 17 | #print(y.tail()) 18 | x.to_pickle('c:/temp/stockMonthly.pkl') 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter10/c10_02_foreign_exchange_futures.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_02_foreigh_exchange_futures.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | amount=5 14 | r_foreign=0.02 15 | T=3./12. 16 | exchangeRateToday=1.25 17 | poundToday=5*sp.exp(-r_foreign*T) 18 | print("Pound needed today=", poundToday) 19 | usToday=exchangeRateToday*poundToday 20 | print("US dollar needed today", usToday) 21 | 22 | -------------------------------------------------------------------------------- /Chapter10/c10_04_payoff_call_graph.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_04_payoff_call_graph.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import matplotlib.pyplot as plt 13 | s = np.arange(10,80,5) 14 | x=30 15 | payoff=(abs(s-x)+s-x)/2 16 | plt.ylim(-10,50) 17 | plt.plot(s,payoff) 18 | plt.title("Payoff for a call (x=30)") 19 | plt.xlabel("stock price") 20 | plt.ylabel("Payoff of a call") 21 | plt.show() 22 | -------------------------------------------------------------------------------- /Chapter08/c8_06_get_daily_data_from_Google.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_06_get_daily_data_from_Google.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas_datareader.data as web 12 | import datetime 13 | 14 | ticker='MSFT' 15 | begdate = datetime.datetime(2012, 1, 2) 16 | enddate = datetime.datetime(2017, 1, 10) 17 | 18 | a = web.DataReader(ticker, 'google',begdate,enddate) 19 | 20 | print(a.head(3)) 21 | print(a.tail(2)) -------------------------------------------------------------------------------- /Chapter12/c12_03_graph_standard_normal_dist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_02_graph_standard_noral_dist.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import scipy.stats as stats 13 | import matplotlib.pyplot as plt 14 | x = sp.arange(-3,3,0.01) 15 | y=stats.norm.pdf(x) 16 | plt.plot(x,y) 17 | plt.title("A standard normal distribution") 18 | plt.xlabel('x') 19 | plt.ylabel('y') 20 | plt.show() 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter01/c1_17_to_letter_grade.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_17_to_letter_grade.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | grade=87 12 | 13 | if grade>=90: 14 | print('A') 15 | elif grade >=85: 16 | print('A-') 17 | elif grade >=80: 18 | print('B+') 19 | elif grade >=75: 20 | print('B') 21 | elif grade >=70: 22 | print('B-') 23 | elif grade>=65: 24 | print('C+') 25 | else: 26 | print('D') -------------------------------------------------------------------------------- /Chapter06/c6_10_save_price_data_from_Yahoo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_10_save_price_data_from_Yahoo.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import re 13 | ticker='msft' 14 | f=open("c:/temp/msft3.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f.write(str(p)) 19 | f.close() 20 | -------------------------------------------------------------------------------- /Chapter07/c7_11_dot_diff_and_dot_shift_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_11_dot_diff_and_dot_shift_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import pandas as pd 13 | price=[10,11,12.2,14.0,12] 14 | x=pd.DataFrame({'Price':price}) 15 | x['diff']=x.diff() 16 | x['Ret']=x['Price'].diff()/x['Price'].shift(1) 17 | x['RetLag']=x['Ret'].shift(1) 18 | x['RetLead']=x['Ret'].shift(-1) 19 | print(x) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter08/c8_99_01_generate_ffDaily_txt.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffDaily.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(5,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0], format='%Y%m%d').date()) 13 | for j in range(1,5): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/4,4]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RF']) 19 | ff.to_pickle("c:/temp/ffDaily.pkl") 20 | 21 | -------------------------------------------------------------------------------- /Chapter08/c8_02_get_date_varible_using_pandasDataFrame.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_02_get_date_variable.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | 14 | sp.random.seed(1257) 15 | mean=0.10 16 | std=0.2 17 | ddate = pd.date_range('1/1/2016', periods=252) 18 | n=len(ddate) 19 | rets=sp.random.normal(mean,std,n) 20 | data = pd.DataFrame(rets, index=ddate,columns=['RET']) 21 | print(data.head()) 22 | -------------------------------------------------------------------------------- /Chapter10/c10_03_exchange_futures.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c10_03_exchange_futures.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | def futuresExchangeRate(s0,rateDomestic,rateForeign,T): 14 | futureEx=s0*sp.exp((rateDomestic-rateForeign)*T) 15 | return futureEx 16 | 17 | s0=1.25 18 | rHome=0.01 19 | rForeigh=0.02 20 | T=3./12. 21 | futures=futuresExchangeRate(s0,rHome,rForeigh,T) 22 | print("futures=",futures) 23 | -------------------------------------------------------------------------------- /Chapter06/c6_11_save_csv_file.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_11_save_csv_file.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 12 | import csv 13 | f=open("c:/temp/c.csv","w") 14 | 15 | ticker='c' 16 | begdate=(2016,1,1) 17 | enddate=(2017,1,9) 18 | p = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 19 | 20 | writer = csv.writer(f) 21 | writer.writerows(p) 22 | f.close() 23 | -------------------------------------------------------------------------------- /Chapter07/c7_100_generate_ffMonthly_txt.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffMonthly.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(4,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 13 | for j in range(1,5): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/4,4]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RF']) 19 | ff.to_pickle("c:/temp/ffMonthly.pkl") 20 | 21 | -------------------------------------------------------------------------------- /Chapter07/c7_25_generate_ffcMonthly_pkl.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_25_generateffcMonthly_pkl.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 13 | print(ff.head(2)) 14 | 15 | mom=pd.read_pickle("c:/temp/ffMomMonthly.pkl") 16 | print(mom.head(3)) 17 | 18 | x=pd.merge(ff,mom,left_index=True,right_index=True) 19 | print(x.head()) 20 | 21 | x.to_pickle("c:/temp/ffcMonthly.pkl") 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter12/c12_33_generateSobol_pkl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c12_33_generateSobol.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import sobol_seq 14 | import scipy as sp 15 | import pandas as pd 16 | a=[] 17 | n=1000 18 | for i in sp.arange(n): 19 | t=sobol_seq.i4_sobol(1,i) 20 | a.append(t) 21 | print(a[0:10]) 22 | b=pd.DataFrame(a,columns=['Sobol','b']) 23 | sobol=b['Sobol'] 24 | sobol.to_pickle("e:/sobol.pkl") -------------------------------------------------------------------------------- /Chapter07/c7_14_sharpe_ratio_using_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_14_sharpe_ratio_using_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | df=pd.read_pickle("c:/temp/yanMonthly.pkl") 13 | rf=0.01 14 | ibm=df[df.index=='IBM'] 15 | ibm['RET']=ibm['VALUE'].diff()/ibm['VALUE'].shift(1) 16 | 17 | ret=ibm['RET'] 18 | sharpe=sp.mean((ret)-rf)/sp.std(ret) 19 | print(sharpe) 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter11/c11_18_sort_pandas.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c11_18_sort_pandas.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import pandas as pd 14 | a = pd.DataFrame([[9,4],[9,2],[1,-1]],columns=['A','B']) 15 | print(a) 16 | # sort by A ascedning, then B descending 17 | b= a.sort_values(['A', 'B'], ascending=[1, 0]) 18 | print(b) 19 | # sort by A and B, both ascedning 20 | c= a.sort_values(['A', 'B'], ascending=[1, 1]) 21 | print(c) -------------------------------------------------------------------------------- /Chapter12/c12_32_scatter_sobol.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_32_scatter_sobol.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import sobol_seq 13 | import scipy as sp 14 | import matplotlib.pyplot as plt 15 | a=[] 16 | n=100 17 | for i in sp.arange(2*n): 18 | t=sobol_seq.i4_sobol(1,i) 19 | a.append(t) 20 | print(a[0:10]) 21 | # 22 | x=sp.random.permutation(a[:n]) 23 | y=sp.random.permutation(a[n:]) 24 | plt.scatter(x,y,edgecolors='r') 25 | plt.show() -------------------------------------------------------------------------------- /Chapter01/c1_21_read_ffMonthly_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_21_read_ffMonthly_data.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | import pandas as pd 13 | file=open("c:/temp/ffMonthly.txt","r") 14 | data=file.readlines() 15 | f=[] 16 | index=[] 17 | for i in range(1,np.size(data)): 18 | t=data[i].split() 19 | index.append(int(t[0])) 20 | for j in range(1,5): 21 | k=float(t[j]) 22 | f.append(k/100) -------------------------------------------------------------------------------- /Chapter06/c6_14_save_Excel_file_index_false.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_14_get_sp500.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import re 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | ticker='^GSPC' 15 | begdate=(2013,1,1) 16 | enddate=(2013,11,9) 17 | df = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | f=open("c:/temp/sp500.txt","w") 19 | f.write(str(df)) 20 | f.close() 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter07/c7_102_generate_ffMonthly5.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | import pandas as pd 4 | import scipy as sp 5 | import numpy as np 6 | file=open("c:/temp/ffMonthly5.txt","r") 7 | data=file.readlines() 8 | f=[] 9 | dd=[] 10 | for i in range(4,sp.size(data)): 11 | t=data[i].split() 12 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 13 | for j in range(1,7): 14 | k=float(t[j]) 15 | f.append(k/100) 16 | n=len(f) 17 | f1=np.reshape(f,[n/6,6]) 18 | ff=pd.DataFrame(f1,index=dd,columns=['MKT_RF','SMB','HML','RMW','CMA','RF']) 19 | ff.to_pickle("c:/temp/ffMonthly5.pkl") 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter10/c10_43_EW_port.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_43_EW_port.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | 14 | ret_A=np.array([0.102,-0.02, 0.213,0.12,0.13]) 15 | ret_B=np.array([0.1062,0.23, 0.045,0.234,0.113]) 16 | 17 | port_EW=(ret_A+ret_B)/2 18 | 19 | round(np.mean(ret_A),3),round(np.mean(ret_B),3),round(np.mean(port_EW),3) 20 | 21 | round(np.std(ret_A),3),round(np.std(ret_B),3),round(np.std(port_EW),3) 22 | -------------------------------------------------------------------------------- /Chapter06/c6_02_random_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_02_random_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import stats 13 | import scipy as sp 14 | sp.random.seed(12456) 15 | alpha=1.0 16 | beta=0.8 17 | n=100 18 | x=sp.arange(n) 19 | y=alpha+beta*x+sp.random.rand(n) 20 | (beta, alpha, r_value, p_value, std_err) = stats.linregress(y,x) 21 | print(alpha,beta) 22 | print("R-squared=", r_value**2) 23 | print("p-value =", p_value) 24 | -------------------------------------------------------------------------------- /Chapter07/c7_06_3factors_IBMno_meaning.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_06_3factor_IBMno_meaning.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | import numpy as np 12 | import statsmodels.api as sm 13 | 14 | inFile='http://canisius.edu/~yany/data/ibm.csv' 15 | df = pd.read_csv(inFile, index_col=0) 16 | x = df[['Open', 'High', 'Volume']] 17 | y = df['Adj.Close'] 18 | x = sm.add_constant(x) 19 | result = sm.OLS(y, x).fit() 20 | print(result.summary()) 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter09/c9_02_matrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_02_matrix.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | ret=np.matrix(np.array([[0.1,0.2],[0.10,0.1071],[-0.02,0.25],[0.012,0.028],[0.06,0.262],[0.14,0.115]])) 13 | print("return matrix") 14 | print(ret) 15 | covar=ret.T*ret 16 | print("covar") 17 | print(covar) 18 | weight=np.matrix(np.array([0.4,0.6])) 19 | print("weight ") 20 | print(weight) 21 | print("mean return") 22 | print(weight*covar*weight.T) 23 | -------------------------------------------------------------------------------- /Chapter12/c12_12_radnomly_choose_m_from_n_stocks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_12_randomly_choose_m_from_n_stocks.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | n_stocks_available=500 13 | n_stocks=20 14 | sp.random.seed(123345) 15 | x=sp.random.uniform(low=1,high=n_stocks_available,size=n_stocks) 16 | y=[] 17 | for i in range(n_stocks): 18 | y.append(int(x[i])) 19 | #print y 20 | final=sp.unique(y) 21 | print(final) 22 | print(len(final)) 23 | -------------------------------------------------------------------------------- /Chapter01/c1_23_read_stock_data_and_save_it.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_23_read_stock_data_and_save_it.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import re 12 | from matplotlib.finance import quotes_historical_yahoo_ochl 13 | ticker='dell' 14 | outfile=open("c:/temp/dell.txt","w") 15 | begdate=(2013,1,1) 16 | enddate=(2016,11,9) 17 | p=quotes_historical_yahoo_ochl(ticker,begdate,enddate,asobject=True,adjusted=True) 18 | outfile.write(str(p)) 19 | outfile.close() -------------------------------------------------------------------------------- /Chapter01/c1_10_while_loop_2IRRs.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c1_09_while_loop_2IRRs.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | def npv_f(rate, cashflows): 12 | total = 0.0 13 | for i in range(0,len(cashflows)): 14 | total += cashflows[i] / (1 + rate)**i 15 | return total 16 | # 17 | cashFlows=(550,-500,-500,-500,1000) 18 | r=0 19 | while(r<1.0): 20 | r+=0.000001 21 | npv=npv_f(r,cashFlows) 22 | if(abs(npv)<=0.0001): 23 | print(r) -------------------------------------------------------------------------------- /Chapter08/c8_20_Durbin_Watson_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_20_Durbin_Watson_test.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import statsmodels.stats.stattools as tools 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='IBM' 15 | begdate=(2012,1,2) 16 | enddate=(2016,12,31) 17 | data= getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | p=data.aclose 19 | ret=p[:1]/p[1:]-1 20 | 21 | print(tools.durbin_watson(ret)) 22 | -------------------------------------------------------------------------------- /Chapter08/c8_35_pandas_OLS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_35_Pandas_OLS.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | from datetime import datetime 14 | n = 252 15 | np.random.seed(12345) 16 | begdate=datetime(2013, 1, 2) 17 | dateRange = pd.date_range(begdate, periods=n) 18 | x0= pd.DataFrame(np.random.randn(n, 1),columns=['ret'],index=dateRange) 19 | y0=pd.Series(np.random.randn(n), index=dateRange) 20 | print pd.ols(y=y0, x=x0) 21 | -------------------------------------------------------------------------------- /Chapter09/c9_03_optimization.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_03_optimization.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import optimize 13 | import matplotlib.pyplot as plt 14 | # 15 | # define a function 16 | def f(x): 17 | return 3.4-2*np.exp(-(x - 0.8)**2) 18 | # 19 | # see the plot 20 | x=np.arange(-3,3,0.1) 21 | y=f(x) 22 | plt.plot(x,y) 23 | plt.show() 24 | 25 | # find the miniumu 26 | solution= optimize.brent(f) 27 | print(solution) 28 | 29 | -------------------------------------------------------------------------------- /Chapter15/c15_01_vol_IBM.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c15_01_vol_IBM.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='IBM' 15 | begdate=(2009,1,1) 16 | enddate=(2013,12,31) 17 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | ret = p.aclose[1:]/p.aclose[:-1]-1 19 | std_annual=np.std(ret)*np.sqrt(252) 20 | print('volatility (std)=',round(std_annual,4)) 21 | 22 | -------------------------------------------------------------------------------- /Chapter10/c10_10_target_beta_portfolio_hedging.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_10_target_beta_portfolio_hedging.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as ps 11 | # input area 12 | todaySP500index=2297.42 13 | valuePortfolio=50e6 14 | betaPortfolio=1.1 15 | betaTarget=0 16 | 17 | priceEachPoint=250 18 | contractFuturesSP500=todaySP500index*priceEachPoint 19 | n=(betaTarget-betaPortfolio)*valuePortfolio/contractFuturesSP500 20 | print("number of contracts SP500 futures=",n) 21 | -------------------------------------------------------------------------------- /Chapter07/c7_39_LPSD.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_39_LPSD.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | import scipy as sp 13 | import numpy as np 14 | 15 | mean=0.10; 16 | Rf=0.02 17 | std=0.20 18 | n=100 19 | sp.random.seed(12456) 20 | x=sp.random.normal(loc=mean,scale=std,size=n) 21 | print("std=", sp.std(x)) 22 | 23 | y=x[x-Rf<0] 24 | m=len(y) 25 | total=0.0 26 | 27 | for i in sp.arange(m): 28 | total+=(y[i]-Rf)**2 29 | 30 | LPSD=total/(m-1) 31 | print("y=",y) 32 | print("LPSD=",LPSD) -------------------------------------------------------------------------------- /Chapter06/c6_01_learn_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_01_learn_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import stats 13 | stock_ret = [0.065, 0.0265, -0.0593, -0.001,0.0346] 14 | mkt_ret = [0.055, -0.09, -0.041,0.045,0.022] 15 | (beta, alpha, r_value, p_value, std_err) = stats.linregress(stock_ret,mkt_ret) 16 | #result=stats.linregress(stock_ret,mkt_ret) 17 | 18 | print(beta, alpha) 19 | print("R-squared=", r_value**2) 20 | print("p-value =", p_value) 21 | -------------------------------------------------------------------------------- /Chapter07/c7_04_3factors_model.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_04_3factor_model.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import numpy as np 13 | import statsmodels.api as sm 14 | 15 | inFile='http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv' 16 | df_adv = pd.read_csv(inFile, index_col=0) 17 | X = df_adv[['TV', 'Radio', 'Newspaper']] 18 | y = df_adv['Sales'] 19 | df_adv.head() 20 | X = sm.add_constant(X) 21 | result = sm.OLS(y, X).fit() 22 | print(result.summary()) 23 | 24 | 25 | -------------------------------------------------------------------------------- /Chapter08/c8_18_ttest_IBM_2013.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_18_ttest_IBM_2013.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | import scipy as sp 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | ticker='ibm' 15 | begdate=(2013,1,1) 16 | enddate=(2013,12,31) 17 | p=getData(ticker,begdate,enddate,asobject=True, adjusted=True) 18 | ret=p.aclose[1:]/p.aclose[:-1]-1 19 | print(' Mean T-value P-value ' ) 20 | print(round(sp.mean(ret),5), stats.ttest_1samp(ret,0)) 21 | -------------------------------------------------------------------------------- /Chapter11/c11_03_standard_normal_dis.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_03_standard_normal_dist.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import scipy.stats as stats 12 | x = sp.arange(-3,3,0.01) 13 | ret=stats.norm.pdf(x) 14 | confidence=0.99 15 | position=10000 16 | z=stats.norm.ppf(1-confidence) 17 | print("z=",z) 18 | zES=-stats.norm.pdf(z)/(1-confidence) 19 | print("zES=", zES) 20 | std=sp.std(ret) 21 | VaR=position*z*std 22 | print("VaR=",VaR) 23 | ES=position*zES*std 24 | print("ES=",ES) 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter12/c12_27_random_numbers_from_three_distributions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_27_random_numbers_from_three_distributions.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import scipy.stats as stats 13 | sp.random.seed(123) 14 | u=stats.uniform(-1,1).rvs() 15 | n=stats.norm(500,150).rvs() 16 | b=stats.binom(10000,0.1).rvs() 17 | x='random number from a ' 18 | print(x+"uniform distribution ",u) 19 | print(x+" normal distribution ",n) 20 | print(x+" binomial distribution",b) 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter12/c12_04_histogram.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_03_histogram.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import matplotlib.pyplot as plt 13 | # 14 | sp.random.seed(12345) 15 | mean=0.1 16 | std=0.2 17 | n=1000 18 | x=sp.random.normal(mean,std,n) 19 | plt.hist(x, 15, normed=True) 20 | plt.title("Histogram for random numbers drawn from a normal distribution") 21 | plt.annotate("mean="+str(mean),xy=(0.6,1.5)) 22 | plt.annotate("std="+str(std),xy=(0.6,1.4)) 23 | plt.show() 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter10/c10_32_implied_vol_EuropeanCall.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_32_implied_vol_EuropeanCall.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | from scipy import log,exp,sqrt,stats 11 | 12 | def implied_vol_call(S,X,T,r,c): 13 | for i in range(200): 14 | sigma=0.005*(i+1) 15 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 16 | d2 = d1-sigma*sqrt(T) 17 | diff=c-(S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)) 18 | if abs(diff)<=0.01: 19 | return i,sigma, diff 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter03/c3_04_appendix_E_more.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c3_04_appendixE.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | from matplotlib.pyplot import * 14 | cashflows=[-120,50,60,70] 15 | rate=[] 16 | npv=[] 17 | x=(0,0.7) 18 | y=(0,0) 19 | for i in range(1,70): 20 | rate.append(0.01*i) 21 | npv.append(sp.npv(0.01*i,cashflows)) 22 | 23 | title("NPV profile") 24 | xlabel("Discount Rate") 25 | ylabel("NPV (Net Present Value)") 26 | plot(rate,npv) 27 | plot(x,y) 28 | show() 29 | -------------------------------------------------------------------------------- /Chapter08/c8_26_test_daily_mean_is_zero.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_26_test_daily_mean_is_zero.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='ibm' 15 | begdate=(2013,1,1) 16 | enddate=(2013,12,31) 17 | p=getData(ticker,begdate,enddate,asobject=True, adjusted=True) 18 | ret=p.aclose[1:]/p.aclose[:-1]-1 19 | print(' Mean T-value P-value ' ) 20 | print(round(sp.mean(ret),5), stats.ttest_1samp(ret,0)) 21 | -------------------------------------------------------------------------------- /Chapter10/c10_34_binary_search.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c10_34_binary_search.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | def binary_search(x, target, my_min=1, my_max=None): 13 | if my_max is None: 14 | my_max = len(x) - 1 15 | while my_min <= my_max: 16 | mid = (my_min + my_max)//2 17 | midval = x[mid] 18 | if midval < target: 19 | my_min = my_mid + 1 20 | elif midval > target: 21 | my_max = mid - 1 22 | else: 23 | return mid 24 | raise ValueError 25 | 26 | -------------------------------------------------------------------------------- /Chapter07/c7_03_random_OLS.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c7_03_random_OLS.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import scipy as sp 14 | import statsmodels.regression.linear_model as sm 15 | 16 | n=100 17 | sp.random.seed(12345) 18 | 19 | y=[1,2,3,4,2,3,4] 20 | x1=range(1,8) 21 | x2=[4,2,-1,4,2,3,5] 22 | x3=[0,2,3,4,2,4,-1] 23 | x=[x1,x2,x3] 24 | x=sm.add_constant(x) 25 | #est = sm.OLS(formula='Sales ~ TV + Radio', data=df_adv).fit() 26 | results=sm.OLS(y,x1).fit() 27 | print(results.summary()) 28 | -------------------------------------------------------------------------------- /Chapter07/c7_01_3factor_model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c7_01_3factor_model.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | 14 | from scipy import stats 15 | from pandas.stats.api import ols 16 | import pandas as pd 17 | y = [0.065, 0.0265, -0.0593, -0.001,0.0346] 18 | x1 = [0.055, -0.09, -0.041,0.045,0.022] 19 | x2 = [0.025, 0.10, 0.021,0.145,0.012] 20 | x3= [0.015, -0.08, 0.341,0.245,-0.022] 21 | 22 | df=pd.DataFrame({"y":y,"x1":x1, 'x2':x2,'x3':x3}) 23 | result=ols(y=df['y'],x=df[['x1','x2','x3']]) 24 | print(result) 25 | -------------------------------------------------------------------------------- /Chapter08/c8_27_test_equal_variances.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_37_test_equal_variance.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | begdate=(2012,1,1) 14 | enddate=(2016,12,31) 15 | def ret_f(ticker,begdate,enddate): 16 | p = getData(ticker,begdate, enddate,asobject=True,adjusted=True) 17 | return p.aclose[1:]/p.aclose[:-1]-1 18 | 19 | y=ret_f('IBM',begdate,enddate) 20 | x=ret_f('DELL',begdate,enddate) 21 | print(sp.stats.bartlett(x,y)) 22 | -------------------------------------------------------------------------------- /Chapter09/c9_22_LPSD_f.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_22_LPSD.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | 12 | 13 | import scipy as sp 14 | import numpy as np 15 | 16 | mean=0.15; 17 | Rf=0.01 18 | std=0.20 19 | n=200 20 | sp.random.seed(3412) 21 | x=sp.random.normal(loc=mean,scale=std,size=n) 22 | 23 | 24 | def LPSD_f(returns, Rf): 25 | y=returns[returns-Rf<0] 26 | m=len(y) 27 | total=0.0 28 | for i in sp.arange(m): 29 | total+=(y[i]-Rf)**2 30 | return total/(m-1) 31 | 32 | answer=LPSD_f(x,Rf) 33 | print("LPSD=",answer) 34 | -------------------------------------------------------------------------------- /Chapter10/c10_21_CRR_01.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c10_21_CRR_01.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import matplotlib.pyplot as plt 14 | plt.xlim(0,1) 15 | plt.figtext(0.18,0.5,'S') 16 | plt.figtext(0.6,0.5+0.25,'Su') 17 | plt.figtext(0.6,0.5-0.25,'Sd') 18 | 19 | plt.annotate('',xy=(0.6,0.5+0.25), xytext=(0.1,0.5), arrowprops=dict(facecolor='b',shrink=0.01)) 20 | plt.annotate('',xy=(0.6,0.5-0.25), xytext=(0.1,0.5), arrowprops=dict(facecolor='b',shrink=0.01)) 21 | plt.axis('off') 22 | plt.show() 23 | 24 | 25 | -------------------------------------------------------------------------------- /Chapter02/c2_99_interplate_not_working.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c2_04_interplate_not_worling.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | # 14 | np.random.seed(123) 15 | x=np.arange(1, 3, .25)**2 16 | n=np.size(x) 17 | y = pd.Series(x + np.random.randn(n)) 18 | 19 | bad = np.array([4, 13, 14, 15, 16, 20, 30]) 20 | 21 | x[bad] = np.nan 22 | methods = ['linear', 'quadratic', 'cubic'] 23 | df = pd.DataFrame({m: x.interpolate(method=m) for m in methods}) 24 | #df=x.interpolate(method="linear") 25 | df.plot() 26 | 27 | -------------------------------------------------------------------------------- /Chapter15/c15_02_normalityTests.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c15_02_normalityTests.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='IBM' 16 | begdate=(2009,1,1) 17 | enddate=(2013,12,31) 18 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 19 | ret = p.aclose[1:]/p.aclose[:-1]-1 20 | # 21 | print('ticker=',ticker,'W-test, and P-value') 22 | print(stats.shapiro(ret)) 23 | 24 | 25 | print(stats.anderson(ret)) -------------------------------------------------------------------------------- /Chapter07/c7_40_generate_usCPImonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_40_generate_usCPImonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | # 13 | x=pd.read_csv("c:/temp/CPI_19jan2017.csv",skiprows=8) 14 | n=len(x) 15 | 16 | ddate=[] 17 | cpi0=[] 18 | k=1 19 | for i in sp.arange(n): 20 | y=sp.array(x[i:(i+1)]) 21 | for j in sp.arange(12): 22 | ddate.append(y[0,0]*100+j+1) 23 | cpi0.append(y[0,j+1]/100) 24 | #print(y) 25 | 26 | cpi=pd.DataFrame(cpi0,index=ddate) 27 | cpi.to_pickle("c:/temp/usCPImonthly.pkl") -------------------------------------------------------------------------------- /Chapter10/c10_35_put_call_ratio.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_35_put_call_ratio.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | from matplotlib.pyplot import * 13 | # 14 | infile='c:/temp/totalpc.csv' 15 | data=pd.read_csv(infile,skiprows=2,index_col=0,parse_dates=True) 16 | data.columns=('Calls','Puts','Total','Ratio') 17 | x=data.index 18 | y=data.Ratio 19 | y2=sp.ones(len(y)) 20 | title('Put-call ratio') 21 | xlabel('Date') 22 | ylabel('Put-call ratio') 23 | ylim(0,1.5) 24 | plot(x, y, 'b-') 25 | plot(x, y2,'r') 26 | show() -------------------------------------------------------------------------------- /Chapter11/c11_10_normality_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_10_normality_test.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='IBM' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | # 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | print( stats.anderson(ret) ) -------------------------------------------------------------------------------- /Chapter07/c7_16_sharpe_ratio_YahooData.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c7_16_sharpe_ratio_YahooData.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import scipy as sp 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | 15 | begdate=(2012,1,1) 16 | enddate=(2016,12,31) 17 | 18 | def ret_f(ticker,begdate,enddate): 19 | p = getData(ticker,begdate, enddate,asobject=True,adjusted=True) 20 | return(p.aclose[1:]/p.aclose[:-1]-1) 21 | 22 | y=ret_f('IBM',begdate,enddate) 23 | sharpe=sp.mean(y)/sp.std(y) 24 | print(sharpe) -------------------------------------------------------------------------------- /Chapter07/c7_24_generate_ffmonMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_24_generateffmonMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | import numpy as np 14 | file=open("c:/temp/ffMom.txt","r") 15 | data=file.readlines() 16 | 17 | f=[] 18 | dd=[] 19 | n=sp.size(data)-1 20 | for i in sp.arange(14,n): 21 | t=data[i].split() 22 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 23 | f.append(float(t[1])/100) 24 | 25 | mom=pd.DataFrame(f,index=dd,columns=['MOM']) 26 | mom.to_pickle("c:/temp/ffMomMonthly.pkl") 27 | -------------------------------------------------------------------------------- /Chapter09/c9_14_get_IBM_ret_from_yanMonthly.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_14_get_IBM_from_yanMonthly.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | import pandas as pd 13 | import numpy as np 14 | n_stocks=10 15 | x=pd.read_pickle('c:/temp/yanMonthly.pkl') 16 | 17 | def ret_f(ticker): 18 | a=x[x.index==ticker] 19 | p=sp.array(a['VALUE']) 20 | ddate=a['DATE'] 21 | ret=p[1:]/p[:-1]-1 22 | output=pd.DataFrame(ret,index=ddate[1:]) 23 | output.columns=[ticker] 24 | return output 25 | 26 | ret=ret_f('IBM') 27 | print(ret.head()) 28 | 29 | -------------------------------------------------------------------------------- /Chapter07/c7_101_generate_ffcMonthly.py: -------------------------------------------------------------------------------- 1 | # still one issue index should be the date!!!! 2 | 3 | 4 | 5 | import pandas as pd 6 | import scipy as sp 7 | import numpy as np 8 | file=open("c:/temp/ffMom.txt","r") 9 | data=file.readlines() 10 | 11 | f=[] 12 | dd=[] 13 | n=sp.size(data)-1 14 | for i in sp.arange(14,n): 15 | t=data[i].split() 16 | dd.append(pd.to_datetime(t[0]+'01', format='%Y%m%d').date()) 17 | f.append(float(t[1])/100) 18 | 19 | 20 | mom=pd.DataFrame(f,index=dd,columns=['MOM']) 21 | import pandas as pd 22 | ff3=pd.read_pickle('c:/temp/ffMonthly.pkl') 23 | ff3['DATE']=ff3.index 24 | mom['DATE']=mom.index 25 | a=pd.merge(ff3,mom) 26 | ffc=pd.DataFrame(a[['DATE','MKT_RF','SMB','HML','MOM','RF']]) 27 | ffc.to_pickle("c:/temp/ffcMonthly.pkl") 28 | -------------------------------------------------------------------------------- /Chapter07/c7_32_merge_02_different_names.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_32_mrege_different_names.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 14 | 'IBM': [0.2, -0.3, 0.13, -0.2], 15 | 'WMT': [0.1, 0, 0.05, 0.23]}) 16 | y = pd.DataFrame({'date': [2011,2013,2014, 2015], 17 | 'C': [0.12, 0.23, 0.11, -0.1], 18 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 19 | print(pd.merge(x,y, left_on='YEAR',right_on='date')) 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter07/c7_33_merge_03_left_index.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_33_merge_03_lef_right_index.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import scipy as sp 13 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 14 | 'IBM': [0.2, -0.3, 0.13, -0.2], 15 | 'WMT': [0.1, 0, 0.05, 0.23]}) 16 | y = pd.DataFrame({'date': [2011,2013,2014, 2015], 17 | 'C': [0.12, 0.23, 0.11, -0.1], 18 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 19 | print(pd.merge(x,y, right_index=True,left_index=True)) 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Chapter10/c10_31_plot_call_vs_one_input.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c10_31_plot_call_vs_one_inut.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import p4f as pf 14 | import matplotlib.pyplot as plt 15 | s0=30;T0=0.5;sigma0=0.2;r0=0.05;x0=30 16 | sigma=np.arange(0.05,0.8,0.05) 17 | T=np.arange(0.5,2.0,0.5) 18 | call_0=pf.bs_call(s0,x0,T0,r0,sigma0) 19 | call_sigma=pf.bs_call(s0,x0,T0,r0,sigma) 20 | call_T=pf.bs_call(s0,x0,T,r0,sigma0) 21 | plt.plot(sigma,call_sigma,'b') 22 | plt.plot(T,call_T) 23 | plt.show() 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chapter11/c11_09_normaility_test_msft.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c11_09_normality_test_MSFT.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import stats 13 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 14 | # 15 | ticker='MSFT' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | # 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | print( stats.anderson(ret)) 24 | 25 | -------------------------------------------------------------------------------- /Chapter11/c11_20_VaR_for_5industry_portfolo_ff.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c11_20_VaR_for_5_industry_portfolio.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import scipy as sp 12 | import pandas as pd 13 | from scipy.stats import norm 14 | 15 | confidence_level=0.99 # input 3 16 | z=norm.ppf(confidence_level) 17 | position=(1,1,1,1,1) 18 | 19 | x=pd.read_pickle("c:/temp/ff5VWindustryMonthly.pkl") 20 | #print(x.head(1)) 21 | mean=sp.mean(x,axis=0) 22 | std=sp.std(x,axis=0) 23 | 24 | t=sp.dot(position,z) 25 | VaR=t*std 26 | print("VaR=",VaR) 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chapter14/c14_01_callandPut.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c14_01_ccallAndPut.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from scipy import log,exp,sqrt,stats 13 | def callAndPut(S,X,T,r,sigma,type='C'): 14 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 15 | d2 = d1-sigma*sqrt(T) 16 | if type.upper()=='C': 17 | c=S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2) 18 | return c 19 | else: 20 | p=X*exp(-r*T)*stats.norm.cdf(-d2)-S*stats.norm.cdf(-d1) 21 | return p 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chapter08/c8_12_normality_test_for_IBM.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_12_normality_test_for_IBM.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | import numpy as np 14 | 15 | ticker='IBM' 16 | begdate=(2012,1,1) 17 | enddate=(2016,12,31) 18 | 19 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 20 | ret = (p.aclose[1:] - p.aclose[:-1])/p.aclose[1:] 21 | print 'ticker=',ticker,'W-test, and P-value' 22 | print(stats.shapiro(ret)) 23 | 24 | 25 | print( stats.anderson(ret) ) -------------------------------------------------------------------------------- /Chapter09/c9_07_find_minimum_expentional_function.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c9_07_find_minimum_expential_function.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from scipy import optimize 13 | import matplotlib.pyplot as plt 14 | # define a function 15 | a=3.4 16 | b=2.0 17 | c=0.8 18 | def f(x): 19 | return a-b*np.exp(-(x - c)**2) 20 | 21 | x=np.arange(-3,3,0.1) 22 | y=f(x) 23 | plt.title("y=a-b*exp(-(x-c)^2)") 24 | plt.xlabel("x") 25 | plt.ylabel("y") 26 | plt.plot(x,y) 27 | plt.show() 28 | 29 | # find the minimum 30 | solution= optimize.brent(f) 31 | print(solution) 32 | -------------------------------------------------------------------------------- /Chapter12/c12_11_poison_dist.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c12_11_Poison_dist.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import scipy as sp 13 | import matplotlib.pyplot as plt 14 | x=sp.random.poisson(lam=1, size=100) 15 | #plt.plot(x,'o') 16 | a = 5. # shape 17 | n = 1000 18 | s = np.random.power(a, n) 19 | count, bins, ignored = plt.hist(s, bins=30) 20 | x = np.linspace(0, 1, 100) 21 | y = a*x**(a-1.) 22 | normed_y = n*np.diff(bins)[0]*y 23 | plt.title("Poisson distribution") 24 | plt.ylabel("y") 25 | plt.xlabel("x") 26 | plt.plot(x, normed_y) 27 | plt.show() 28 | -------------------------------------------------------------------------------- /Chapter12/c12_20_boots_f_function.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Name : c12_20_boots_f_function.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | import numpy as np 12 | # 13 | def boots_f(data,n_obs,replacement=None): 14 | n=len(data) 15 | if (n>>pv_f(100,0.1,1) 20 | 90.9090909090909 21 | >>>pv_f(r=0.1,fv=100,n=1) 22 | 90.9090909090909 23 | >>>pv_f(n=1,fv=100,r=0.1) 24 | 90.9090909090909 25 | """ 26 | return fv/(1+r)**n -------------------------------------------------------------------------------- /Chapter08/c8_15_merge_ffMonthly_GDP.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_15_merge_ffMonthly_GDP.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import pandas as pd 12 | import pandas_datareader.data as web 13 | import datetime 14 | begdate = datetime.datetime(1900, 1, 1) 15 | enddate = datetime.datetime(2017, 1, 27) 16 | GDP= web.DataReader("GDP", "fred", begdate,enddate) 17 | ff=pd.read_pickle("c:/temp/ffMonthly.pkl") 18 | final=pd.merge(ff,GDP,left_index=True,right_index=True,how='left') 19 | tt=final['GDP'] 20 | GDP2=pd.Series(tt).interpolate() 21 | final['GDP2']=GDP2 22 | #print(GDP.head()) 23 | #print(ff.head()) 24 | print(final.head()) 25 | print(final.tail(10)) 26 | 27 | -------------------------------------------------------------------------------- /Chapter07/c7_31_merge_01.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_31_mrege_01.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import scipy as sp 11 | import pandas as pd 12 | # 13 | x= pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'], 14 | 'A': ['A0', 'A1', 'A2', 'A3'], 15 | 'B': ['B0', 'B1', 'B2', 'B3']}) 16 | y = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K6'], 17 | 'C': ['C0', 'C1', 'C2', 'C3'], 18 | 'D': ['D0', 'D1', 'D2', 'D3']}) 19 | print(sp.shape(x)) 20 | print(sp.shape(y)) 21 | print(x) 22 | print(y) 23 | 24 | result = pd.merge(x,y, on='key') 25 | print(result) 26 | 27 | result2=pd.merge(x,y) 28 | print(result2) 29 | 30 | -------------------------------------------------------------------------------- /Chapter15/c15_04_sp500_4moments.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c15_04_sp500_4moments.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import numpy as np 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | # 14 | ticker='^GSPC' 15 | begdate=(1926,1,1) 16 | enddate=(2013,12,31) 17 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | ret = p.aclose[1:]/p.aclose[:-1]-1 19 | print( 'S&P500 n =',len(ret)) 20 | print( 'S&P500 mean =',round(np.mean(ret),8)) 21 | print( 'S&P500 std =',round(np.std(ret),8)) 22 | print( 'S&P500 skewness=',round(stats.skew(ret),8)) 23 | print( 'S&P500 kurtosis=',round(stats.kurtosis(ret),8)) 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | 42 | # Directories potentially created on remote AFP share 43 | .AppleDB 44 | .AppleDesktop 45 | Network Trash Folder 46 | Temporary Items 47 | .apdisk 48 | -------------------------------------------------------------------------------- /Chapter08/c8_28_52_week_high.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_28_52_week_high.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | from datetime import datetime 13 | from dateutil.relativedelta import relativedelta 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | enddate=datetime(2016,12,31) 18 | # 19 | begdate=enddate-relativedelta(years=1) 20 | p =getData(ticker, begdate, enddate,asobject=True, adjusted=True) 21 | x=p[-1] 22 | y=np.array(p.tolist())[:,-1] 23 | high=max(y) 24 | low=min(y) 25 | print(" Today, Price High Low, % from low ") 26 | print(x[0], x[-1], high, low, round((x[-1]-low)/(high-low)*100,2)) 27 | -------------------------------------------------------------------------------- /Chapter07/c7_32_merge_02_stock.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c7_32_merge_02_stock.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | import pandas as pd 11 | import scipy as sp 12 | x= pd.DataFrame({'YEAR': [2010,2011, 2012, 2013], 13 | 'IBM': [0.2, -0.3, 0.13, -0.2], 14 | 'WMT': [0.1, 0, 0.05, 0.23]}) 15 | y = pd.DataFrame({'YEAR': [2011,2013,2014, 2015], 16 | 'C': [0.12, 0.23, 0.11, -0.1], 17 | 'SP500': [0.1,0.17, -0.05, 0.13]}) 18 | 19 | print(pd.merge(x,y, on='YEAR')) 20 | print(pd.merge(x,y, on='YEAR',how='outer')) 21 | print(pd.merge(x,y, on='YEAR',how='left')) 22 | print(pd.merge(x,y, on='YEAR',how='left')) 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter04/c4_11_daily_ret_to_annual.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c4_11_from_daily_ret_to_annual.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | import numpy as np 13 | import pandas as pd 14 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 15 | # 16 | ticker='IBM' 17 | begdate=(1980,1,1) 18 | enddate=(2012,12,31) 19 | x=getData(ticker,begdate,enddate,asobject=True,adjusted=True) 20 | logret = np.log(x.aclose[1:]/x.aclose[:-1]) 21 | 22 | date=[] 23 | d0=x.date 24 | for i in range(0,np.size(logret)): 25 | date.append(d0[i].strftime("%Y")) 26 | 27 | y=pd.DataFrame(logret,date,columns=['retAnnual']) 28 | ret_annual=np.exp(y.groupby(y.index).sum())-1 29 | -------------------------------------------------------------------------------- /Chapter06/c6_24_bible.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Name : c6_24_bible.py 4 | Book : Python for Finance (2nd ed.) 5 | Publisher: Packt Publishing Ltd. 6 | Author : Yuxing Yan 7 | Date : 6/6/2017 8 | email : yany@canisius.edu 9 | paulyxy@hotmail.com 10 | """ 11 | 12 | from string import maketrans 13 | import pandas as pd 14 | word_freq = {} 15 | infile="c:/temp/AV1611.txt" 16 | word_list = open(infile, "r").read().split() 17 | ttt='!"#$%&()*+,./:;<=>?@[\\]^_`{|}~0123456789' 18 | for word in word_list: 19 | word = word.translate(maketrans("",""),ttt ) 20 | if word.startswith('-'): 21 | word = word.replace('-','') 22 | if len(word): 23 | word_freq[word] = word_freq.get(word, 0) + 1 24 | keys = sorted(word_freq.keys()) 25 | x=pd.DataFrame(keys) 26 | x.to_pickle('c:/temp/uniqueWords.pkl') 27 | 28 | 29 | -------------------------------------------------------------------------------- /Chapter08/c8_16_4moments_forSP500.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_16_4moments_for_sp500.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | import numpy as np 14 | ticker='^GSPC' 15 | begdate=(1926,1,1) 16 | enddate=(2016,12,31) 17 | p = getData(ticker, begdate, enddate,asobject=True, adjusted=True) 18 | ret = p.aclose[1:]/p.aclose[:-1]-1 19 | print( 'S&P500 n =',len(ret)) 20 | print( 'S&P500 mean =',round(np.mean(ret),8)) 21 | print('S&P500 std =',round(np.std(ret),8)) 22 | print('S&P500 skewness=',round(stats.skew(ret),8)) 23 | print('S&P500 kurtosis=',round(stats.kurtosis(ret),8)) 24 | -------------------------------------------------------------------------------- /Chapter06/c6_26_beta_good.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_26_beta_good.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | from scipy import stats 12 | from matplotlib.finance import quotes_historical_yahoo_ochl as getData 13 | begdate=(2012,1,1) 14 | enddate=(2016,12,31) 15 | 16 | ticker='MSFT' 17 | p =getData(ticker, begdate, enddate,asobject=True,adjusted=True) 18 | retIBM = p.aclose[1:]/p.aclose[:1]-1 19 | 20 | ticker='^GSPC' 21 | p2 = getData(ticker, begdate, enddate,asobject=True,adjusted=True) 22 | retMkt = p2.aclose[1:]/p2.aclose[:1]-1 23 | (beta,alpha,r_value,p_value,std_err)=stats.linregress(retMkt,retIBM) 24 | print(alpha,beta) 25 | print("R-squared=", r_value**2) 26 | print("p-value =", p_value) 27 | -------------------------------------------------------------------------------- /Chapter08/c8_36_Fama_Mecbeth_regression.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c8_36_Fama_MecBeth_regression.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import numpy as np 12 | import pandas as pd 13 | import statsmodels.api as sm 14 | from datetime import datetime 15 | # 16 | n = 252 17 | np.random.seed(12345) 18 | begdate=datetime(2013, 1, 2) 19 | dateRange = pd.date_range(begdate, periods=n) 20 | def makeDataFrame(): 21 | data=pd.DataFrame(np.random.randn(n,7),columns=['A','B','C','D','E',' F','G'], 22 | index=dateRange) 23 | return data 24 | # 25 | data = { 'A': makeDataFrame(), 'B': makeDataFrame(), 'C': makeDataFrame() } 26 | Y = makeDataFrame() 27 | print(pd.fama_macbeth(y=Y,x=data)) 28 | -------------------------------------------------------------------------------- /Chapter10/c10_08_arbitrage_argument_exchange_futures.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_08_abtitrage_ragument_exchange_futures.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | import scipy as sp 12 | # 13 | obligationForeign=1.0 # how much to pay in 3 months 14 | f=1.26 # future price 15 | s0=1.25 # today's exchnage rate 16 | rHome=0.01 17 | rForeign=0.02 18 | T=3./12. 19 | 20 | todayObligationForeign=obligationForeign*sp.exp(-rForeign*T) 21 | usBorrow=todayObligationForeign*s0 22 | costDollarBorrow=usBorrow*sp.exp(rHome*T) 23 | 24 | profit=f*obligationForeign-costDollarBorrow 25 | print("profit in USD =", profit) 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Chapter06/c6_16_string_manipulation2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c6_16_string_manipulation2.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | 11 | string='Hellow World!' 12 | 13 | print(string.lower()) 14 | print(string.title()) 15 | print(string.capitalize()) 16 | print(string.swapcase()) 17 | 18 | string2=string.replace("World", "John") 19 | print(string2) 20 | 21 | 22 | # strip() would remove spaces before and the end of string 23 | # lstrip() would remove spaces before and the end of string 24 | # rstrip() would remove spaces before and the end of string 25 | string3=' Hellow World! ' 26 | print(string3) 27 | print(string3.strip()) 28 | print(string3.lstrip()) 29 | print(string3.rstrip()) 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Chapter04/c4_18_federal_fund_rate.py: -------------------------------------------------------------------------------- 1 | # generate ff_monthly.pickle 2 | 3 | """ 4 | Name : c4_28_federal_fund_rate.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | 13 | import pandas as pd 14 | import numpy as np 15 | infile="c:/temp/fedFundRate.csv" 16 | data=pd.read_csv(infile,skiprows=6,header=None) 17 | 18 | #data=pd.read_csv(file,skiprows=3) 19 | dd=rate=[] 20 | n=len(data) 21 | y=np.array(data) 22 | rate=[] 23 | 24 | for i in np.arange(n): 25 | t=y[i][0] 26 | dd.append(pd.to_datetime(t, format='%Y-%m-%d').date()) 27 | rate.append(y[i][1]/100.) 28 | # 29 | fedFundRate=pd.DataFrame(rate,index=dd,columns=['FEDFUNDRATE']) 30 | fedFundRate.to_pickle("c:/temp/fedFundRate.pkl") 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter14/c14_18_down_and_in_put.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c14_18_down_and_in_put.py 3 | Book : Python for Finance 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 3/3/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | def down_and_in_put(s0,x,T,r,sigma,n_simulation,barrier): 11 | n_steps=100. 12 | dt=T/n_steps 13 | total=0 14 | for j in range(0, n_simulation): 15 | sT=s0 16 | in_=False 17 | for i in range(0,int(n_steps)): 18 | e=sp.random.normal() 19 | sT*=sp.exp((r-0.5*sigma*sigma)*dt+sigma*e*sp.sqrt(dt)) 20 | if sT>>myPV(0.1,1,100) 28 | 90.9090909090909 29 | 30 | Example #2 >>>myPV(r=0.1,fv=100,n=1) 31 | 90.9090909090909 32 | """ 33 | import scipy as sp 34 | return(-sp.pv(r,n,0,fv)) -------------------------------------------------------------------------------- /Chapter10/c10_29_fig_good.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | Name : c10_29_fig_good.py 5 | Book : Python for Finance (2nd ed.) 6 | Publisher: Packt Publishing Ltd. 7 | Author : Yuxing Yan 8 | Date : 6/6/2017 9 | email : yany@canisius.edu 10 | paulyxy@hotmail.com 11 | """ 12 | import numpy as np 13 | import scipy as sp 14 | from matplotlib import pyplot as plt 15 | # 16 | z=0.325 # user can change this number 17 | def f(t): 18 | return sp.stats.norm.pdf(t) 19 | plt.ylim(0,0.45) 20 | x = np.arange(-3,3,0.1) 21 | y1=f(x) 22 | plt.plot(x,y1) 23 | x2= np.arange(-4,z,1/40.) 24 | sum=0 25 | delta=0.05 26 | s=np.arange(-10,z,delta) 27 | for i in s: 28 | sum+=f(i)*delta 29 | plt.annotate('area is '+str(round(sum,4)),xy=(-1,0.25),xytext=(-3.8,0.4), arrowprops=dict(facecolor='red',shrink=0.01)) 30 | plt.annotate('z= '+str(z),xy=(z,0.01)) 31 | plt.fill_between(x2,f(x2)) 32 | plt.show() 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /Chapter10/c10_33_implied_vol_EuropeanPut_min.py: -------------------------------------------------------------------------------- 1 | """ 2 | Name : c10_33_implied_vol_EuropeanPut_min.py 3 | Book : Python for Finance (2nd ed.) 4 | Publisher: Packt Publishing Ltd. 5 | Author : Yuxing Yan 6 | Date : 6/6/2017 7 | email : yany@canisius.edu 8 | paulyxy@hotmail.com 9 | """ 10 | from scipy import log,exp,sqrt,stats 11 | 12 | def implied_vol_put_min(S,X,T,r,p): 13 | implied_vol=1.0 14 | min_value=100.0 15 | for i in xrange(1,10000): 16 | sigma=0.0001*(i+1) 17 | d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T)) 18 | d2 = d1-sigma*sqrt(T) 19 | put=X*exp(-r*T)*stats.norm.cdf(-d2)-S*stats.norm.cdf(-d1) 20 | abs_diff=abs(put-p) 21 | if abs_diff